Compare commits
No files matched your search
+138
-52
@@ -1,20 +1,19 @@
|
||||
# Chaîne d'intégration continue de rustscreen.
|
||||
# rustscreen continuous integration.
|
||||
#
|
||||
# Elle tourne sur Gitea, sur le runner `rustscreen-ci`, qui est un hôte et non un
|
||||
# conteneur : la machine n'a pas de démon Docker, mais elle a cargo, node et
|
||||
# nasm. Ce runner est enregistré pour ce dépôt : celui d'Exoledge ne voit que les
|
||||
# jobs de l'organisation Exoledge, et rustscreen vit sous `heap`. Le label est explicite pour qu'un changement d'environnement se voie
|
||||
# dans le diff plutôt qu'en pleine exécution.
|
||||
# It runs on Gitea, on the `rustscreen-ci` runner, which is a host and not a
|
||||
# container: the machine has no Docker daemon, but it has cargo, node and nasm.
|
||||
# This runner is registered for this repository: Exoledge's only sees jobs from
|
||||
# the Exoledge organization, and rustscreen lives under `heap`. The label is
|
||||
# explicit so that an environment change shows up in the diff rather than in
|
||||
# the middle of a run.
|
||||
#
|
||||
# Deux précautions qui coûtent cher quand on les oublie :
|
||||
# Two precautions that cost a lot when forgotten:
|
||||
#
|
||||
# - libvpx n'est pas fourni par le système. `env-libvpx-sys` exige un préfixe
|
||||
# explicite, donc la chaîne construit libvpx une fois dans le cache et le
|
||||
# réutilise. Sans ce cache, chaque exécution repaierait dix minutes de
|
||||
# compilation C.
|
||||
# - les caches sont rangés par dépôt. Le runner est partagé avec d'autres
|
||||
# projets : un `CARGO_TARGET_DIR` commun ferait se marcher dessus des
|
||||
# compilations qui n'ont rien à voir.
|
||||
# - libvpx is not provided by the system. `env-libvpx-sys` requires an explicit
|
||||
# prefix, so the pipeline builds libvpx once into the cache and reuses it.
|
||||
# Without that cache, every run would pay ten minutes of C compilation again.
|
||||
# - caches are kept per repository. The runner is shared with other projects:
|
||||
# a common `CARGO_TARGET_DIR` would make unrelated builds trample each other.
|
||||
|
||||
name: CI
|
||||
|
||||
@@ -27,17 +26,17 @@ permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
integrer:
|
||||
name: Formatage, tests et builds
|
||||
integrate:
|
||||
name: Formatting, tests and builds
|
||||
runs-on: rustscreen-ci
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Outils et caches
|
||||
- name: Tools and caches
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# Les caches vivent hors du dépôt, et le répertoire est propre à ce
|
||||
# projet: la machine de la chaîne est partagée avec d'autres.
|
||||
# Caches live outside the repository, in a directory specific to this
|
||||
# project: the CI machine is shared with others.
|
||||
cache="${RUSTSCREEN_CACHE_DIR:-$HOME/.cache/rustscreen-ci}"
|
||||
mkdir -p "$cache"
|
||||
{
|
||||
@@ -45,11 +44,21 @@ jobs:
|
||||
echo "VPX_PREFIX=$cache/libvpx"
|
||||
echo "npm_config_cache=$cache/npm"
|
||||
} >> "$GITHUB_ENV"
|
||||
# nasm, file et desktop-file-validate peuvent être installés par
|
||||
# l'administrateur du runner dans ~/.local/bin, hors du PATH de la
|
||||
# session. Absents, la chaîne se replie sur ce que le système fournit.
|
||||
if [ -d "$HOME/.local/bin" ]; then
|
||||
echo "PATH=$HOME/.local/bin:$PATH" >> "$GITHUB_ENV"
|
||||
# nasm, file and desktop-file-validate may be installed by the runner's
|
||||
# administrator in ~/.local/bin, outside the session PATH. When they
|
||||
# are missing there, the pipeline falls back on what the system provides.
|
||||
# rustup's ~/.cargo/bin likewise: the runner service does not always
|
||||
# read the profile that adds it.
|
||||
path="$PATH"
|
||||
for dir in "$HOME/.local/bin" "${CARGO_HOME:-$HOME/.cargo}/bin"; do
|
||||
if [ -d "$dir" ]; then
|
||||
path="$dir:$path"
|
||||
fi
|
||||
done
|
||||
echo "PATH=$path" >> "$GITHUB_ENV"
|
||||
if ! PATH="$path" command -v cargo >/dev/null; then
|
||||
echo "cargo not found (HOME=$HOME, PATH=$path): install rustup for the runner's user" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Versions
|
||||
@@ -60,15 +69,15 @@ jobs:
|
||||
cargo fmt --version
|
||||
node --version
|
||||
npm --version
|
||||
nasm -v || echo "nasm absent: libvpx sera construit sans assembleur, encodage plus lent"
|
||||
nasm -v || echo "nasm missing: libvpx will be built without an assembler, slower encoding"
|
||||
|
||||
- name: Bibliothèque libvpx
|
||||
- name: libvpx library
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# La version est figée par le script : au-delà de 1.13, les bindings
|
||||
# pré-générés de `env-libvpx-sys` ne suffisent plus.
|
||||
# The version is pinned by the script: beyond 1.13, the pre-generated
|
||||
# bindings of `env-libvpx-sys` are no longer enough.
|
||||
if [ -f "$VPX_PREFIX/lib/libvpx.a" ]; then
|
||||
echo "libvpx déjà construite dans $VPX_PREFIX"
|
||||
echo "libvpx already built in $VPX_PREFIX"
|
||||
else
|
||||
./scripts/build-libvpx.sh "$VPX_PREFIX"
|
||||
fi
|
||||
@@ -78,59 +87,136 @@ jobs:
|
||||
echo "VPX_VERSION=1.13.0"
|
||||
} >> "$GITHUB_ENV"
|
||||
|
||||
- name: Dépendances du viewer
|
||||
- name: Viewer dependencies
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd apps/viewer
|
||||
# `npm ci` plutôt que `npm install` : le fichier de verrouillage est la
|
||||
# référence, la chaîne ne négocie aucune version.
|
||||
# `npm ci` rather than `npm install`: the lock file is the reference,
|
||||
# the pipeline negotiates no version.
|
||||
npm ci --no-audit --no-fund
|
||||
|
||||
- name: Lint et types du viewer
|
||||
- name: Viewer lint and types
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd apps/viewer
|
||||
npm run lint
|
||||
npx tsc --noEmit
|
||||
|
||||
- name: Tests du viewer
|
||||
- name: Viewer tests
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd apps/viewer
|
||||
npm test
|
||||
|
||||
- name: Bundle du viewer
|
||||
- name: Viewer bundle
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd apps/viewer
|
||||
npm run build
|
||||
|
||||
- name: Formatage
|
||||
- name: Licenses
|
||||
# Every shipped dependency stays compatible with Apache-2.0 (#59): a
|
||||
# new crate under GPL, or without a license, fails here.
|
||||
run: node scripts/check-licenses.mjs
|
||||
|
||||
- name: Formatting
|
||||
run: cargo fmt --all --check
|
||||
|
||||
- name: Clippy
|
||||
run: cargo clippy --workspace --all-targets -- -D warnings
|
||||
|
||||
- name: Tests
|
||||
run: cargo test --workspace -- --skip export_bindings
|
||||
# The `export_bindings` tests write the TypeScript types: they run
|
||||
# here, with the rest, and the "up to date" step only compares. A
|
||||
# second cargo invocation, with different features, rebuilt half of
|
||||
# the workspace (34 s, #78).
|
||||
run: cargo test --workspace
|
||||
|
||||
- name: Binaire de publication
|
||||
- name: Wayland capture (PipeWire)
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# La chaîne ne se contente pas de tester : elle vérifie que le binaire
|
||||
# se construit et démarre, parce qu'un produit qui ne démarre pas passe
|
||||
# tous les tests unitaires.
|
||||
cargo build --release -p rs-signaling --bin rustscreen
|
||||
"$CARGO_TARGET_DIR/release/rustscreen" --version
|
||||
# The feature requires libpipewire-0.3 and libclang (bindgen). The
|
||||
# runner does not always have them: without them, the step says so and
|
||||
# passes, and the release is the one that fails (see release.yml).
|
||||
if pkg-config --exists libpipewire-0.3; then
|
||||
cargo clippy -p rs-capture -p rs-session --features rs-session/pipewire --all-targets -- -D warnings
|
||||
cargo test -p rs-capture --features pipewire
|
||||
else
|
||||
echo "libpipewire-0.3 missing on the runner: Wayland capture not checked"
|
||||
fi
|
||||
|
||||
- name: Le protocole TypeScript est à jour
|
||||
- name: Hardware encoding (VA-API)
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# Les types du protocole sont générés depuis Rust. Un écart entre le
|
||||
# dépôt et la génération veut dire que le viewer compile contre une
|
||||
# version périmée du protocole, ce qui ne se voit qu'en production.
|
||||
cargo test -p rs-proto export_bindings >/dev/null
|
||||
git diff --exit-code -- apps/viewer/src/proto || {
|
||||
echo "apps/viewer/src/proto n'est pas à jour : lancer make proto et commiter" >&2
|
||||
# The `vaapi` feature links GStreamer (#57). Without its development
|
||||
# files the step says so and passes, like the PipeWire one. The
|
||||
# encoder tests skip themselves on a runner without a GPU.
|
||||
if pkg-config --exists gstreamer-app-1.0 gstreamer-video-1.0; then
|
||||
cargo clippy -p rs-codec -p rs-session --features rs-session/vaapi --all-targets -- -D warnings
|
||||
cargo test -p rs-codec --features vaapi
|
||||
else
|
||||
echo "GStreamer development files missing on the runner: hardware encoding not checked"
|
||||
fi
|
||||
|
||||
- name: Windows build (cross-compiled)
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# Windows is built from Linux with mingw-w64 (#93). With Nix, the
|
||||
# `windows` shell of the flake brings everything. Without it, the
|
||||
# runner needs `gcc-mingw-w64-x86-64` and
|
||||
# `rustup target add x86_64-pc-windows-gnu`; libvpx for Windows is
|
||||
# then built once into the cache. Missing both, the step says so and
|
||||
# passes, like the PipeWire one.
|
||||
if command -v nix >/dev/null 2>&1; then
|
||||
nix develop .#windows -c cargo clippy --workspace --all-targets -- -D warnings
|
||||
nix develop .#windows -c cargo build -p rs-session --bin rustscreen-cli
|
||||
elif command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1 \
|
||||
&& rustup target list --installed 2>/dev/null | grep -qx x86_64-pc-windows-gnu; then
|
||||
win_vpx="$(dirname "$VPX_PREFIX")/libvpx-windows"
|
||||
if [ ! -f "$win_vpx/lib/libvpx.a" ]; then
|
||||
LIBVPX_TARGET=x86_64-win64-gcc CROSS=x86_64-w64-mingw32- \
|
||||
./scripts/build-libvpx.sh "$win_vpx"
|
||||
fi
|
||||
export CARGO_BUILD_TARGET=x86_64-pc-windows-gnu
|
||||
export CARGO_TARGET_X86_64_PC_WINDOWS_GNU_LINKER=x86_64-w64-mingw32-gcc
|
||||
export CC_x86_64_pc_windows_gnu=x86_64-w64-mingw32-gcc
|
||||
export AR_x86_64_pc_windows_gnu=x86_64-w64-mingw32-ar
|
||||
export VPX_LIB_DIR="$win_vpx/lib" VPX_INCLUDE_DIR="$win_vpx/include" VPX_STATIC=1
|
||||
export CARGO_TARGET_DIR="$CARGO_TARGET_DIR/windows"
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
cargo build -p rs-session --bin rustscreen-cli
|
||||
else
|
||||
echo "neither Nix nor mingw-w64 with the Windows rustup target: the Windows build is not checked"
|
||||
fi
|
||||
|
||||
- name: The binary starts
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# The pipeline does not stop at tests: it checks that the binary
|
||||
# starts, because a product that does not start passes every unit
|
||||
# test. The integration tests have already built it.
|
||||
"$CARGO_TARGET_DIR/debug/rustscreen-cli" --version
|
||||
|
||||
- name: Release binary
|
||||
# On main only: the whole stack in release costs more than a minute,
|
||||
# and the release workflow rebuilds it anyway (#78).
|
||||
if: github.event_name == 'push'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cargo build --release -p rs-session --bin rustscreen-cli
|
||||
"$CARGO_TARGET_DIR/release/rustscreen-cli" --version
|
||||
|
||||
- name: The TypeScript protocol is up to date
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# The protocol types are generated from Rust. A gap between the
|
||||
# repository and the generated output means the viewer compiles
|
||||
# against a stale protocol, which only shows in production.
|
||||
# Written by the "Tests" step: all that is left is to compare.
|
||||
# `status` rather than `diff`: a new type, never committed, counts too.
|
||||
drift=$(git status --porcelain -- apps/viewer/src/proto apps/desktop/src/bindings)
|
||||
if [ -n "$drift" ]; then
|
||||
echo "$drift" >&2
|
||||
echo "generated TypeScript types are out of date: run make proto and commit" >&2
|
||||
exit 1
|
||||
}
|
||||
fi
|
||||
@@ -1,14 +1,15 @@
|
||||
# Publication : une étiquette `vX.Y.Z` produit une release avec ses artefacts.
|
||||
# Release: a `vX.Y.Z` tag produces a release with its artifacts.
|
||||
#
|
||||
# Rien d'autre ne déclenche cette chaîne: pas de bouton, pas de commande tapée
|
||||
# sur un portable, et pas de numéro de version écrit à la main dans un fichier.
|
||||
# L'étiquette git est la seule source de la version; le binaire et l'AppImage en
|
||||
# découlent, et la release dit ce qu'elle contient.
|
||||
# Nothing else triggers this pipeline: no button, no command typed on a laptop,
|
||||
# and no version number written by hand in a file. The git tag is the single
|
||||
# source of the version; the binary and the AppImage follow from it, and the
|
||||
# release states what it contains. GoReleaser publishes it (#97); the builds
|
||||
# stay in the scripts, which know libvpx and PipeWire.
|
||||
#
|
||||
# Elle vérifie d'abord que l'étiquette correspond à la version déclarée dans le
|
||||
# `Cargo.toml`: une release `v0.2.0` construite sur un `Cargo.toml` en `0.1.0`
|
||||
# mentirait sur son contenu, et c'est le genre d'erreur qu'on ne voit qu'après
|
||||
# avoir distribué le paquet.
|
||||
# It first checks that the tag matches the version declared in `Cargo.toml`: a
|
||||
# `v0.2.0` release built from a `Cargo.toml` at `0.1.0` would lie about its
|
||||
# contents, and that is the kind of mistake only noticed after the package has
|
||||
# been distributed.
|
||||
|
||||
name: Release
|
||||
|
||||
@@ -21,20 +22,20 @@ permissions:
|
||||
|
||||
jobs:
|
||||
release:
|
||||
name: Paquets et release
|
||||
name: Packages and release
|
||||
runs-on: rustscreen-ci
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
# `git describe` et l'historique depuis l'étiquette précédente ont
|
||||
# besoin des étiquettes, que le clone superficiel ne prend pas.
|
||||
# `git describe` and the history since the previous tag need the
|
||||
# tags, which a shallow clone does not fetch.
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Outils et caches
|
||||
- name: Tools and caches
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# Les caches vivent hors du dépôt, et le répertoire est propre à ce
|
||||
# projet: la machine de la chaîne est partagée avec d'autres.
|
||||
# Caches live outside the repository, in a directory specific to this
|
||||
# project: the CI machine is shared with others.
|
||||
cache="${RUSTSCREEN_CACHE_DIR:-$HOME/.cache/rustscreen-ci}"
|
||||
mkdir -p "$cache"
|
||||
{
|
||||
@@ -42,26 +43,36 @@ jobs:
|
||||
echo "VPX_PREFIX=$cache/libvpx"
|
||||
echo "npm_config_cache=$cache/npm"
|
||||
} >> "$GITHUB_ENV"
|
||||
# nasm, file et desktop-file-validate peuvent être installés par
|
||||
# l'administrateur du runner dans ~/.local/bin, hors du PATH de la
|
||||
# session. Absents, la chaîne se replie sur ce que le système fournit.
|
||||
if [ -d "$HOME/.local/bin" ]; then
|
||||
echo "PATH=$HOME/.local/bin:$PATH" >> "$GITHUB_ENV"
|
||||
fi
|
||||
|
||||
- name: Version et étiquette
|
||||
run: |
|
||||
set -euo pipefail
|
||||
etiquette="${GITHUB_REF_NAME#v}"
|
||||
declaree=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)
|
||||
if [ "$etiquette" != "$declaree" ]; then
|
||||
echo "étiquette v$etiquette mais Cargo.toml déclare $declaree" >&2
|
||||
# nasm, file and desktop-file-validate may be installed by the runner's
|
||||
# administrator in ~/.local/bin, outside the session PATH. When they
|
||||
# are missing there, the pipeline falls back on what the system provides.
|
||||
# rustup's ~/.cargo/bin likewise: the runner service does not always
|
||||
# read the profile that adds it.
|
||||
path="$PATH"
|
||||
for dir in "$HOME/.local/bin" "${CARGO_HOME:-$HOME/.cargo}/bin"; do
|
||||
if [ -d "$dir" ]; then
|
||||
path="$dir:$path"
|
||||
fi
|
||||
done
|
||||
echo "PATH=$path" >> "$GITHUB_ENV"
|
||||
if ! PATH="$path" command -v cargo >/dev/null; then
|
||||
echo "cargo not found (HOME=$HOME, PATH=$path): install rustup for the runner's user" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "VERSION=$etiquette" >> "$GITHUB_ENV"
|
||||
echo "version $etiquette confirmée"
|
||||
|
||||
- name: Bibliothèque libvpx
|
||||
- name: Version and tag
|
||||
run: |
|
||||
set -euo pipefail
|
||||
tag="${GITHUB_REF_NAME#v}"
|
||||
declared=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)
|
||||
if [ "$tag" != "$declared" ]; then
|
||||
echo "tag v$tag but Cargo.toml declares $declared" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "VERSION=$tag" >> "$GITHUB_ENV"
|
||||
echo "version $tag confirmed"
|
||||
|
||||
- name: libvpx library
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [ ! -f "$VPX_PREFIX/lib/libvpx.a" ]; then
|
||||
@@ -80,36 +91,68 @@ jobs:
|
||||
npm ci --no-audit --no-fund
|
||||
npm run build
|
||||
|
||||
- name: Binaire
|
||||
- name: Binary
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cargo build --release -p rs-signaling --bin rustscreen
|
||||
# Le binaire est distribué: ses symboles ne servent qu'aux diagnostics
|
||||
# de développement et pèsent la moitié du fichier.
|
||||
strip "$CARGO_TARGET_DIR/release/rustscreen"
|
||||
"$CARGO_TARGET_DIR/release/rustscreen" --version
|
||||
# A binary released without PipeWire captures nothing under Wayland,
|
||||
# the product's target (ADR 0009): the release fails rather than ship
|
||||
# it. The runner needs libpipewire-0.3-dev and libclang-dev.
|
||||
if ! pkg-config --exists libpipewire-0.3; then
|
||||
echo "libpipewire-0.3 not found: install libpipewire-0.3-dev and libclang-dev on the runner" >&2
|
||||
exit 1
|
||||
fi
|
||||
cargo build --release -p rs-session --features pipewire --bin rustscreen-cli
|
||||
# The binary is distributed: its symbols only help development
|
||||
# diagnostics and weigh half of the file.
|
||||
strip "$CARGO_TARGET_DIR/release/rustscreen-cli"
|
||||
"$CARGO_TARGET_DIR/release/rustscreen-cli" --version
|
||||
|
||||
- name: AppImage
|
||||
run: |
|
||||
set -euo pipefail
|
||||
./scripts/build-appimage.sh
|
||||
|
||||
- name: Release
|
||||
env:
|
||||
# Le jeton de la chaîne, avec les droits d'écriture demandés plus haut.
|
||||
GITEA_TOKEN: ${{ github.token }}
|
||||
GITEA_REPO: ${{ github.repository }}
|
||||
GITEA_API: ${{ github.server_url }}/api/v1
|
||||
RELEASE_NOTES: docs/releases/${{ github.ref_name }}.md
|
||||
- name: .deb and .rpm
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# `RELEASE_NOTES` désigne un fichier versionné quand il existe; sinon
|
||||
# le script écrit une note minimale plutôt que d'échouer.
|
||||
./scripts/build-linux-packages.sh
|
||||
|
||||
- name: GoReleaser
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# Pinned with its checksum, like appimagetool: the runner has neither
|
||||
# Nix nor a package for it, and a "latest" URL would change
|
||||
# underneath us.
|
||||
version=2.17.1
|
||||
sum=a99bbc7ae0d8d897b07c4c497a9b62f222558804715ef219d1af05a7e417bc80
|
||||
dir="${RUSTSCREEN_CACHE_DIR:-$HOME/.cache/rustscreen-ci}/goreleaser-$version"
|
||||
if [ ! -x "$dir/goreleaser" ]; then
|
||||
mkdir -p "$dir"
|
||||
curl -fsSL -o "$dir/goreleaser.tar.gz" \
|
||||
"https://github.com/goreleaser/goreleaser/releases/download/v$version/goreleaser_Linux_x86_64.tar.gz"
|
||||
echo "$sum $dir/goreleaser.tar.gz" | sha256sum -c -
|
||||
tar -xzf "$dir/goreleaser.tar.gz" -C "$dir" goreleaser
|
||||
rm "$dir/goreleaser.tar.gz"
|
||||
fi
|
||||
echo "$dir" >> "$GITHUB_PATH"
|
||||
|
||||
- name: Release
|
||||
env:
|
||||
# The pipeline token, with the write permission requested above.
|
||||
GITEA_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# GoReleaser publishes what was built above (`.goreleaser.yaml`): it
|
||||
# only globs inside the repository, hence `dist/release`.
|
||||
mkdir -p dist/release
|
||||
cp "dist-appimage/rustscreen-${VERSION}-x86_64.AppImage" dist/release/
|
||||
cp "$CARGO_TARGET_DIR/release/rustscreen-cli" dist/release/
|
||||
cp dist-packages/*.deb dist-packages/*.rpm dist/release/
|
||||
notes="docs/releases/${GITHUB_REF_NAME}.md"
|
||||
if [ ! -f "$notes" ]; then
|
||||
echo "pas de notes pour ${GITHUB_REF_NAME}, note minimale" >&2
|
||||
export RELEASE_NOTES="$notes.absent"
|
||||
if [ -f "$notes" ]; then
|
||||
goreleaser release --clean --release-notes "$notes"
|
||||
else
|
||||
# Without written notes, the commits since the previous tag.
|
||||
echo "no notes for ${GITHUB_REF_NAME}, changelog from git" >&2
|
||||
goreleaser release --clean
|
||||
fi
|
||||
./scripts/publish-release.py "$GITHUB_REF_NAME" \
|
||||
"dist-appimage/rustscreen-${VERSION}-x86_64.AppImage" \
|
||||
"$CARGO_TARGET_DIR/release/rustscreen"
|
||||
@@ -30,6 +30,7 @@ diag-*.zip
|
||||
|
||||
# Empaquetage local
|
||||
dist-appimage/
|
||||
dist-packages/
|
||||
.cache/
|
||||
SHA256SUMS
|
||||
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
# Release of a `vX.Y.Z` tag (#97), run by `.gitea/workflows/release.yml`.
|
||||
#
|
||||
# GoReleaser does not compile anything here: the Rust stack needs libvpx,
|
||||
# PipeWire and the viewer built first, which the pipeline does with its own
|
||||
# scripts. It takes the finished artifacts and publishes the release: Gitea
|
||||
# release, attachments, SHA256SUMS, notes. A rerun on the same tag replaces
|
||||
# them instead of stacking copies.
|
||||
#
|
||||
# Local check, without publishing:
|
||||
# goreleaser release --snapshot --clean --skip=publish
|
||||
version: 2
|
||||
|
||||
project_name: rustscreen
|
||||
|
||||
# Not `dist/`: `--clean` empties it, and the Windows installer is built there.
|
||||
dist: dist/goreleaser
|
||||
|
||||
# A skipped build, declared Rust so that GoReleaser does not look for a Go
|
||||
# module.
|
||||
builds:
|
||||
- builder: rust
|
||||
skip: true
|
||||
|
||||
gitea_urls:
|
||||
api: https://gitea-nubo.hopledge.com/api/v1
|
||||
download: https://gitea-nubo.hopledge.com
|
||||
|
||||
# The pipeline token is GITEA_TOKEN; a GITHUB_TOKEN set by the runner must not
|
||||
# send GoReleaser to GitHub.
|
||||
force_token: gitea
|
||||
|
||||
# What the release ships: the binary, the AppImage, the .deb and the .rpm,
|
||||
# built beforehand and gathered in `dist/release` (GoReleaser only globs
|
||||
# inside the repository). The packages come from nfpm directly: see
|
||||
# `scripts/build-linux-packages.sh` for why not GoReleaser's own. A missing
|
||||
# file fails the release rather than publishing an incomplete one.
|
||||
release:
|
||||
gitea:
|
||||
owner: heap
|
||||
name: rustscreen
|
||||
name_template: "v{{ .Version }}"
|
||||
mode: replace
|
||||
replace_existing_artifacts: true
|
||||
extra_files:
|
||||
- glob: "dist/release/rustscreen-{{ .Version }}-x86_64.AppImage"
|
||||
- glob: "dist/release/rustscreen-cli"
|
||||
- glob: "dist/release/rustscreen-cli_{{ .Version }}_amd64.deb"
|
||||
- glob: "dist/release/rustscreen-cli-{{ .Version }}-1.x86_64.rpm"
|
||||
|
||||
checksum:
|
||||
name_template: SHA256SUMS
|
||||
algorithm: sha256
|
||||
extra_files:
|
||||
- glob: "dist/release/rustscreen-{{ .Version }}-x86_64.AppImage"
|
||||
- glob: "dist/release/rustscreen-cli"
|
||||
- glob: "dist/release/rustscreen-cli_{{ .Version }}_amd64.deb"
|
||||
- glob: "dist/release/rustscreen-cli-{{ .Version }}-1.x86_64.rpm"
|
||||
|
||||
# `--snapshot` (local check): the artifacts are named after this version.
|
||||
snapshot:
|
||||
version_template: "{{ .Version }}-snapshot"
|
||||
|
||||
# Used when `docs/releases/vX.Y.Z.md` does not exist; otherwise the pipeline
|
||||
# passes that file with `--release-notes`.
|
||||
changelog:
|
||||
use: git
|
||||
sort: asc
|
||||
filters:
|
||||
exclude:
|
||||
- "^chore\\(deps\\)"
|
||||
@@ -11,12 +11,41 @@ TypeScript. Le spectateur n'installe rien : il ouvre une URL, éventuellement sc
|
||||
code. La cible fonctionnelle est le plan **Pro** de Deskreen, plus les fonctions Teams qui ne
|
||||
dépendent pas d'un service en ligne.
|
||||
|
||||
Ce qui tourne: capture synthétique, conversion BGRA vers I420, encodage VP8, session str0m par
|
||||
spectateur, serveur local avec jeton, viewer React. Ce qui manque: la capture réelle par OS, la
|
||||
coque desktop Tauri, et l'encodeur matériel.
|
||||
Ce qui tourne: capture Linux réelle (portail et PipeWire sous Wayland, X11 en repli, chaque
|
||||
moniteur RandR, une fenêtre seule), écran virtuel par le portail (GNOME 46, KDE), conversion BGRA
|
||||
vers I420, encodage VP8 ou VP9 temps réel qui suit les changements de résolution, session str0m par
|
||||
spectateur, serveur local avec jeton qui expire et code court, appareils de confiance qui reviennent sans lien
|
||||
par une clé Ed25519 (ADR 0011), changement de source en plein partage sans reconnexion, nom
|
||||
local `rustscreen.local` en mDNS, viewer React qui reprend seul après
|
||||
une coupure ou une veille, tourne l'image et suit le thème, coque desktop Tauri avec icône de
|
||||
barre système, réglages persistants, interface en français et en anglais, inhibition de veille,
|
||||
journal JSON local et archive de diagnostics.
|
||||
L'encodage matériel passe par VA-API et GStreamer sous Linux (fonctionnalité `vaapi`, ADR 0012), par
|
||||
Media Foundation sous Windows (#95). Ce qui manque: la duplication de bureau DXGI sous Windows
|
||||
(la capture y passe par GDI, #8), et tout le travail Windows reste à vérifier sur une vraie machine,
|
||||
il n'a tourné que sous Wine. macOS est hors périmètre comme hôte (#90). Les messages de l'hôte
|
||||
(erreurs, avertissements, refus de réglages) partent en codes (`Notice`) que la coque traduit sous
|
||||
`desktop.host` (#75); le test `notices` refuse un code sans traduction.
|
||||
|
||||
L'hôte tient dans `rs-session::Host`: démarrer, arrêter, déconnecter un spectateur, régler, et
|
||||
publier l'état complet à chaque changement. Lancer `rustscreen` ouvre l'application de bureau
|
||||
(`apps/desktop/src-tauri`); la ligne de commande est `rustscreen-cli`
|
||||
(`rs-session/src/bin/rustscreen-cli.rs`). Les deux ne font que piloter l'hôte: aucune ne connaît
|
||||
la capture ni le serveur.
|
||||
|
||||
## Conventions
|
||||
|
||||
### Langue
|
||||
|
||||
- **Le code est en anglais**: identifiants, noms de fichiers et de modules, commentaires, messages
|
||||
et noms d'événements du journal, messages d'erreur, sorties de `rustscreen-cli`, scripts (#83).
|
||||
- **Les textes affichés à l'utilisateur** passent par `locales/` (français et anglais), jamais en dur.
|
||||
- **La documentation** (`docs/`, ce fichier, `README.md`) **et les messages de commit** restent en
|
||||
français.
|
||||
- Un format déjà écrit chez l'utilisateur garde ses anciens noms en lecture: alias `serde` des
|
||||
réglages, `reglages.json` relu à défaut de `settings.json`, anciennes clés `localStorage`,
|
||||
anciennes options de la ligne de commande, ancien fichier de restauration du portail.
|
||||
|
||||
### Rust
|
||||
|
||||
- Édition 2024, un crate par domaine sous `crates/`, préfixe `rs-`. Le spike jetable est sous
|
||||
@@ -33,7 +62,17 @@ coque desktop Tauri, et l'encodeur matériel.
|
||||
### TypeScript
|
||||
|
||||
- `apps/viewer` et `apps/desktop` : Vite, React 19, TypeScript strict, biome pour lint et format
|
||||
(tabs, guillemets simples, pas d'ESLint, pas de Prettier).
|
||||
(tabs, guillemets simples, pas d'ESLint, pas de Prettier). Le viewer s'installe avec npm, la
|
||||
coque avec **pnpm** (`pnpm-lock.yaml`).
|
||||
- Les types de la coque (`apps/desktop/src/bindings`) sont générés depuis `rs-store` et
|
||||
`rs-session`, comme ceux du viewer depuis `rs-proto`: `make proto`.
|
||||
- **Aucun texte en dur dans un composant.** Les textes vivent dans `locales/<langue>.json`, une
|
||||
section par application, et passent par `t('clé')`. L'anglais est la langue de repli et doit
|
||||
être complet, le français aussi. `npm run lint` (viewer) et `pnpm lint` (coque) lancent
|
||||
`scripts/check-i18n.mjs`, qui refuse une clé absente de l'anglais et un texte en dur. Ajouter
|
||||
une langue, c'est ajouter un fichier: l'hôte l'embarque (`rs-signaling/build.rs`) et la sert au
|
||||
viewer, la coque l'embarque à la compilation. Le viewer et la coque partagent le cœur
|
||||
(`apps/viewer/src/lib/i18n.ts`), sans React.
|
||||
- Aucune dépendance à un service externe : pas d'analytics, pas de CDN, pas de police distante.
|
||||
Le client doit fonctionner sur un LAN sans Internet.
|
||||
- Le protocole vient de `rs-proto`. Un type de message en double (un côté Rust, un côté TS, écrit
|
||||
@@ -45,12 +84,16 @@ coque desktop Tauri, et l'encodeur matériel.
|
||||
pas de tiret cadratin.
|
||||
- Une issue par sujet dans le tracker Gitea, avec son jalon. Une demande nouvelle ouvre une issue
|
||||
avant la première ligne de code.
|
||||
- Le suivi d'avancement est un **tableau Projets par jalon**, colonnes `En cours`, `P0`, `P1`, `P2`,
|
||||
`P3` de gauche à droite. Une carte passe dans `En cours` quand elle est attaquée, l'ordre des
|
||||
cartes dans une colonne est l'ordre de travail, et une issue livrée se ferme (elle quitte le
|
||||
tableau). Ne pas recréer de colonnes de statut : le statut, c'est l'état ouvert/fermé.
|
||||
|
||||
## Pièges connus de ce domaine
|
||||
|
||||
- **La capture écran est le vrai sujet, pas WebRTC.** Chaque OS a sa contrainte : Wayland interdit
|
||||
la capture directe (portail PipeWire obligatoire, avec une boîte de dialogue de consentement),
|
||||
macOS exige la permission d'enregistrement d'écran et ScreenCaptureKit, Windows demande DXGI ou
|
||||
Windows demande DXGI ou
|
||||
Windows Graphics Capture. Un chemin de capture unique et portable n'existe pas.
|
||||
- **Le profil couleur casse les conversions.** Une frame BGRA 10 bits traitée comme du 8 bits donne
|
||||
des couleurs fausses ; préciser le format en entrée de chaque étape et le tester avec une mire.
|
||||
@@ -80,20 +123,107 @@ cargo test -p rs-proto export_bindings # régénère apps/viewer/src/proto
|
||||
Une fonctionnalité de capture ou d'encodage se prouve avec une mire de test et des mesures de
|
||||
latence, pas avec une capture d'écran de l'UI.
|
||||
|
||||
Le banc d'essai actuel est la démo de `rs-signaling`: elle assemble la vraie pile (protocole,
|
||||
session, serveur) et rejoue une mire IVF.
|
||||
**Sans libvpx, rien ne compile.** `rs-codec` lie `env-libvpx-sys`, qui exige un préfixe explicite :
|
||||
sans lui, la compilation s'arrête sur `Package 'vpx' was not found in the pkg-config search path`,
|
||||
après deux minutes de dépendances. La CI construit libvpx une fois dans son cache et exporte quatre
|
||||
variables; les mêmes suffisent en local, avec le répertoire de cible de la CI déjà chaud pour éviter
|
||||
une reconstruction complète.
|
||||
|
||||
```bash
|
||||
export VPX_PREFIX=$HOME/.cache/rustscreen-ci/libvpx # ou ./scripts/build-libvpx.sh <préfixe>
|
||||
export VPX_LIB_DIR=$VPX_PREFIX/lib
|
||||
export VPX_INCLUDE_DIR=$VPX_PREFIX/include
|
||||
export VPX_VERSION=1.13.0
|
||||
export PKG_CONFIG_PATH=$VPX_PREFIX/lib/pkgconfig${PKG_CONFIG_PATH:+:$PKG_CONFIG_PATH}
|
||||
export CARGO_TARGET_DIR=$HOME/.cache/rustscreen-ci/cargo-target
|
||||
```
|
||||
|
||||
Le banc d'essai actuel est le binaire `rustscreen-cli` de `rs-session`: il assemble la vraie pile
|
||||
(capture, encodage, protocole, session, serveur) et sait aussi rejouer une mire IVF.
|
||||
|
||||
```bash
|
||||
# mire synthétique: capture, conversion BGRA vers I420, encodage VP8, en direct
|
||||
cargo run -p rs-signaling --bin rustscreen -- --synthetic --port 8099
|
||||
cargo run -p rs-session --bin rustscreen-cli -- --synthetic --port 8099
|
||||
|
||||
# ou rejeu d'un fichier encodé, sans encodeur
|
||||
cargo run -p rs-signaling --bin rustscreen -- spikes/str0m-mire/mire.ivf --port 8099
|
||||
cargo run -p rs-session --bin rustscreen-cli -- spikes/str0m-mire/mire.ivf --port 8099
|
||||
```
|
||||
|
||||
Elle accepte `--limit N`, `--tls` et `--viewer DIR`. Sans TLS, le serveur est en HTTP simple:
|
||||
Il accepte `--limit N`, `--tls` et `--viewer DIR`; le port, l'interface et la limite viennent
|
||||
sinon des réglages (`~/.config/rustscreen/settings.json`, partagés avec l'application de bureau). Sans TLS, le serveur est en HTTP simple:
|
||||
pratique pour un navigateur local, insuffisant pour un vrai appareil (voir ADR 0005).
|
||||
|
||||
La capture réelle sous Wayland demande la feature `pipewire` (libpipewire-0.3 et libclang au
|
||||
build, fournies par `nix develop`; ADR 0009). Sans elle, le binaire refuse le chemin portail avec
|
||||
un message clair.
|
||||
|
||||
```bash
|
||||
# écran réel, par le portail (sous X11: XShm, sans feature)
|
||||
cargo run --release -p rs-session --features pipewire --bin rustscreen-cli
|
||||
# second écran créé par le portail, à la taille de la tablette
|
||||
cargo run --release -p rs-session --features pipewire --bin rustscreen-cli -- --virtual --size 1280x800
|
||||
# archive de diagnostics, sans rien démarrer
|
||||
cargo run -p rs-session --bin rustscreen-cli -- --diagnostics
|
||||
# VP9 au lieu de VP8 (même qualité pour moins de débit, 1,6x le calcul), une fenêtre par le portail
|
||||
cargo run --release -p rs-session --features pipewire --bin rustscreen-cli -- --codec vp9 --pick-window
|
||||
# H.264 ou VP9 sur le GPU (VA-API, ADR 0012); --software force libvpx
|
||||
cargo run --release -p rs-session --features pipewire,vaapi --bin rustscreen-cli -- --codec h264
|
||||
```
|
||||
|
||||
Windows se compile depuis Linux (#93): le shell `.#windows` fournit un rustc pour la cible
|
||||
`x86_64-pc-windows-gnu`, mingw-w64 et une libvpx statique, et range sa cible sous `target/windows`.
|
||||
Wine fait tourner le `.exe` et les tests, sans machine Windows. Les tests de Media Foundation y
|
||||
passent par la transformée H.264 de Wine (GStreamer, `x264enc`), logicielle et sans basse latence:
|
||||
ils encodent assez d'images pour franchir sa file d'attente. La capture GDI (#8) s'y vérifie sur
|
||||
un Xvfb **à la taille d'un moniteur que Wine annonce** (1920 × 1080): plus petit, X refuse de lire
|
||||
la zone et l'image sort noire.
|
||||
|
||||
```bash
|
||||
nix develop .#windows -c cargo clippy --workspace --all-targets -- -D warnings
|
||||
nix develop .#windows -c cargo build -p rs-session --bin rustscreen-cli
|
||||
# tests et binaire sous Wine (nix shell nixpkgs#wine64)
|
||||
CARGO_TARGET_X86_64_PC_WINDOWS_GNU_RUNNER=wine nix develop .#windows -c cargo test --workspace
|
||||
```
|
||||
|
||||
Sous Windows, les réglages vont dans `%APPDATA%\rustscreen`, le journal dans
|
||||
`%LOCALAPPDATA%\rustscreen\logs`. Le portail n'existe pas: `rs_platform::portal` y répond
|
||||
`Unsupported`, et le code propre à un système vit dans un sous-module par OS (`sleep/linux.rs`,
|
||||
`sleep/windows.rs`).
|
||||
|
||||
La coque desktop demande WebKitGTK au build: elle a son propre workspace Cargo et son shell Nix.
|
||||
|
||||
```bash
|
||||
nix develop .#desktop
|
||||
make desktop # pnpm install, interface, puis binaire (target/release/rustscreen)
|
||||
nix build .#rustscreen # le paquet: application de bureau, rustscreen-cli et viewer
|
||||
make desktop-lint # biome, vitest, rustfmt et clippy de la coque
|
||||
```
|
||||
|
||||
En debug, le binaire embarque `apps/desktop/dist` (feature `custom-protocol` par défaut);
|
||||
`--no-default-features` charge le serveur Vite (`pnpm --dir apps/desktop dev`) à la place.
|
||||
|
||||
Le chemin se force avec `RUSTSCREEN_CAPTURE=portal|x11|gdi|synthetic`. Le test X11 réel se lance
|
||||
contre un serveur jetable: `Xephyr :5 & DISPLAY=:5 xeyes &` puis
|
||||
`RUSTSCREEN_X11_TEST=:5 cargo test -p rs-capture x11 -- --ignored`. Pour plusieurs moniteurs,
|
||||
lancer Xephyr avec `+extension RANDR` et en déclarer avec `xrandr --setmonitor` (voir le test).
|
||||
Avec openbox sur ce serveur, le même test réduit puis restaure une fenêtre partagée (#17).
|
||||
|
||||
Pour essayer la coque ou un navigateur sans rien ouvrir sur le bureau, préférer `Xvfb` à
|
||||
`Xephyr`, qui affiche une fenêtre. L'icône de barre système, elle, passe par le bus de session: elle
|
||||
apparaît dans la vraie barre. Elle se vérifie par D-Bus (`org.kde.StatusNotifierWatcher`, menu
|
||||
`com.canonical.dbusmenu`), et son menu se pilote par `Event`.
|
||||
|
||||
Le journal JSON (`~/.local/state/rustscreen/logs`) nomme les étapes d'une session par le champ
|
||||
`event`: `portal_granted`, `capture_format`, `first_buffer`, `first_frame_encoded`,
|
||||
`session_opened`, `ice_candidate_selected`, `first_frame_sent`, `quality_change`, `disconnected`
|
||||
(avec `cause`), `capture_revoked`, `capture_failed`, `encode_failed`, et côté hôte `share_started`,
|
||||
`share_ended`, `share_interrupted`, `viewer_disconnected`, `resolution_changed`, `sleep_inhibited`,
|
||||
`sleep_released`, `wake_detected`, `capture_restarted`, `address_changed`, `settings_changed`,
|
||||
`access_regenerated`, `code_accepted`, `code_rejected`, `trust_changed`, `source_switched`,
|
||||
`source_switch_failed`, `local_name_failed`, et côté serveur `trusted_device_admitted`,
|
||||
`local_name_announced`, `local_name_renamed`, `local_name_confirmed`. Avant la 0.6, ces noms étaient en français
|
||||
(champ `evenement`). Ne jamais y écrire un titre de fenêtre ni une image (ADR 0008).
|
||||
|
||||
Le spike historique `spikes/str0m-mire` reste pour comparer les mesures:
|
||||
|
||||
```bash
|
||||
@@ -116,3 +246,31 @@ vérifier qu'une régression ne casse pas le transport.
|
||||
reçu. C'est un argument pour ICE-lite côté hôte.
|
||||
- **Le candidat annoncé doit être l'adresse LAN**, jamais `127.0.0.1`: Chrome ignore les candidats
|
||||
loopback et la connexion reste en `Checking`.
|
||||
- **Le viewer servi en HTTP sur le LAN n'est pas un contexte sécurisé.** `crypto.randomUUID()`,
|
||||
`navigator.clipboard` et d'autres API y manquent. Un `randomUUID` dans le `hello` a empêché toute
|
||||
connexion depuis un autre appareil que l'hôte, alors que tous les essais sur `127.0.0.1`
|
||||
passaient. Tester le viewer par l'adresse du LAN, jamais seulement par le loopback.
|
||||
|
||||
- **Le type de charge utile suit le codec encodé**, jamais le premier venu: `payload_params().next()`
|
||||
prenait VP8 pendant qu'on envoyait du VP9, et le navigateur affichait un écran noir sans erreur.
|
||||
- **libvpx 1.13 plante en VP9 à la vitesse 6**, et avec le réglage « contenu écran » à toute vitesse
|
||||
(SIGSEGV dans `vpx_variance8x8_sse2`, reproduit en C pur; corrigé en 1.14). L'encodeur est figé
|
||||
à la vitesse 7 et le test `vp9_survives_moving_content` tombe si quelqu'un remet 6.
|
||||
|
||||
## Pièges du portail, appris à la dure
|
||||
|
||||
La négociation du portail a « compilé et passé les tests » avec trois bugs que seule une vraie
|
||||
session a révélés. Le détail est dans `docs/capture-wayland.md`; l'essentiel:
|
||||
|
||||
- **Le corps d'un appel D-Bus est un tuple d'arguments, pas une `Variant`**: sinon la signature
|
||||
part en `(v)` et le portail répond `InvalidArgs`.
|
||||
- **`SelectSources`, `Start`, `OpenPipeWireRemote` s'appellent sur `/org/freedesktop/portal/desktop`**,
|
||||
la session en premier argument.
|
||||
- **Le descripteur PipeWire vient de `OpenPipeWireRemote`**, jamais de la réponse de `Start`.
|
||||
- **GNOME livre des tampons MemFd que PipeWire ne mappe pas**, malgré `MAP_BUFFERS`: `data()` est
|
||||
vide. Ils se lisent par `pread` sur le descripteur (`read_memfd`). Les ignorer donnait un écran
|
||||
noir sans aucune erreur. Une mire GStreamer (`examples/pipewire_local.rs`) livre des tampons
|
||||
mappés: elle ne remplace pas un essai par le vrai portail. Le journal dit comment arrive le
|
||||
premier tampon (`premier_tampon`), puis la première panne de capture ou d'encodage.
|
||||
- **`/proc/self/net/*` liste tout l'espace de noms réseau**, pas le processus: filtrer par les
|
||||
inodes de `/proc/self/fd` (voir le test `no_outbound_connection`).
|
||||
Generated
+1365
-58
File diff suppressed because it is too large.
Load diff
+10
-1
@@ -9,11 +9,14 @@ members = [
|
||||
"crates/rs-session",
|
||||
"crates/rs-platform",
|
||||
"crates/rs-store",
|
||||
"crates/rs-diag",
|
||||
"spikes/str0m-mire",
|
||||
]
|
||||
# La coque Tauri a son propre workspace: WebKitGTK au build (voir son Cargo.toml).
|
||||
exclude = ["apps/desktop/src-tauri"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.1"
|
||||
version = "0.5.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.90"
|
||||
license = "Apache-2.0"
|
||||
@@ -24,3 +27,9 @@ serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
thiserror = "2"
|
||||
tracing = "0.1"
|
||||
|
||||
# Les dépendances sans informations de débogage complètes: des binaires de test
|
||||
# trois fois plus légers et une édition de liens plus courte (#78). Les numéros
|
||||
# de ligne restent, une trace de pile se lit toujours; nos crates gardent tout.
|
||||
[profile.dev.package."*"]
|
||||
debug = "line-tables-only"
|
||||
@@ -1,6 +1,6 @@
|
||||
# Portes du projet. `make` seul lance tout ce qui doit être vert avant un commit.
|
||||
# Project gates. Plain `make` runs everything that must pass before a commit.
|
||||
|
||||
.PHONY: all fmt lint test build proto bench clean
|
||||
.PHONY: all fmt lint test build proto bench clean desktop desktop-lint
|
||||
|
||||
all: fmt lint test build
|
||||
|
||||
@@ -13,26 +13,40 @@ lint:
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
npm --prefix apps/viewer run lint
|
||||
|
||||
# `--skip export_bindings` : les tests de génération de ts-rs écriraient dans
|
||||
# apps/viewer/src/proto à chaque exécution. La cible `proto` s'en charge, avec
|
||||
# le formatage qui va avec.
|
||||
# `--skip export_bindings`: the ts-rs generation tests would write into
|
||||
# apps/viewer/src/proto on every run. The `proto` target handles that, along
|
||||
# with the matching formatting.
|
||||
test:
|
||||
cargo test --workspace -- --skip export_bindings
|
||||
|
||||
# Les types TypeScript du protocole sont générés, jamais écrits à la main.
|
||||
# Ils sont exclus du formateur et du linter (voir biome.json): leur format
|
||||
# appartient à ts-rs, sinon chaque `make` laisse un diff dans le dépôt.
|
||||
# The protocol's TypeScript types are generated, never written by hand.
|
||||
# They are excluded from the formatter and the linter (see biome.json): their
|
||||
# format belongs to ts-rs, otherwise every `make` leaves a diff in the repository.
|
||||
proto:
|
||||
cargo test -p rs-proto export_bindings
|
||||
cargo test -p rs-proto -p rs-store -p rs-session -p rs-signaling export_bindings
|
||||
|
||||
build:
|
||||
cargo build --workspace
|
||||
npm --prefix apps/viewer run build
|
||||
|
||||
# Banc d'essai: toujours en release, un binaire debug fausse les mesures.
|
||||
# Test bench: always in release, a debug binary skews the measurements.
|
||||
bench:
|
||||
cargo run --release -p rs-signaling --bin rustscreen -- --synthetic
|
||||
cargo run --release -p rs-session --bin rustscreen-cli -- --synthetic
|
||||
|
||||
# The Tauri shell: WebKitGTK at build time, so inside `nix develop .#desktop`.
|
||||
# Its crate has its own workspace; it shares the target directory to avoid
|
||||
# rebuilding everything. pnpm for the shell's interface, npm for the viewer.
|
||||
desktop:
|
||||
pnpm --dir apps/desktop install --frozen-lockfile
|
||||
pnpm --dir apps/desktop build
|
||||
cd apps/desktop/src-tauri && CARGO_TARGET_DIR=../../../target cargo build --release --features pipewire
|
||||
|
||||
desktop-lint:
|
||||
node scripts/check-licenses.mjs --desktop
|
||||
pnpm --dir apps/desktop lint
|
||||
pnpm --dir apps/desktop test
|
||||
cd apps/desktop/src-tauri && cargo fmt --check && CARGO_TARGET_DIR=../../../target cargo clippy --features pipewire -- -D warnings
|
||||
|
||||
clean:
|
||||
cargo clean
|
||||
rm -rf apps/viewer/dist
|
||||
rm -rf apps/viewer/dist apps/desktop/dist
|
||||
@@ -8,26 +8,30 @@
|
||||
côté spectateur. Réimplémentation de [Deskreen](https://deskreen.com) (Electron + WebRTC) avec un
|
||||
hôte en Rust, un client web en TypeScript et une interface desktop Tauri.
|
||||
|
||||
État : **M0 terminé, M1 en cours**. Ce qui tourne aujourd'hui, vérifié le 24 octobre 2026:
|
||||
État : **jalon 0.6 « Parité Pro »**, Linux seulement. Pour s'en servir, lire le
|
||||
[guide de l'utilisateur](docs/guide/README.md). Ce qui tourne:
|
||||
|
||||
- workspace Rust de huit crates, protocole partagé avec types TypeScript générés
|
||||
- `rs-capture`: interface de capture, avec une mire synthétique qui alimente tout le pipeline
|
||||
- `rs-codec`: conversion BGRA vers I420 en BT.709, encodeur VP8 libvpx, pont vers la session
|
||||
- `rs-rtc`: session str0m par spectateur, avec sa boucle testée
|
||||
- `rs-signaling`: serveur local, jeton de room, WebSocket de signalement, TLS auto-signé
|
||||
- `apps/viewer`: viewer React avec machine à états, reconnexion bornée, statistiques
|
||||
- une session complète de bout en bout: capture synthétique, encodage en direct, VP8 dans le
|
||||
navigateur, couleurs vérifiées à l'écran (voir `docs/perf.md` pour les mesures)
|
||||
- capture Linux réelle: portail et PipeWire sous Wayland, X11 en repli, chaque écran, une fenêtre
|
||||
seule, et un **second écran virtuel** créé par le bureau (GNOME 46, KDE Plasma);
|
||||
- encodage VP8 ou VP9 temps réel jusqu'à 60 images par seconde, une session WebRTC par spectateur;
|
||||
- application de bureau Tauri: choix de la source, QR code et code court, spectateurs, réglages,
|
||||
icône de barre système, français et anglais;
|
||||
- page du spectateur sans installation: reprise après coupure ou veille, rotation, miroir, plein
|
||||
écran;
|
||||
- appareils de confiance qui reviennent sans QR code, nom local `rustscreen.local`, lien à usage
|
||||
unique, changement de source sans couper les spectateurs;
|
||||
- journal local et archive de diagnostics expurgée, aucun appel sortant.
|
||||
|
||||
Restent à écrire: la capture réelle par OS (#8, #9, #10), la coque desktop Tauri (#15), et
|
||||
l'encodeur matériel (#53). Le prerequis de build hors Rust est libvpx: voir
|
||||
`scripts/build-libvpx.sh` et AGENTS.md.
|
||||
Reste à écrire: Windows (capture, encodeur matériel, intégration système). macOS n'est pas pris
|
||||
en charge comme hôte (#90); un Mac reste un spectateur comme un autre, par son navigateur. Les prérequis de build
|
||||
hors Rust sont libvpx (`scripts/build-libvpx.sh`) et, pour la capture Wayland, libpipewire-0.3 et
|
||||
libclang (`nix develop` fournit tout): voir AGENTS.md.
|
||||
|
||||
## Pourquoi
|
||||
|
||||
Deskreen fonctionne, mais son hôte Electron coûte 210 Mo sur disque, ~250 Mo de RAM par session et
|
||||
repose sur Chromium pour capturer et encoder. Un hôte Rust permet de capturer au plus près du
|
||||
système (DXGI, ScreenCaptureKit, PipeWire), d'encoder en VP8/H.264 matériel, et de servir un client
|
||||
système (PipeWire, DXGI), d'encoder en VP8/H.264 matériel, et de servir un client
|
||||
web minimal. Le spectateur reste un simple onglet, comme dans Deskreen.
|
||||
|
||||
Objectifs mesurables :
|
||||
@@ -43,7 +47,8 @@ offre SaaS multi-tenant. Ils sont cadrés dans le backlog comme extensions, pas
|
||||
|
||||
## Stack
|
||||
|
||||
- **Hôte** : Rust, `axum` (HTTP/WSS), `str0m` (WebRTC sans I/O), `scap` (capture), `libvpx` puis
|
||||
- **Hôte** : Rust, `axum` (HTTP/WSS), `str0m` (WebRTC sans I/O), portail `zbus` + `pipewire` et
|
||||
`x11rb` (capture), `libvpx` puis
|
||||
encodeurs matériels (`rs-codec`), `rustls` + `rcgen` (TLS local), `mdns-sd` (nom local)
|
||||
- **UI desktop** : Tauri v2, front TypeScript + React 19 + Vite
|
||||
- **Client spectateur** : TypeScript + Vite, `RTCPeerConnection` natif du navigateur, servi par
|
||||
@@ -56,40 +61,54 @@ offre SaaS multi-tenant. Ils sont cadrés dans le backlog comme extensions, pas
|
||||
```
|
||||
apps/desktop UI Tauri (front TS) + src-tauri (commandes, cycle de vie)
|
||||
apps/viewer client navigateur (TS, Vite)
|
||||
locales textes de l'interface, un fichier JSON par langue
|
||||
crates/rs-proto types partagés, versions, modèle de session
|
||||
crates/rs-capture abstraction de capture + implémentations par OS
|
||||
crates/rs-codec conversion de pixels et encodeurs vidéo
|
||||
crates/rs-rtc session str0m, ICE, DTLS, RTP, statistiques
|
||||
crates/rs-signaling serveur axum, WebSocket de signalement, QR code, TLS optionnel, viewer statique
|
||||
crates/rs-session orchestration des sessions, appareils, alias, confiance
|
||||
crates/rs-session l'hôte: partage, spectateurs, réglages, veille; binaire `rustscreen`
|
||||
crates/rs-platform autostart, inhibition de veille, interfaces réseau, MAC, tray
|
||||
crates/rs-store persistance locale (JSON)
|
||||
crates/rs-diag journal structuré local, archive de diagnostics
|
||||
docs architecture, ADR, matrice de fonctionnalités, backlog
|
||||
```
|
||||
|
||||
## Prérequis (une fois le code là)
|
||||
|
||||
- Rust stable (édition 2024), `cargo`
|
||||
- Node 22+ et npm 12 pour `apps/desktop` et `apps/viewer`
|
||||
- Node 22+, npm pour `apps/viewer`, pnpm pour `apps/desktop` (`nix develop .#desktop`)
|
||||
- Linux : PipeWire et `xdg-desktop-portal` (Wayland), X11 accepté en repli
|
||||
- macOS : 12.3+ pour ScreenCaptureKit
|
||||
- Windows : 10 1809+ pour la duplications de bureau DXGI
|
||||
- Windows : 10 1809+ pour la duplication de bureau DXGI (en cours, pas encore utilisable)
|
||||
|
||||
## Installer
|
||||
|
||||
```sh
|
||||
nix run . # Nix: reproductible, tout est inclus
|
||||
./scripts/build-appimage.sh # AppImage: un fichier, rien à installer
|
||||
nix run . # l'application de bureau (Nix: reproductible, tout est inclus)
|
||||
nix run .#rustscreen-cli # la ligne de commande seule
|
||||
./scripts/build-appimage.sh # AppImage de la ligne de commande: un fichier, rien à installer
|
||||
```
|
||||
|
||||
Détails, prérequis et limites dans [docs/PACKAGING.md](docs/PACKAGING.md). Les deux paquets
|
||||
démarrent aujourd'hui avec `--synthetic` : la capture d'un vrai écran reste à brancher (#8, #9, #10).
|
||||
capturent l'écran sous Wayland (portail) et X11; `--synthetic` reste là pour essayer sans écran.
|
||||
|
||||
## Licence
|
||||
|
||||
Apache-2.0, voir [LICENSE](LICENSE). Licence permissive avec clause de brevets explicite: elle
|
||||
laisse réutiliser le code, y compris dans un produit commercial, sans imposer de partager le reste.
|
||||
|
||||
Les dépendances livrées sont compatibles, et la CI le vérifie à chaque commit
|
||||
(`scripts/check-licenses.mjs`): MIT, Apache-2.0, BSD, ISC, Zlib pour l'essentiel; libvpx est en
|
||||
BSD-3-Clause; `env-libvpx-sys` et quelques crates de la coque (`cssparser`, `selectors`) sont en
|
||||
MPL-2.0, dont le copyleft porte sur leurs propres fichiers, livrés sans modification. WebKitGTK
|
||||
(LGPL-2.1) et PipeWire sont des bibliothèques du système, liées dynamiquement.
|
||||
|
||||
## Feuille de route
|
||||
|
||||
[docs/ROADMAP.md](docs/ROADMAP.md) dit ce qui doit exister pour une 1.0 honnête, dans quel ordre, et
|
||||
comment on décide qu'une release est prête. Le suivi vivant est dans les jalons Gitea et le projet
|
||||
« Roadmap 1.0 ».
|
||||
|
||||
## Suivre le travail
|
||||
|
||||
Le découpage complet est dans [docs/backlog.md](docs/backlog.md), une issue par sujet, avec les
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>rustscreen</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "@rustscreen/desktop",
|
||||
"private": true,
|
||||
"version": "0.5.0",
|
||||
"type": "module",
|
||||
"packageManager": "pnpm@12.15.0",
|
||||
"description": "rustscreen desktop shell: pick the source, see the viewers, stop.",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc --noEmit && vite build",
|
||||
"lint": "biome lint src && node ../../scripts/check-i18n.mjs apps/desktop/src desktop",
|
||||
"format": "biome format --write src",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "^2.12.3",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@biomejs/biome": "^2.6.0",
|
||||
"@types/react": "^19.2.0",
|
||||
"@types/react-dom": "^19.2.0",
|
||||
"@vitejs/plugin-react": "^6.1.0",
|
||||
"typescript": "~7.0.0",
|
||||
"vite": "^8.3.0",
|
||||
"vitest": "^5.0.5"
|
||||
}
|
||||
}
|
||||
Generated
+1203
File diff suppressed because it is too large.
Load diff
Generated
+6546
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,47 @@
|
||||
[package]
|
||||
name = "rustscreen-desktop"
|
||||
description = "rustscreen desktop shell: choose what to share, see who is watching, stop."
|
||||
version = "0.5.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.90"
|
||||
license = "Apache-2.0"
|
||||
repository = "https://gitea-nubo.hopledge.com/heap/rustscreen"
|
||||
|
||||
# Outside the main workspace: WebKitGTK and GTK are needed at build time, and
|
||||
# the host CI does not have them. `nix develop .#desktop` provides them.
|
||||
# Launching rustscreen opens this desktop application (#84); the command line
|
||||
# is `rustscreen-cli` (crates/rs-session).
|
||||
[[bin]]
|
||||
name = "rustscreen"
|
||||
path = "src/main.rs"
|
||||
|
||||
[workspace]
|
||||
|
||||
[features]
|
||||
# The built interface (`dist`) is embedded in the binary. Without this
|
||||
# feature, Tauri loads `devUrl` (the Vite server, `pnpm dev`): that is the
|
||||
# development mode, `--no-default-features`. The Tauri CLI makes this choice on
|
||||
# its own; we do without it, hence the explicit choice.
|
||||
default = ["custom-protocol"]
|
||||
custom-protocol = ["tauri/custom-protocol"]
|
||||
# Real Wayland capture (ADR 0009), like the command-line binary.
|
||||
pipewire = ["rs-session/pipewire"]
|
||||
# Hardware encoding (#57), like the command-line binary.
|
||||
vaapi = ["rs-session/vaapi"]
|
||||
|
||||
[dependencies]
|
||||
rs-diag = { path = "../../../crates/rs-diag" }
|
||||
rs-platform = { path = "../../../crates/rs-platform" }
|
||||
rs-session = { path = "../../../crates/rs-session" }
|
||||
rs-store = { path = "../../../crates/rs-store" }
|
||||
# `tray-icon`: system tray icon (#22); `image-png`: its icons.
|
||||
tauri = { version = "2.12.5", features = ["tray-icon", "image-png"] }
|
||||
tracing = "0.1"
|
||||
serde = { version = "1.0.229", features = ["derive"] }
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
# Trial load of libayatana-appindicator before creating the icon (#22).
|
||||
libloading = "0.8.9"
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "2.7.4", features = [] }
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() {
|
||||
tauri_build::build();
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "The main window: listen to the host state. The application commands are allowed by default.",
|
||||
"windows": ["main"],
|
||||
"permissions": ["core:default"]
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 361 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.3 KiB |
@@ -0,0 +1,370 @@
|
||||
//! rustscreen desktop shell (#15): the screen the host sees.
|
||||
//!
|
||||
//! It does nothing but relay: each command calls [`rs_session::Host`], and
|
||||
//! each state change goes to the interface through the `state` event, the
|
||||
//! complete state every time. The interface therefore keeps no share state of
|
||||
//! its own, and cannot show a button that lies.
|
||||
|
||||
mod tray;
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use rs_session::{
|
||||
Config, Host, HostState, InterfaceOption, Overrides, Phase, SettingsOutcome, SourceChoice,
|
||||
SourceOption,
|
||||
};
|
||||
use rs_store::{CloseAction, Notice, Rejection, Settings};
|
||||
use tauri::{Emitter, Manager, RunEvent, State, WindowEvent};
|
||||
|
||||
/// The last started source, so that the system tray menu can restart a share
|
||||
/// without opening the window.
|
||||
#[derive(Default)]
|
||||
struct LastSource(Mutex<Option<SourceChoice>>);
|
||||
|
||||
/// The system tray icon, if this desktop has one: without it, hiding the
|
||||
/// window would make the application impossible to find.
|
||||
struct MaybeTray(Option<Arc<tray::Tray<tauri::Wry>>>);
|
||||
|
||||
impl MaybeTray {
|
||||
fn present(&self) -> bool {
|
||||
self.0.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
fn last_source_known(app: &tauri::AppHandle) -> bool {
|
||||
app.state::<LastSource>()
|
||||
.0
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.is_some()
|
||||
}
|
||||
|
||||
// The binary is `rustscreen` (#84): its log target follows.
|
||||
const FILTER: &str = "rustscreen=info,rs_session=info,rs_signaling=info,rs_rtc=info,\
|
||||
rs_capture=info,rs_codec=info,rs_platform=info,rs_diag=info,\
|
||||
rs_store=info,str0m=warn";
|
||||
|
||||
#[tauri::command]
|
||||
fn state(host: State<'_, Host>) -> HostState {
|
||||
host.state()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn sources(host: State<'_, Host>) -> Result<Vec<SourceOption>, ()> {
|
||||
Ok(host.sources().await)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn start(
|
||||
host: State<'_, Host>,
|
||||
last: State<'_, LastSource>,
|
||||
choice: SourceChoice,
|
||||
) -> Result<(), Notice> {
|
||||
*last.0.lock().unwrap_or_else(|e| e.into_inner()) = Some(choice.clone());
|
||||
host.start(choice).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn stop(host: State<'_, Host>) -> Result<(), ()> {
|
||||
host.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn disconnect(host: State<'_, Host>, connection: u64) -> bool {
|
||||
host.disconnect(connection)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn regenerate_access(host: State<'_, Host>) -> bool {
|
||||
host.regenerate_access()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn trust_device(host: State<'_, Host>, connection: u64) -> Result<(), Notice> {
|
||||
host.trust_device(connection).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn switch_source(
|
||||
host: State<'_, Host>,
|
||||
last: State<'_, LastSource>,
|
||||
choice: SourceChoice,
|
||||
) -> Result<(), Notice> {
|
||||
host.switch_source(choice.clone()).await?;
|
||||
*last.0.lock().unwrap_or_else(|e| e.into_inner()) = Some(choice);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn rename_device(
|
||||
host: State<'_, Host>,
|
||||
connection: u64,
|
||||
alias: Option<String>,
|
||||
) -> Result<(), Notice> {
|
||||
host.rename_device(connection, alias).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn revoke_device(host: State<'_, Host>, key: String) -> Result<(), Notice> {
|
||||
host.revoke_device(&key).await
|
||||
}
|
||||
|
||||
/// The texts of the system tray menu, in the language of the interface.
|
||||
#[tauri::command]
|
||||
fn translate_tray(
|
||||
app: tauri::AppHandle,
|
||||
host: State<'_, Host>,
|
||||
tray: State<'_, MaybeTray>,
|
||||
texts: tray::TrayTexts,
|
||||
) {
|
||||
if let Some(tray) = &tray.0 {
|
||||
tray.translate(texts);
|
||||
tray.follow(&host.state(), last_source_known(&app));
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn settings(host: State<'_, Host>) -> Settings {
|
||||
host.settings()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn update_settings(
|
||||
host: State<'_, Host>,
|
||||
settings: Settings,
|
||||
) -> Result<SettingsOutcome, Vec<Rejection>> {
|
||||
host.update_settings(settings).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn interfaces(host: State<'_, Host>) -> Vec<InterfaceOption> {
|
||||
host.interfaces()
|
||||
}
|
||||
|
||||
/// Writes the diagnostics archive to the download folder and returns its
|
||||
/// path: the user sends it themselves (ADR 0008).
|
||||
#[tauri::command]
|
||||
async fn export_diagnostics(host: State<'_, Host>) -> Result<String, String> {
|
||||
let host = host.inner().clone();
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let (name, bytes) = host.diagnostics()?;
|
||||
let dir = download_dir();
|
||||
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
|
||||
let path = dir.join(name);
|
||||
std::fs::write(&path, bytes).map_err(|e| e.to_string())?;
|
||||
tracing::info!(event = "diagnostics_exported", "archive written");
|
||||
Ok(path.display().to_string())
|
||||
})
|
||||
.await
|
||||
.map_err(|e| e.to_string())?
|
||||
}
|
||||
|
||||
/// `XDG_DOWNLOAD_DIR` from `user-dirs.dirs` when it exists, otherwise the home
|
||||
/// folder.
|
||||
fn download_dir() -> PathBuf {
|
||||
let home = std::env::var_os("HOME")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_default();
|
||||
let config = std::env::var_os("XDG_CONFIG_HOME")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| home.join(".config"));
|
||||
std::fs::read_to_string(config.join("user-dirs.dirs"))
|
||||
.ok()
|
||||
.and_then(|text| {
|
||||
text.lines().find_map(|line| {
|
||||
let value = line.strip_prefix("XDG_DOWNLOAD_DIR=")?.trim_matches('"');
|
||||
Some(PathBuf::from(
|
||||
value.replace("$HOME", &home.display().to_string()),
|
||||
))
|
||||
})
|
||||
})
|
||||
.unwrap_or(home)
|
||||
}
|
||||
|
||||
/// A click in the system tray menu.
|
||||
fn on_tray_click(app: &tauri::AppHandle, id: &str) {
|
||||
let host = app.state::<Host>().inner().clone();
|
||||
match id {
|
||||
tray::OPEN => tray::show(app),
|
||||
tray::START => {
|
||||
let last = app
|
||||
.state::<LastSource>()
|
||||
.0
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.clone();
|
||||
match last {
|
||||
Some(choice) => {
|
||||
tauri::async_runtime::spawn(async move {
|
||||
// The failure shows in the window, through the state.
|
||||
let _ = host.start(choice).await;
|
||||
});
|
||||
}
|
||||
None => tray::show(app),
|
||||
}
|
||||
}
|
||||
tray::STOP => {
|
||||
tauri::async_runtime::spawn(async move { host.stop().await });
|
||||
}
|
||||
tray::QUIT => request_quit(app),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Autostart argument: the application starts hidden in the system tray
|
||||
/// (#32).
|
||||
const AUTOSTARTED: &str = "--autostarted";
|
||||
/// The former spelling, still written in the `.desktop` files of existing
|
||||
/// installations: it keeps being accepted.
|
||||
const AUTOSTARTED_LEGACY: &str = "--au-demarrage";
|
||||
|
||||
/// Quit, or ask first if a share is running (#43): a reflex gesture must not
|
||||
/// cut a presentation short. The window comes back and asks the question; the
|
||||
/// `quit` command concludes.
|
||||
fn request_quit(app: &tauri::AppHandle) {
|
||||
let host = app.state::<Host>();
|
||||
if host.state().phase == Phase::Stopped || !host.settings().confirm_quit {
|
||||
app.exit(0);
|
||||
return;
|
||||
}
|
||||
tray::show(app);
|
||||
if let Err(error) = app.emit("confirm-quit", ()) {
|
||||
tracing::warn!(%error, "quit confirmation not requested: quitting");
|
||||
app.exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Answer to the confirmation: quit, and stop asking if so wished.
|
||||
#[tauri::command]
|
||||
async fn quit(
|
||||
app: tauri::AppHandle,
|
||||
host: State<'_, Host>,
|
||||
dont_ask_again: bool,
|
||||
) -> Result<(), Vec<Rejection>> {
|
||||
if dont_ask_again {
|
||||
let mut settings = host.settings();
|
||||
settings.confirm_quit = false;
|
||||
host.update_settings(settings).await?;
|
||||
}
|
||||
app.exit(0);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let log = rs_diag::init(rs_diag::log_dir().as_deref(), FILTER);
|
||||
// Autostart relaunches this binary. An AppImage runs from a temporary
|
||||
// mount: its file is what must be relaunched.
|
||||
let executable = std::env::var_os("APPIMAGE")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| std::env::current_exe().ok())
|
||||
.map(|exe| rs_platform::autostart::launcher(&exe, std::env::var_os("PATH").as_deref()));
|
||||
// An update may have moved the binary: the autostart entry follows (#32).
|
||||
if let (Some(exe), Some(dir)) = (&executable, rs_platform::autostart::directory()) {
|
||||
match rs_platform::autostart::refresh(&dir, exe, AUTOSTARTED) {
|
||||
Ok(true) => tracing::info!(event = "autostart_refreshed", "autostart entry updated"),
|
||||
Ok(false) => {}
|
||||
Err(error) => tracing::warn!(%error, "autostart entry not updated"),
|
||||
}
|
||||
}
|
||||
let autostarted = std::env::args().any(|a| a == AUTOSTARTED || a == AUTOSTARTED_LEGACY);
|
||||
|
||||
let host = tauri::async_runtime::block_on(Host::new(Config {
|
||||
version: env!("CARGO_PKG_VERSION").into(),
|
||||
viewer_dir: std::env::var_os("RUSTSCREEN_VIEWER")
|
||||
.map(PathBuf::from)
|
||||
.or_else(rs_session::installed_viewer),
|
||||
tls: false,
|
||||
store: rs_store::Store::user_default(),
|
||||
overrides: Overrides::default(),
|
||||
log_dir: log.dir.clone(),
|
||||
autostart: executable.map(|exe| (exe, AUTOSTARTED.to_string())),
|
||||
}));
|
||||
|
||||
let application = tauri::Builder::default()
|
||||
.manage(host.clone())
|
||||
.manage(LastSource::default())
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
state,
|
||||
sources,
|
||||
start,
|
||||
stop,
|
||||
disconnect,
|
||||
regenerate_access,
|
||||
trust_device,
|
||||
revoke_device,
|
||||
rename_device,
|
||||
switch_source,
|
||||
translate_tray,
|
||||
quit,
|
||||
settings,
|
||||
update_settings,
|
||||
interfaces,
|
||||
export_diagnostics,
|
||||
])
|
||||
.setup(move |app| {
|
||||
let tray = tray::Tray::create(app.handle(), on_tray_click).map(Arc::new);
|
||||
app.manage(MaybeTray(tray.clone()));
|
||||
// The window is created hidden: at session start, it stays so if
|
||||
// the system tray exists to find it again; otherwise it is shown,
|
||||
// an invisible application would be lost.
|
||||
if !(autostarted && tray.is_some()) {
|
||||
tray::show(app.handle());
|
||||
}
|
||||
// The state goes to the interface and to the icon on each change,
|
||||
// complete: the icon follows the real state at the same moment as
|
||||
// the window.
|
||||
let handle = app.handle().clone();
|
||||
let mut subscriber = host.subscribe();
|
||||
if let Some(tray) = &tray {
|
||||
tray.follow(&subscriber.borrow(), false);
|
||||
}
|
||||
tauri::async_runtime::spawn(async move {
|
||||
while subscriber.changed().await.is_ok() {
|
||||
let state = subscriber.borrow_and_update().clone();
|
||||
if let Some(tray) = &tray {
|
||||
tray.follow(&state, last_source_known(&handle));
|
||||
}
|
||||
if let Err(error) = handle.emit("state", state) {
|
||||
tracing::warn!(%error, "state not sent to the interface");
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
})
|
||||
.on_window_event(|window, event| {
|
||||
if let WindowEvent::CloseRequested { api, .. } = event {
|
||||
let app = window.app_handle();
|
||||
let host = app.state::<Host>();
|
||||
if host.settings().close_action == CloseAction::Quit {
|
||||
// Closing means quitting: same confirmation as the menu.
|
||||
api.prevent_close();
|
||||
request_quit(app);
|
||||
return;
|
||||
}
|
||||
// Closing does not cut a share (#22): the window hides in the
|
||||
// system tray. Without a tray, it minimizes during a share,
|
||||
// and closes the application otherwise.
|
||||
if app.state::<MaybeTray>().present() {
|
||||
api.prevent_close();
|
||||
let _ = window.hide();
|
||||
} else if host.state().phase != Phase::Stopped {
|
||||
api.prevent_close();
|
||||
let _ = window.minimize();
|
||||
}
|
||||
}
|
||||
})
|
||||
.build(tauri::generate_context!())
|
||||
.expect("Tauri application");
|
||||
|
||||
application.run(move |app, event| {
|
||||
// Quitting stops the share cleanly: portal session closed, sleep
|
||||
// released, viewers told.
|
||||
if let RunEvent::Exit = event {
|
||||
let host = app.state::<Host>().inner().clone();
|
||||
tauri::async_runtime::block_on(host.stop());
|
||||
}
|
||||
});
|
||||
drop(log);
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
//! System tray icon and session menu (#22).
|
||||
//!
|
||||
//! The icon tells the real state: it follows the same `state` as the window,
|
||||
//! at the same moment, so in well under a second. The menu can start (the last
|
||||
//! chosen source), stop, open the window and quit, without the window being
|
||||
//! open.
|
||||
//!
|
||||
//! On Linux, the icon goes through StatusNotifierItem (libayatana-appindicator,
|
||||
//! loaded at run time). GNOME without the AppIndicator extension shows nothing:
|
||||
//! [`available`] detects it, and closing the window then falls back to a plain
|
||||
//! minimize, so as never to hide a share with no way to find it again.
|
||||
//!
|
||||
//! The texts come from the interface (`translate_tray`), in its language
|
||||
//! (#21): translations live in `locales/`, not here. The English below (the fallback language) only
|
||||
//! serves before the first update.
|
||||
|
||||
use std::sync::Mutex;
|
||||
|
||||
use rs_session::{HostState, Phase};
|
||||
use serde::Deserialize;
|
||||
use tauri::image::Image;
|
||||
use tauri::menu::{Menu, MenuItem, PredefinedMenuItem};
|
||||
use tauri::tray::{MouseButton, MouseButtonState, TrayIcon, TrayIconBuilder, TrayIconEvent};
|
||||
use tauri::{AppHandle, Manager, Runtime};
|
||||
|
||||
const ICON: &[u8] = include_bytes!("../icons/icon.png");
|
||||
|
||||
/// What the menu offers; the identifier comes back in the click event.
|
||||
pub const OPEN: &str = "open";
|
||||
pub const START: &str = "start";
|
||||
pub const STOP: &str = "stop";
|
||||
pub const QUIT: &str = "quit";
|
||||
|
||||
/// The forms of the live status: Rust does not know the plural rules of each
|
||||
/// language, the interface gives it those for 0, for 1 and for the rest.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct PluralForms {
|
||||
pub zero: String,
|
||||
pub one: String,
|
||||
/// With `{count}` to replace.
|
||||
pub other: String,
|
||||
}
|
||||
|
||||
/// The menu texts, translated by the interface.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct TrayTexts {
|
||||
pub none: String,
|
||||
pub starting: String,
|
||||
pub live: PluralForms,
|
||||
pub open: String,
|
||||
pub start: String,
|
||||
pub resume: String,
|
||||
pub stop: String,
|
||||
pub quit: String,
|
||||
}
|
||||
|
||||
impl Default for TrayTexts {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
none: "Not sharing".into(),
|
||||
starting: "Starting to share…".into(),
|
||||
live: PluralForms {
|
||||
zero: "Live, nobody is watching".into(),
|
||||
one: "Live, 1 viewer".into(),
|
||||
other: "Live, {count} viewers".into(),
|
||||
},
|
||||
open: "Open rustscreen".into(),
|
||||
start: "Start sharing…".into(),
|
||||
resume: "Resume the last share".into(),
|
||||
stop: "Stop sharing".into(),
|
||||
quit: "Quit".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TrayTexts {
|
||||
fn status(&self, state: &HostState) -> String {
|
||||
match state.phase {
|
||||
Phase::Stopped => self.none.clone(),
|
||||
Phase::Starting => self.starting.clone(),
|
||||
Phase::Live => match state.share.as_ref().map_or(0, |s| s.devices.len()) {
|
||||
0 => self.live.zero.clone(),
|
||||
1 => self.live.one.clone(),
|
||||
n => self.live.other.replace("{count}", &n.to_string()),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Tray<R: Runtime> {
|
||||
icon: TrayIcon<R>,
|
||||
status: MenuItem<R>,
|
||||
open: MenuItem<R>,
|
||||
start: MenuItem<R>,
|
||||
stop: MenuItem<R>,
|
||||
quit: MenuItem<R>,
|
||||
idle: Image<'static>,
|
||||
live: Image<'static>,
|
||||
texts: Mutex<TrayTexts>,
|
||||
}
|
||||
|
||||
impl<R: Runtime> Tray<R> {
|
||||
/// Creates the icon and its menu. `None` when this desktop has no system
|
||||
/// tray: the application then lives in its window only.
|
||||
pub fn create(
|
||||
app: &AppHandle<R>,
|
||||
on_click: impl Fn(&AppHandle<R>, &str) + Send + Sync + 'static,
|
||||
) -> Option<Self> {
|
||||
if !available() {
|
||||
tracing::info!("no system tray on this desktop: window only");
|
||||
return None;
|
||||
}
|
||||
let build = || -> tauri::Result<Self> {
|
||||
let idle = Image::from_bytes(ICON)?.to_owned();
|
||||
let live = with_dot(&idle);
|
||||
let texts = TrayTexts::default();
|
||||
let status = MenuItem::with_id(app, "status", &texts.none, false, None::<&str>)?;
|
||||
let open = MenuItem::with_id(app, OPEN, &texts.open, true, None::<&str>)?;
|
||||
let start = MenuItem::with_id(app, START, &texts.start, true, None::<&str>)?;
|
||||
let stop = MenuItem::with_id(app, STOP, &texts.stop, false, None::<&str>)?;
|
||||
let quit = MenuItem::with_id(app, QUIT, &texts.quit, true, None::<&str>)?;
|
||||
let menu = Menu::with_items(
|
||||
app,
|
||||
&[
|
||||
&status,
|
||||
&PredefinedMenuItem::separator(app)?,
|
||||
&open,
|
||||
&start,
|
||||
&stop,
|
||||
&PredefinedMenuItem::separator(app)?,
|
||||
&quit,
|
||||
],
|
||||
)?;
|
||||
let icon = TrayIconBuilder::with_id("rustscreen")
|
||||
.icon(idle.clone())
|
||||
.tooltip(format!("rustscreen: {}", texts.none))
|
||||
.menu(&menu)
|
||||
.show_menu_on_left_click(false)
|
||||
.on_menu_event(move |app, event| on_click(app, event.id().as_ref()))
|
||||
.on_tray_icon_event(|icon, event| {
|
||||
// Windows and macOS: a left click reopens the window. On
|
||||
// Linux, StatusNotifierItem only sends the menu.
|
||||
if let TrayIconEvent::Click {
|
||||
button: MouseButton::Left,
|
||||
button_state: MouseButtonState::Up,
|
||||
..
|
||||
} = event
|
||||
{
|
||||
show(icon.app_handle());
|
||||
}
|
||||
})
|
||||
.build(app)?;
|
||||
Ok(Self {
|
||||
icon,
|
||||
status,
|
||||
open,
|
||||
start,
|
||||
stop,
|
||||
quit,
|
||||
idle,
|
||||
live,
|
||||
texts: Mutex::new(texts),
|
||||
})
|
||||
};
|
||||
match build() {
|
||||
Ok(tray) => Some(tray),
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "system tray icon impossible");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Changes the menu language; the caller redraws with [`Tray::follow`].
|
||||
pub fn translate(&self, texts: TrayTexts) {
|
||||
let result = (|| -> tauri::Result<()> {
|
||||
self.open.set_text(&texts.open)?;
|
||||
self.stop.set_text(&texts.stop)?;
|
||||
self.quit.set_text(&texts.quit)?;
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(error) = result {
|
||||
tracing::warn!(%error, "system tray menu not translated");
|
||||
}
|
||||
*self.texts.lock().unwrap_or_else(|e| e.into_inner()) = texts;
|
||||
}
|
||||
|
||||
/// Makes the icon, the tooltip and the menu match the state.
|
||||
pub fn follow(&self, state: &HostState, last_source: bool) {
|
||||
let texts = self.texts.lock().unwrap_or_else(|e| e.into_inner()).clone();
|
||||
let text = texts.status(state);
|
||||
let icon = if state.phase == Phase::Live {
|
||||
&self.live
|
||||
} else {
|
||||
&self.idle
|
||||
};
|
||||
let result = (|| -> tauri::Result<()> {
|
||||
self.icon.set_icon(Some(icon.clone()))?;
|
||||
self.icon.set_tooltip(Some(format!("rustscreen: {text}")))?;
|
||||
self.status.set_text(&text)?;
|
||||
// Starting from the menu restarts the last source; without one,
|
||||
// the menu opens the window to pick one.
|
||||
self.start.set_text(if last_source {
|
||||
&texts.resume
|
||||
} else {
|
||||
&texts.start
|
||||
})?;
|
||||
self.start.set_enabled(state.phase == Phase::Stopped)?;
|
||||
self.stop.set_enabled(state.phase != Phase::Stopped)?;
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(error) = result {
|
||||
tracing::warn!(%error, "system tray not updated");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reopens the main window, hidden or minimized.
|
||||
pub fn show<R: Runtime>(app: &AppHandle<R>) {
|
||||
if let Some(window) = app.get_webview_window("main") {
|
||||
let _ = window.unminimize();
|
||||
let _ = window.show();
|
||||
let _ = window.set_focus();
|
||||
}
|
||||
}
|
||||
|
||||
/// Is there a system tray? On Linux, it takes a StatusNotifierItem host on the
|
||||
/// session bus and the library that talks to it.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn available() -> bool {
|
||||
let library = ["libayatana-appindicator3.so.1", "libappindicator3.so.1"]
|
||||
.iter()
|
||||
.any(|name| library_loads(name));
|
||||
library && status_notifier_host()
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
fn available() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Can the dynamic loader open this library? tray-icon panics otherwise,
|
||||
/// instead of returning an error. Looking for the file is not enough: a binary
|
||||
/// built by Nix does not read the system cache, the same loading as its own
|
||||
/// must be tried.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn library_loads(name: &str) -> bool {
|
||||
// SAFETY: this is the library tray-icon will load anyway right after,
|
||||
// through the same search path; its constructors (GObject type
|
||||
// registration) are meant to run once loaded, and keeping it loaded avoids
|
||||
// a second pass.
|
||||
match unsafe { libloading::Library::new(name) } {
|
||||
Ok(library) => {
|
||||
std::mem::forget(library);
|
||||
true
|
||||
}
|
||||
Err(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Does `org.kde.StatusNotifierWatcher` have an owner on the session bus? It
|
||||
/// is the one that shows the icons (KDE, Ubuntu, GNOME with the AppIndicator
|
||||
/// extension).
|
||||
#[cfg(target_os = "linux")]
|
||||
fn status_notifier_host() -> bool {
|
||||
std::process::Command::new("busctl")
|
||||
.args([
|
||||
"--user",
|
||||
"call",
|
||||
"org.freedesktop.DBus",
|
||||
"/org/freedesktop/DBus",
|
||||
"org.freedesktop.DBus",
|
||||
"NameHasOwner",
|
||||
"s",
|
||||
"org.kde.StatusNotifierWatcher",
|
||||
])
|
||||
.output()
|
||||
.is_ok_and(|output| String::from_utf8_lossy(&output.stdout).trim() == "b true")
|
||||
}
|
||||
|
||||
/// The "live" icon: the same one, with a red dot at the bottom right, readable
|
||||
/// even at 16 pixels.
|
||||
fn with_dot(base: &Image<'_>) -> Image<'static> {
|
||||
let (w, h) = (base.width(), base.height());
|
||||
let mut rgba = base.rgba().to_vec();
|
||||
let radius = w.min(h) as f32 * 0.22;
|
||||
let (cx, cy) = (w as f32 - radius - 1.0, h as f32 - radius - 1.0);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let d = ((x as f32 + 0.5 - cx).powi(2) + (y as f32 + 0.5 - cy).powi(2)).sqrt();
|
||||
let i = ((y * w + x) * 4) as usize;
|
||||
if d <= radius {
|
||||
rgba[i..i + 4].copy_from_slice(&[0xdc, 0x26, 0x26, 0xff]);
|
||||
} else if d <= radius + w as f32 * 0.03 {
|
||||
// White rim: the dot stands out on a dark bar as on a light
|
||||
// one.
|
||||
rgba[i..i + 4].copy_from_slice(&[0xff, 0xff, 0xff, 0xff]);
|
||||
}
|
||||
}
|
||||
}
|
||||
Image::new_owned(rgba, w, h)
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "rustscreen",
|
||||
"version": "0.5.0",
|
||||
"identifier": "local.rustscreen.desktop",
|
||||
"build": {
|
||||
"frontendDist": "../dist",
|
||||
"devUrl": "http://localhost:5175"
|
||||
},
|
||||
"app": {
|
||||
"windows": [
|
||||
{
|
||||
"label": "main",
|
||||
"title": "rustscreen",
|
||||
"width": 1100,
|
||||
"height": 760,
|
||||
"minWidth": 800,
|
||||
"minHeight": 560,
|
||||
"visible": false
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; connect-src ipc: http://ipc.localhost"
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
"active": false,
|
||||
"icon": ["icons/icon.png", "icons/icon.ico"]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import type { HostState } from './bindings/HostState';
|
||||
import type { SourceChoice } from './bindings/SourceChoice';
|
||||
import type { SourceOption } from './bindings/SourceOption';
|
||||
import type { Theme } from './bindings/Theme';
|
||||
import { ConfirmQuit } from './components/ConfirmQuit';
|
||||
import { SettingsDialog } from './components/SettingsDialog';
|
||||
import { SharePanel } from './components/SharePanel';
|
||||
import { SourcePicker } from './components/SourcePicker';
|
||||
import { effectiveLanguage, I18nProvider, useI18n } from './i18n';
|
||||
import { type Host, rejectionsOf } from './lib/host';
|
||||
import { actions, isVirtual, key, say, status, trayTexts, withSize } from './lib/view';
|
||||
|
||||
/**
|
||||
* The language comes from the host settings, or from the desktop. Changing it
|
||||
* retranslates the interface and the system tray menu at the next render
|
||||
* (#21).
|
||||
*/
|
||||
export function App({ host }: { host: Host }) {
|
||||
const [setting, setSetting] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
host.settings().then((s) => setSetting(s.language));
|
||||
}, [host]);
|
||||
const language = effectiveLanguage(setting, navigator.languages ?? [navigator.language]);
|
||||
return (
|
||||
<I18nProvider language={language}>
|
||||
<Shell host={host} onLanguage={setSetting} />
|
||||
</I18nProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function Shell({ host, onLanguage }: { host: Host; onLanguage: (code: string | null) => void }) {
|
||||
const { t, language } = useI18n();
|
||||
const [state, setState] = useState<HostState | null>(null);
|
||||
const [sources, setSources] = useState<SourceOption[] | null>(null);
|
||||
const [selection, setSelection] = useState<SourceChoice | null>(null);
|
||||
const [sending, setSending] = useState(false);
|
||||
const [settingsOpen, setSettingsOpen] = useState(false);
|
||||
const [confirmQuit, setConfirmQuit] = useState(false);
|
||||
// Picking another source while sharing (#26): viewers stay connected.
|
||||
const [switching, setSwitching] = useState(false);
|
||||
const [theme, setTheme] = useState<Theme>('system');
|
||||
|
||||
// The state comes from the host, always complete: subscribe before reading,
|
||||
// so as not to miss a change in between.
|
||||
useEffect(() => {
|
||||
let unlisten: (() => void) | undefined;
|
||||
let done = false;
|
||||
host.listen(setState).then((stop) => {
|
||||
if (done) stop();
|
||||
else unlisten = stop;
|
||||
});
|
||||
host.state().then(setState);
|
||||
let unlistenQuit: (() => void) | undefined;
|
||||
host
|
||||
.listenQuit(() => setConfirmQuit(true))
|
||||
.then((stop) => {
|
||||
if (done) stop();
|
||||
else unlistenQuit = stop;
|
||||
});
|
||||
host.settings().then((s) => setTheme(s.theme));
|
||||
return () => {
|
||||
done = true;
|
||||
unlisten?.();
|
||||
unlistenQuit?.();
|
||||
};
|
||||
}, [host]);
|
||||
|
||||
useEffect(() => {
|
||||
document.documentElement.dataset.theme = theme;
|
||||
}, [theme]);
|
||||
|
||||
// The system tray menu is drawn by Rust: it receives its texts in the
|
||||
// language of the interface.
|
||||
useEffect(() => {
|
||||
document.documentElement.lang = language;
|
||||
host.translateTray(trayTexts(t)).catch(() => undefined);
|
||||
}, [host, t, language]);
|
||||
|
||||
const refresh = useCallback(() => {
|
||||
setSources(null);
|
||||
host.sources().then((list) => {
|
||||
setSources(list);
|
||||
// A selection that vanished (window closed) is not kept silently.
|
||||
setSelection((choice) =>
|
||||
choice && list.some((s) => key(s.choice) === key(choice))
|
||||
? choice
|
||||
: (list[0]?.choice ?? null),
|
||||
);
|
||||
});
|
||||
}, [host]);
|
||||
|
||||
// The size is a setting (#89): saved at once, it applies to the next start
|
||||
// or, while sharing, to the next "Switch to".
|
||||
const changeVirtualSize = useCallback(
|
||||
async (size: [number, number]) => {
|
||||
const settings = await host.settings();
|
||||
try {
|
||||
await host.updateSettings({ ...settings, virtual_size: size });
|
||||
} catch (e) {
|
||||
throw rejectionsOf(e)
|
||||
.map((r) => say(r.message, t))
|
||||
.join('; ');
|
||||
}
|
||||
setSelection((choice) => choice && withSize(choice, size));
|
||||
setSources(
|
||||
(list) =>
|
||||
list?.map((s) =>
|
||||
isVirtual(s.choice)
|
||||
? { ...s, choice: withSize(s.choice, size), width: size[0], height: size[1] }
|
||||
: s,
|
||||
) ?? null,
|
||||
);
|
||||
},
|
||||
[host, t],
|
||||
);
|
||||
|
||||
const phase = state?.phase;
|
||||
useEffect(() => {
|
||||
if (phase === 'stopped') {
|
||||
refresh();
|
||||
}
|
||||
}, [phase, refresh]);
|
||||
|
||||
if (!state) {
|
||||
return <div className='loading'>{t('title')}</div>;
|
||||
}
|
||||
|
||||
const buttons = actions(state, selection, sending);
|
||||
const badge = status(state, t);
|
||||
const send = async (command: () => Promise<unknown>) => {
|
||||
setSending(true);
|
||||
try {
|
||||
await command();
|
||||
} catch {
|
||||
// The error also arrives in the state (`error`), which shows it.
|
||||
} finally {
|
||||
setSending(false);
|
||||
}
|
||||
};
|
||||
const portal = selection?.type === 'portal';
|
||||
const live = state.phase === 'live' && state.share !== null;
|
||||
const picking = switching && live;
|
||||
const switchTo = (choice: SourceChoice) =>
|
||||
send(async () => {
|
||||
await host.switchSource(choice);
|
||||
setSwitching(false);
|
||||
});
|
||||
|
||||
return (
|
||||
<div className='app'>
|
||||
<header className='header'>
|
||||
<h1>{t('title')}</h1>
|
||||
<span className={`badge ${badge.tone}`} role='status'>
|
||||
{badge.text}
|
||||
</span>
|
||||
{state.phase === 'live' && (
|
||||
<span className='sleep' title={state.sleep_inhibited.join(', ')}>
|
||||
{state.sleep_inhibited.length > 0 ? t('sleepInhibited') : t('sleepNotInhibited')}
|
||||
</span>
|
||||
)}
|
||||
<span className='spacer' />
|
||||
<button type='button' className='button muted' onClick={() => setSettingsOpen(true)}>
|
||||
{t('settings')}
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<main className='content'>
|
||||
<Banners state={state} />
|
||||
|
||||
{state.phase === 'live' && state.share && !picking ? (
|
||||
<SharePanel
|
||||
share={state.share}
|
||||
onDisconnect={(connection) => send(() => host.disconnect(connection))}
|
||||
onNewCode={() => send(() => host.regenerateAccess())}
|
||||
onTrust={(connection) => send(() => host.trustDevice(connection))}
|
||||
onRename={(connection, alias) => send(() => host.renameDevice(connection, alias))}
|
||||
/>
|
||||
) : (
|
||||
<SourcePicker
|
||||
sources={sources}
|
||||
selection={selection}
|
||||
enabled={buttons.pick || picking}
|
||||
onPick={setSelection}
|
||||
onRefresh={refresh}
|
||||
onVirtualSize={changeVirtualSize}
|
||||
/>
|
||||
)}
|
||||
</main>
|
||||
|
||||
<footer className='action-bar'>
|
||||
{(state.phase === 'starting' || (picking && sending)) && (
|
||||
<p className='waiting' role='status'>
|
||||
{portal ? t('waitingDesktop') : t('waiting')}
|
||||
</p>
|
||||
)}
|
||||
<span className='spacer' />
|
||||
{picking && (
|
||||
<>
|
||||
<button
|
||||
type='button'
|
||||
className='button'
|
||||
disabled={sending}
|
||||
onClick={() => setSwitching(false)}
|
||||
>
|
||||
{t('cancel')}
|
||||
</button>
|
||||
<button
|
||||
type='button'
|
||||
className='button primary'
|
||||
disabled={!selection || sending}
|
||||
onClick={() => selection && switchTo(selection)}
|
||||
>
|
||||
{t('switchTo')}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{live && !picking && (
|
||||
<button
|
||||
type='button'
|
||||
className='button'
|
||||
title={t('switchHelp')}
|
||||
disabled={sending}
|
||||
onClick={() => {
|
||||
setSelection(null);
|
||||
refresh();
|
||||
setSwitching(true);
|
||||
}}
|
||||
>
|
||||
{t('switchSource')}
|
||||
</button>
|
||||
)}
|
||||
{buttons.start.visible && (
|
||||
<button
|
||||
type='button'
|
||||
className='button primary'
|
||||
disabled={!buttons.start.enabled}
|
||||
onClick={() => selection && send(() => host.start(selection))}
|
||||
>
|
||||
{t('start')}
|
||||
</button>
|
||||
)}
|
||||
{buttons.cancel.visible && (
|
||||
<button
|
||||
type='button'
|
||||
className='button'
|
||||
disabled={!buttons.cancel.enabled}
|
||||
onClick={() => host.stop()}
|
||||
>
|
||||
{t('cancel')}
|
||||
</button>
|
||||
)}
|
||||
{buttons.stop.visible && (
|
||||
<button
|
||||
type='button'
|
||||
className='button danger'
|
||||
disabled={!buttons.stop.enabled}
|
||||
onClick={() => send(() => host.stop())}
|
||||
>
|
||||
{t('stop')}
|
||||
</button>
|
||||
)}
|
||||
</footer>
|
||||
|
||||
{confirmQuit && (
|
||||
<ConfirmQuit
|
||||
viewers={state.share?.devices.length ?? 0}
|
||||
onCancel={() => setConfirmQuit(false)}
|
||||
onQuit={(dontAskAgain) => {
|
||||
void host.quit(dontAskAgain);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{settingsOpen && (
|
||||
<SettingsDialog
|
||||
host={host}
|
||||
autostart={state.capabilities.autostart}
|
||||
onClose={() => setSettingsOpen(false)}
|
||||
onSaved={(s) => {
|
||||
setTheme(s.theme);
|
||||
onLanguage(s.language);
|
||||
// The test pattern comes and goes with its setting (#91).
|
||||
if (buttons.pick) refresh();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Banners({ state }: { state: HostState }) {
|
||||
const { t } = useI18n();
|
||||
return (
|
||||
<>
|
||||
{state.error && state.phase === 'stopped' && (
|
||||
<div className='banner error' role='alert'>
|
||||
<strong>{t('startFailed')}</strong> {say(state.error, t)}
|
||||
</div>
|
||||
)}
|
||||
{state.stop && state.phase === 'stopped' && (
|
||||
<div className='banner error' role='alert'>
|
||||
<strong>{t('stoppedByDesktop')}</strong> {say(state.stop.reason, t)}
|
||||
</div>
|
||||
)}
|
||||
{state.settings_recovered && (
|
||||
<div className='banner warning'>{say(state.settings_recovered, t)}</div>
|
||||
)}
|
||||
{state.warnings.map((w) => (
|
||||
<div key={w.text} className='banner warning' role='alert'>
|
||||
{say(w, t)}
|
||||
</div>
|
||||
))}
|
||||
{state.pending_settings.length > 0 && (
|
||||
<div className='banner info'>
|
||||
<strong>{t('pendingSettings')}</strong>{' '}
|
||||
{state.pending_settings.map((n) => say(n, t)).join('; ')}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
export type Capabilities = {
|
||||
/**
|
||||
* `wayland`, `x11` or `none`.
|
||||
*/
|
||||
session: string, desktop: string, portal: boolean, virtual_display: boolean,
|
||||
/**
|
||||
* The binary can consume a PipeWire stream (`pipewire` feature).
|
||||
*/
|
||||
pipewire: boolean,
|
||||
/**
|
||||
* Autostart can be set from this application.
|
||||
*/
|
||||
autostart: boolean, };
|
||||
@@ -0,0 +1,6 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
/**
|
||||
* What closing the desktop application window does (#22).
|
||||
*/
|
||||
export type CloseAction = "tray" | "quit";
|
||||
@@ -0,0 +1,7 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
/**
|
||||
* Video codec of the shares (#67). VP9 keeps the same quality at a lower
|
||||
* bitrate, but costs 1.6x the CPU of VP8 (`docs/perf.md`).
|
||||
*/
|
||||
export type Codec = "vp8" | "vp9" | "h264";
|
||||
@@ -0,0 +1,7 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { DeviceId } from "../../../viewer/src/proto/DeviceId";
|
||||
|
||||
/**
|
||||
* The host's name for a device (#37).
|
||||
*/
|
||||
export type DeviceAlias = { id: DeviceId, name: string, };
|
||||
@@ -0,0 +1,37 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { Capabilities } from "./Capabilities";
|
||||
import type { Notice } from "./Notice";
|
||||
import type { Phase } from "./Phase";
|
||||
import type { Share } from "./Share";
|
||||
import type { Stop } from "./Stop";
|
||||
|
||||
/**
|
||||
* The whole state of the host.
|
||||
*/
|
||||
export type HostState = { phase: Phase, share: Share | null,
|
||||
/**
|
||||
* Failure of the last start, translated by the interface (#75).
|
||||
*/
|
||||
error: Notice | null, stop: Stop | null,
|
||||
/**
|
||||
* What still works but deserves to be known (interface down, address
|
||||
* changed).
|
||||
*/
|
||||
warnings: Array<Notice>,
|
||||
/**
|
||||
* Sleep inhibition mechanisms held (`login1`, `screensaver`): empty
|
||||
* outside a share, or if none could be taken.
|
||||
*/
|
||||
sleep_inhibited: Array<string>,
|
||||
/**
|
||||
* Settings changed during the share, applied to the next one.
|
||||
*/
|
||||
pending_settings: Array<Notice>,
|
||||
/**
|
||||
* The settings file was unusable at startup: what was done about it.
|
||||
*/
|
||||
settings_recovered: Notice | null,
|
||||
/**
|
||||
* Capabilities of this machine, to offer only what works.
|
||||
*/
|
||||
capabilities: Capabilities, };
|
||||
@@ -0,0 +1,6 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
/**
|
||||
* A network interface offered in the settings.
|
||||
*/
|
||||
export type InterfaceOption = { name: string, addresses: Array<string>, active: boolean, };
|
||||
@@ -0,0 +1,7 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
/**
|
||||
* What the interface shows as the name of a source, in its language (#21).
|
||||
* Only a window title or an output name comes from the system as is.
|
||||
*/
|
||||
export type Label = { "type": "title", text: string, } | { "type": "monitor", output: string, primary: boolean, } | { "type": "screen" } | { "type": "window" } | { "type": "virtual_screen" } | { "type": "test_pattern" } | { "type": "recorded_pattern" } | { "type": "all_screens" } | { "type": "entire_screen" } | { "type": "chosen_screen" } | { "type": "chosen_window" };
|
||||
@@ -0,0 +1,19 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
/**
|
||||
* The local name of the host, as the interface shows it (#25).
|
||||
*/
|
||||
export type LocalNameInfo = {
|
||||
/**
|
||||
* `rustscreen.local`, or `rustscreen-2.local` if the name was taken.
|
||||
*/
|
||||
host: string,
|
||||
/**
|
||||
* Home page by name, to type the short code: `http://rustscreen.local:8099/`.
|
||||
*/
|
||||
url: string,
|
||||
/**
|
||||
* Another machine answers over mDNS: the name most likely works. Until
|
||||
* then the interface puts the address first and says the name is a try.
|
||||
*/
|
||||
confirmed: boolean, };
|
||||
@@ -0,0 +1,16 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
export type Notice = {
|
||||
/**
|
||||
* Key under `desktop.host` in `locales/`, snake case (`port_in_use`).
|
||||
*/
|
||||
code: string,
|
||||
/**
|
||||
* Values of the placeholders: numbers, interface names, paths, and the
|
||||
* system's own words (`detail`), which no catalog can translate.
|
||||
*/
|
||||
params: { [key in string]: string },
|
||||
/**
|
||||
* The English sentence, for the command line and unknown codes.
|
||||
*/
|
||||
text: string, };
|
||||
@@ -0,0 +1,6 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
/**
|
||||
* Where the share stands.
|
||||
*/
|
||||
export type Phase = "stopped" | "starting" | "live";
|
||||
@@ -0,0 +1,17 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { RefusalCause } from "./RefusalCause";
|
||||
|
||||
/**
|
||||
* A connection the host refused, kept for the interface and the diagnostics:
|
||||
* "who tried to get in, from where, and why it failed" answers most session
|
||||
* questions without reading a log (#35).
|
||||
*/
|
||||
export type Refusal = {
|
||||
/**
|
||||
* When, in milliseconds since the Unix epoch.
|
||||
*/
|
||||
at_ms: number, address: string,
|
||||
/**
|
||||
* Device name announced by the viewer, empty if it never said.
|
||||
*/
|
||||
device: string, cause: RefusalCause, };
|
||||
@@ -0,0 +1,6 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
/**
|
||||
* Why a connection was refused, as the host interface names it (#35).
|
||||
*/
|
||||
export type RefusalCause = "bad_token" | "token_used" | "expired_token" | "kicked" | "room_full" | "not_trusted" | "no_media_port";
|
||||
@@ -0,0 +1,8 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { Notice } from "./Notice";
|
||||
|
||||
/**
|
||||
* A rejected value, named by its field: the interface places it next to the
|
||||
* faulty field, and the message reads as is.
|
||||
*/
|
||||
export type Rejection = { field: string, message: Notice, };
|
||||
@@ -0,0 +1,78 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { QualityPreset } from "../../../viewer/src/proto/QualityPreset";
|
||||
import type { CloseAction } from "./CloseAction";
|
||||
import type { Codec } from "./Codec";
|
||||
import type { DeviceAlias } from "./DeviceAlias";
|
||||
import type { Theme } from "./Theme";
|
||||
import type { TrustedDevice } from "./TrustedDevice";
|
||||
|
||||
/**
|
||||
* Everything that can be set, in a single place.
|
||||
*
|
||||
* `#[serde(default)]`: a file written by a version that did not know a field
|
||||
* still reads, the field takes its default value. Every renamed field keeps
|
||||
* its previous (French) name as an alias, so files from 0.5 and earlier read
|
||||
* without loss.
|
||||
*/
|
||||
export type Settings = { version: number,
|
||||
/**
|
||||
* Listening port of the server (viewer and signaling).
|
||||
*/
|
||||
port: number,
|
||||
/**
|
||||
* First UDP port of the media (#88): one per viewer, [`MAX_LIMIT`] in a
|
||||
* row, the range to open in a firewall. `0`: right after `port`.
|
||||
*/
|
||||
media_port: number,
|
||||
/**
|
||||
* Name of the network interface to listen on (`wlp2s0`, `enp3s0`).
|
||||
* `None`: all interfaces.
|
||||
*/
|
||||
interface: string | null, theme: Theme,
|
||||
/**
|
||||
* Language code of the interface (`fr`, `en`, `pt-BR`), among the files
|
||||
* of `locales/` (#21). `None`: the desktop's. A code, not a closed list:
|
||||
* adding a language does not change this format.
|
||||
*/
|
||||
language: string | null,
|
||||
/**
|
||||
* Simultaneous viewers.
|
||||
*/
|
||||
limit: number,
|
||||
/**
|
||||
* Quality offered when a share starts.
|
||||
*/
|
||||
quality: QualityPreset, codec: Codec,
|
||||
/**
|
||||
* Let the GPU encode when it can (#57): VP9 and H.264 through VA-API.
|
||||
* Off, libvpx encodes everything; H.264 then falls back on VP8.
|
||||
*/
|
||||
hardware_encoding: boolean,
|
||||
/**
|
||||
* Minutes during which the QR code and the short code let a new device in
|
||||
* (#19). `0`: no limit. Devices already admitted come back after the
|
||||
* deadline.
|
||||
*/
|
||||
code_validity_min: number,
|
||||
/**
|
||||
* Start the host when the user session opens (#32).
|
||||
*/
|
||||
autostart: boolean, close_action: CloseAction,
|
||||
/**
|
||||
* Ask for confirmation before quitting during a share (#43).
|
||||
*/
|
||||
confirm_quit: boolean, trusted_devices: Array<TrustedDevice>,
|
||||
/**
|
||||
* Names the host gave to devices, by device id (#37). They win over the
|
||||
* name a viewer announces, and survive a restart.
|
||||
*/
|
||||
aliases: Array<DeviceAlias>,
|
||||
/**
|
||||
* Width and height of the virtual screen the portal creates (#89).
|
||||
*/
|
||||
virtual_size: [number, number],
|
||||
/**
|
||||
* Offer the test pattern among the sources (#91): a debugging aid, off
|
||||
* by default. The command line's `--synthetic` does not depend on it.
|
||||
*/
|
||||
test_pattern: boolean, };
|
||||
@@ -0,0 +1,16 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { Notice } from "./Notice";
|
||||
|
||||
/**
|
||||
* What a settings change produces.
|
||||
*/
|
||||
export type SettingsOutcome = {
|
||||
/**
|
||||
* Fields applied right away.
|
||||
*/
|
||||
immediate: Array<string>,
|
||||
/**
|
||||
* Fields waiting for the next share, with the reason; `field` in the
|
||||
* parameters names the field.
|
||||
*/
|
||||
next_share: Array<Notice>, };
|
||||
@@ -0,0 +1,54 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { LocalNameInfo } from "./LocalNameInfo";
|
||||
import type { Refusal } from "./Refusal";
|
||||
import type { SharedSource } from "./SharedSource";
|
||||
import type { ViewerDevice } from "./ViewerDevice";
|
||||
|
||||
/**
|
||||
* A share in progress.
|
||||
*/
|
||||
export type Share = { source: SharedSource, room: string,
|
||||
/**
|
||||
* The URL to hand out, token included, on the LAN address.
|
||||
*/
|
||||
url: string,
|
||||
/**
|
||||
* The QR code of `url`, as SVG.
|
||||
*/
|
||||
qr_svg: string,
|
||||
/**
|
||||
* Short code to type without a camera, lowercase: the interface groups it.
|
||||
*/
|
||||
code: string,
|
||||
/**
|
||||
* Expiry of the token and the code, in Unix milliseconds. `None`: no
|
||||
* limit.
|
||||
*/
|
||||
expires_ms: number | null,
|
||||
/**
|
||||
* The expiry has passed: no new device gets in until the host draws a
|
||||
* new code.
|
||||
*/
|
||||
access_expired: boolean,
|
||||
/**
|
||||
* SHA-256 fingerprint of the certificate, over HTTPS only.
|
||||
*/
|
||||
fingerprint: string | null,
|
||||
/**
|
||||
* Actual listen address and port (`0.0.0.0:8099`, `192.168.1.20:9000`).
|
||||
*/
|
||||
listen: string,
|
||||
/**
|
||||
* Chosen interface, `None` if the host listens everywhere.
|
||||
*/
|
||||
interface: string | null, devices: Array<ViewerDevice>,
|
||||
/**
|
||||
* Connections refused since the share started, newest first (#35): who
|
||||
* tried, from where, and why it did not work.
|
||||
*/
|
||||
refusals: Array<Refusal>,
|
||||
/**
|
||||
* `rustscreen.local`, when announced (#25). The QR code keeps the
|
||||
* address: the name is for whoever types.
|
||||
*/
|
||||
local_name: LocalNameInfo | null, limit: number, started_ms: number, };
|
||||
@@ -0,0 +1,16 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { SourceKind } from "../../../viewer/src/proto/SourceKind";
|
||||
import type { Label } from "./Label";
|
||||
|
||||
/**
|
||||
* The source being shared.
|
||||
*/
|
||||
export type SharedSource = { kind: SourceKind, name: string, label: Label,
|
||||
/**
|
||||
* `portal`, `x11`, `synthetic` or `ivf`.
|
||||
*/
|
||||
backend: string,
|
||||
/**
|
||||
* Current encoded size: it follows a resolution change.
|
||||
*/
|
||||
width: number, height: number, };
|
||||
@@ -0,0 +1,15 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
/**
|
||||
* What the user chooses to share. The interface sends back the `choice` of a
|
||||
* [`SourceOption`] as is.
|
||||
*/
|
||||
export type SourceChoice = { "type": "synthetic", width: number, height: number, } | { "type": "x11", id: string, } | { "type": "windows", id: string, } | { "type": "portal", virtual_display: boolean,
|
||||
/**
|
||||
* A window rather than a screen (#17), if the portal allows it.
|
||||
*/
|
||||
window: boolean,
|
||||
/**
|
||||
* Size of a virtual screen. Ignored for an existing screen.
|
||||
*/
|
||||
size: [number, number] | null, } | { "type": "playback", path: string, };
|
||||
@@ -0,0 +1,7 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
/**
|
||||
* What to know about a source before choosing it, translated by the
|
||||
* interface.
|
||||
*/
|
||||
export type SourceNote = "portal_screen" | "portal_window" | "portal_no_window" | "virtual_screen" | "test_pattern" | "no_pipewire" | "minimized";
|
||||
@@ -0,0 +1,35 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { SourceKind } from "../../../viewer/src/proto/SourceKind";
|
||||
import type { Label } from "./Label";
|
||||
import type { SourceChoice } from "./SourceChoice";
|
||||
import type { SourceNote } from "./SourceNote";
|
||||
|
||||
/**
|
||||
* A source offered in the list.
|
||||
*/
|
||||
export type SourceOption = { choice: SourceChoice, kind: SourceKind,
|
||||
/**
|
||||
* English name, for the command line. A window title may be in it: it
|
||||
* stays in the local interface, never in the log (ADR 0008).
|
||||
*/
|
||||
name: string,
|
||||
/**
|
||||
* The name to display, which the interface translates.
|
||||
*/
|
||||
label: Label, width: number, height: number,
|
||||
/**
|
||||
* Thumbnail as a `data:image/png` URL, when the platform allows taking
|
||||
* one without consent (X11). Never under Wayland: the portal shows
|
||||
* nothing before the user agrees.
|
||||
*/
|
||||
thumbnail: string | null,
|
||||
/**
|
||||
* What to know before choosing ("the desktop will ask which one").
|
||||
*/
|
||||
note: SourceNote | null,
|
||||
/**
|
||||
* False for a source that is listed but not shareable right now
|
||||
* (minimized window, desktop that cannot share a window): the note says
|
||||
* why, before starting and not after (#17).
|
||||
*/
|
||||
available: boolean, };
|
||||
@@ -0,0 +1,12 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { Notice } from "./Notice";
|
||||
|
||||
/**
|
||||
* Why the last share stopped, when it was not the user.
|
||||
*/
|
||||
export type Stop = { reason: Notice,
|
||||
/**
|
||||
* Stopped from the desktop ("stop sharing" button, screen unplugged):
|
||||
* the command line then exits with code 3.
|
||||
*/
|
||||
by_desktop: boolean, };
|
||||
@@ -0,0 +1,6 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
/**
|
||||
* Theme of the host interface.
|
||||
*/
|
||||
export type Theme = "system" | "light" | "dark";
|
||||
@@ -0,0 +1,19 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { DeviceId } from "../../../viewer/src/proto/DeviceId";
|
||||
|
||||
/**
|
||||
* A device allowed to come back without scanning again (#34).
|
||||
*
|
||||
* The host keeps the public key only: the device proves it holds the private
|
||||
* one by signing a challenge, and the private key never leaves it.
|
||||
*/
|
||||
export type TrustedDevice = { id: DeviceId, name: string,
|
||||
/**
|
||||
* Ed25519 public key, 64 lowercase hex digits. Empty in a file written
|
||||
* before #34: such an entry lets nobody in.
|
||||
*/
|
||||
key: string,
|
||||
/**
|
||||
* When the host started trusting it, in milliseconds since the Unix epoch.
|
||||
*/
|
||||
added_ms: number, };
|
||||
@@ -0,0 +1,38 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
/**
|
||||
* A connected viewer.
|
||||
*/
|
||||
export type ViewerDevice = {
|
||||
/**
|
||||
* Number to send back to disconnect it.
|
||||
*/
|
||||
connection: number,
|
||||
/**
|
||||
* The name to show: the host's alias if it gave one (#37), otherwise the
|
||||
* name the viewer announces (#36). Plain text, markup included.
|
||||
*/
|
||||
name: string,
|
||||
/**
|
||||
* The name the viewer announces, to show next to an alias and to go
|
||||
* back to.
|
||||
*/
|
||||
announced: string, aliased: boolean, platform: string | null, address: string,
|
||||
/**
|
||||
* MAC address from the neighbour table, `None` when unknown: behind a
|
||||
* router, over IPv6, or the host itself (#38). Never logged.
|
||||
*/
|
||||
mac: string | null,
|
||||
/**
|
||||
* Arrival, in Unix milliseconds.
|
||||
*/
|
||||
since_ms: number,
|
||||
/**
|
||||
* The host trusts its key: it comes back without a link (#34).
|
||||
*/
|
||||
trusted: boolean,
|
||||
/**
|
||||
* It announced a key the host could trust. A browser without storage, or
|
||||
* too old to sign, has none.
|
||||
*/
|
||||
can_trust: boolean, };
|
||||
@@ -0,0 +1,52 @@
|
||||
import { useId, useState } from 'react';
|
||||
|
||||
import { useI18n } from '../i18n';
|
||||
|
||||
type Props = {
|
||||
viewers: number;
|
||||
onCancel: () => void;
|
||||
onQuit: (dontAskAgain: boolean) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Quitting during a share (#43): say so before cutting the viewers off.
|
||||
* "Don't ask again" can be turned back on in the settings.
|
||||
*/
|
||||
export function ConfirmQuit({ viewers, onCancel, onQuit }: Props) {
|
||||
const { t } = useI18n();
|
||||
const [dontAskAgain, setDontAskAgain] = useState(false);
|
||||
const id = useId();
|
||||
return (
|
||||
<div className='overlay'>
|
||||
<div
|
||||
className='dialog'
|
||||
role='alertdialog'
|
||||
aria-modal='true'
|
||||
aria-labelledby={`${id}-title`}
|
||||
aria-describedby={`${id}-text`}
|
||||
onKeyDown={(e) => e.key === 'Escape' && onCancel()}
|
||||
>
|
||||
<h2 id={`${id}-title`}>{t('quitTitle')}</h2>
|
||||
<p id={`${id}-text`}>{t('quitText', { count: viewers })}</p>
|
||||
<label className='checkbox'>
|
||||
<input
|
||||
type='checkbox'
|
||||
checked={dontAskAgain}
|
||||
onChange={(e) => setDontAskAgain(e.target.checked)}
|
||||
/>
|
||||
{t('dontAskAgain')}
|
||||
</label>
|
||||
<div className='dialog-actions'>
|
||||
<span className='spacer' />
|
||||
{/* biome-ignore lint/a11y/noAutofocus: the safe choice gets the focus, Enter stops nothing */}
|
||||
<button type='button' className='button' onClick={onCancel} autoFocus>
|
||||
{t('cancel')}
|
||||
</button>
|
||||
<button type='button' className='button danger' onClick={() => onQuit(dontAskAgain)}>
|
||||
{t('quitConfirm')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,397 @@
|
||||
import { useEffect, useId, useState } from 'react';
|
||||
import type { QualityPreset } from '../../../viewer/src/proto/QualityPreset';
|
||||
import type { CloseAction } from '../bindings/CloseAction';
|
||||
import type { Codec } from '../bindings/Codec';
|
||||
import type { InterfaceOption } from '../bindings/InterfaceOption';
|
||||
import type { Rejection } from '../bindings/Rejection';
|
||||
import type { Settings } from '../bindings/Settings';
|
||||
import type { SettingsOutcome } from '../bindings/SettingsOutcome';
|
||||
import type { Theme } from '../bindings/Theme';
|
||||
import { LANGUAGES, useI18n } from '../i18n';
|
||||
import { type Host, rejectionsOf } from '../lib/host';
|
||||
import { noticeOf, outcomeSummary, say } from '../lib/view';
|
||||
|
||||
const QUALITIES: QualityPreset[] = ['saver', 'balanced', 'sharp'];
|
||||
const CODECS: Codec[] = ['vp8', 'vp9', 'h264'];
|
||||
const THEMES: Theme[] = ['system', 'light', 'dark'];
|
||||
const CLOSE_ACTIONS: CloseAction[] = ['tray', 'quit'];
|
||||
|
||||
type Props = {
|
||||
host: Host;
|
||||
autostart: boolean;
|
||||
onClose: () => void;
|
||||
onSaved: (settings: Settings) => void;
|
||||
};
|
||||
|
||||
export function SettingsDialog({ host, autostart, onClose, onSaved }: Props) {
|
||||
const { t } = useI18n();
|
||||
const [settings, setSettings] = useState<Settings | null>(null);
|
||||
const [interfaces, setInterfaces] = useState<InterfaceOption[]>([]);
|
||||
const [rejections, setRejections] = useState<Rejection[]>([]);
|
||||
// What is kept is the fact, not its sentence: changing the language while
|
||||
// saving also retranslates the confirmation.
|
||||
const [message, setMessage] = useState<
|
||||
{ type: 'outcome'; outcome: SettingsOutcome } | { type: 'diagnostics'; path: string } | null
|
||||
>(null);
|
||||
const [sending, setSending] = useState(false);
|
||||
const id = useId();
|
||||
|
||||
useEffect(() => {
|
||||
host.settings().then(setSettings);
|
||||
host.interfaces().then(setInterfaces);
|
||||
}, [host]);
|
||||
|
||||
if (!settings) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const change = <K extends keyof Settings>(field: K, value: Settings[K]) => {
|
||||
setSettings({ ...settings, [field]: value });
|
||||
setRejections((r) => r.filter((x) => x.field !== field));
|
||||
setMessage(null);
|
||||
};
|
||||
const error = (field: string) => {
|
||||
const found = rejections.find((r) => r.field === field);
|
||||
return found ? say(found.message, t) : undefined;
|
||||
};
|
||||
|
||||
const save = async () => {
|
||||
setSending(true);
|
||||
try {
|
||||
const outcome = await host.updateSettings(settings);
|
||||
setRejections([]);
|
||||
setMessage({ type: 'outcome', outcome });
|
||||
onSaved(settings);
|
||||
} catch (e) {
|
||||
setRejections(rejectionsOf(e));
|
||||
setMessage(null);
|
||||
} finally {
|
||||
setSending(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Revoking acts at once, without waiting for "Save": a device must lose
|
||||
// its access within the second (#34).
|
||||
const revoke = async (key: string) => {
|
||||
try {
|
||||
await host.revokeDevice(key);
|
||||
setSettings({
|
||||
...settings,
|
||||
trusted_devices: settings.trusted_devices.filter((d) => d.key !== key),
|
||||
});
|
||||
setRejections((r) => r.filter((x) => x.field !== 'trusted_devices'));
|
||||
} catch (e) {
|
||||
setRejections([{ field: 'trusted_devices', message: noticeOf(e) }]);
|
||||
}
|
||||
};
|
||||
|
||||
const exportDiagnostics = async () => {
|
||||
try {
|
||||
setMessage({ type: 'diagnostics', path: await host.exportDiagnostics() });
|
||||
} catch (e) {
|
||||
setRejections([{ field: 'diagnostics', message: noticeOf(e) }]);
|
||||
}
|
||||
};
|
||||
|
||||
// A chosen interface missing from the list (unplugged) stays displayed, so
|
||||
// that the saved setting does not vanish silently.
|
||||
const missing =
|
||||
settings.interface !== null && !interfaces.some((i) => i.name === settings.interface);
|
||||
|
||||
return (
|
||||
<div className='overlay'>
|
||||
<div
|
||||
className='dialog'
|
||||
role='dialog'
|
||||
aria-modal='true'
|
||||
aria-labelledby={`${id}-title`}
|
||||
onKeyDown={(e) => e.key === 'Escape' && onClose()}
|
||||
>
|
||||
<h2 id={`${id}-title`}>{t('settings')}</h2>
|
||||
<form
|
||||
className='form'
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
save();
|
||||
}}
|
||||
>
|
||||
<Field
|
||||
id={`${id}-port`}
|
||||
label={t('portField')}
|
||||
help={t('portHelp')}
|
||||
error={error('port')}
|
||||
>
|
||||
<input
|
||||
id={`${id}-port`}
|
||||
type='number'
|
||||
min={1024}
|
||||
max={65535}
|
||||
value={settings.port}
|
||||
onChange={(e) => change('port', Number(e.target.value))}
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
id={`${id}-media-port`}
|
||||
label={t('mediaPortField')}
|
||||
help={t('mediaPortHelp', firewall(settings))}
|
||||
error={error('media_port')}
|
||||
>
|
||||
<input
|
||||
id={`${id}-media-port`}
|
||||
type='number'
|
||||
min={0}
|
||||
max={65516}
|
||||
placeholder={String(settings.port + 1)}
|
||||
value={settings.media_port || ''}
|
||||
onChange={(e) => change('media_port', Number(e.target.value) || 0)}
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
id={`${id}-interface`}
|
||||
label={t('interface')}
|
||||
help={t('interfaceHelp')}
|
||||
error={error('interface')}
|
||||
>
|
||||
<select
|
||||
id={`${id}-interface`}
|
||||
value={settings.interface ?? ''}
|
||||
onChange={(e) => change('interface', e.target.value === '' ? null : e.target.value)}
|
||||
>
|
||||
<option value=''>{t('allInterfaces')}</option>
|
||||
{interfaces.map((i) => (
|
||||
<option key={i.name} value={i.name}>
|
||||
{i.name} ({i.addresses.join(', ')}){i.active ? '' : `, ${t('interfaceInactive')}`}
|
||||
</option>
|
||||
))}
|
||||
{missing && settings.interface && (
|
||||
<option value={settings.interface}>
|
||||
{settings.interface}, {t('interfaceInactive')}
|
||||
</option>
|
||||
)}
|
||||
</select>
|
||||
</Field>
|
||||
<Field id={`${id}-limit`} label={t('limit')} error={error('limit')}>
|
||||
<input
|
||||
id={`${id}-limit`}
|
||||
type='number'
|
||||
min={1}
|
||||
max={20}
|
||||
value={settings.limit}
|
||||
onChange={(e) => change('limit', Number(e.target.value))}
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
id={`${id}-validity`}
|
||||
label={t('codeValidity')}
|
||||
help={t('codeValidityHelp')}
|
||||
error={error('code_validity_min')}
|
||||
>
|
||||
<input
|
||||
id={`${id}-validity`}
|
||||
type='number'
|
||||
min={0}
|
||||
max={1440}
|
||||
value={settings.code_validity_min}
|
||||
onChange={(e) => change('code_validity_min', Number(e.target.value))}
|
||||
/>
|
||||
</Field>
|
||||
<Field id={`${id}-quality`} label={t('quality')} error={error('quality')}>
|
||||
<select
|
||||
id={`${id}-quality`}
|
||||
value={settings.quality}
|
||||
onChange={(e) => change('quality', e.target.value as QualityPreset)}
|
||||
>
|
||||
{QUALITIES.map((q) => (
|
||||
<option key={q} value={q}>
|
||||
{t(`qualities.${q}`)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field id={`${id}-codec`} label={t('codec')} help={t('codecHelp')} error={error('codec')}>
|
||||
<select
|
||||
id={`${id}-codec`}
|
||||
value={settings.codec}
|
||||
onChange={(e) => change('codec', e.target.value as Codec)}
|
||||
>
|
||||
{CODECS.map((c) => (
|
||||
<option key={c} value={c}>
|
||||
{t(`codecs.${c}`)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<label className='checkbox' title={t('hardwareEncodingHelp')}>
|
||||
<input
|
||||
type='checkbox'
|
||||
checked={settings.hardware_encoding}
|
||||
onChange={(e) => change('hardware_encoding', e.target.checked)}
|
||||
/>
|
||||
{t('hardwareEncoding')}
|
||||
</label>
|
||||
<Field id={`${id}-theme`} label={t('theme')}>
|
||||
<select
|
||||
id={`${id}-theme`}
|
||||
value={settings.theme}
|
||||
onChange={(e) => change('theme', e.target.value as Theme)}
|
||||
>
|
||||
{THEMES.map((theme) => (
|
||||
<option key={theme} value={theme}>
|
||||
{t(`themes.${theme}`)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field id={`${id}-language`} label={t('language')}>
|
||||
<select
|
||||
id={`${id}-language`}
|
||||
value={settings.language ?? ''}
|
||||
onChange={(e) => change('language', e.target.value === '' ? null : e.target.value)}
|
||||
>
|
||||
<option value=''>{t('languageSystem')}</option>
|
||||
{LANGUAGES.map((l) => (
|
||||
<option key={l.code} value={l.code} lang={l.code}>
|
||||
{l.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field id={`${id}-close-action`} label={t('closeAction')} help={t('closeActionHelp')}>
|
||||
<select
|
||||
id={`${id}-close-action`}
|
||||
value={settings.close_action}
|
||||
onChange={(e) => change('close_action', e.target.value as CloseAction)}
|
||||
>
|
||||
{CLOSE_ACTIONS.map((a) => (
|
||||
<option key={a} value={a}>
|
||||
{t(`closeActions.${a}`)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<label className='checkbox'>
|
||||
<input
|
||||
type='checkbox'
|
||||
checked={settings.confirm_quit}
|
||||
onChange={(e) => change('confirm_quit', e.target.checked)}
|
||||
/>
|
||||
{t('confirmQuit')}
|
||||
</label>
|
||||
{autostart && (
|
||||
<label className='checkbox'>
|
||||
<input
|
||||
type='checkbox'
|
||||
checked={settings.autostart}
|
||||
onChange={(e) => change('autostart', e.target.checked)}
|
||||
/>
|
||||
{t('autostart')}
|
||||
{error('autostart') && <span className='field-error'>{error('autostart')}</span>}
|
||||
</label>
|
||||
)}
|
||||
<div className='field'>
|
||||
<span>{t('trustedDevices')}</span>
|
||||
{settings.trusted_devices.filter((d) => d.key).length === 0 ? (
|
||||
<span className='help'>{t('trustedNone')}</span>
|
||||
) : (
|
||||
<ul className='devices'>
|
||||
{settings.trusted_devices
|
||||
.filter((d) => d.key)
|
||||
.map((device) => (
|
||||
<li key={device.key}>
|
||||
<span className='device-name'>{device.name}</span>
|
||||
<span className='muted'>{device.key.slice(0, 16)}</span>
|
||||
<button
|
||||
type='button'
|
||||
className='button muted danger'
|
||||
title={t('revokeHelp')}
|
||||
onClick={() => revoke(device.key)}
|
||||
>
|
||||
{t('revoke')}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{error('trusted_devices') && (
|
||||
<span className='field-error'>{error('trusted_devices')}</span>
|
||||
)}
|
||||
</div>
|
||||
<fieldset className='debug'>
|
||||
<legend>{t('debug')}</legend>
|
||||
<label className='checkbox' title={t('testPatternHelp')}>
|
||||
<input
|
||||
type='checkbox'
|
||||
checked={settings.test_pattern}
|
||||
onChange={(e) => change('test_pattern', e.target.checked)}
|
||||
/>
|
||||
{t('testPattern')}
|
||||
</label>
|
||||
<div className='field'>
|
||||
<button type='button' className='button muted' onClick={exportDiagnostics}>
|
||||
{t('diagnostics')}
|
||||
</button>
|
||||
<span className='help'>{t('diagnosticsHelp')}</span>
|
||||
{error('diagnostics') && <span className='field-error'>{error('diagnostics')}</span>}
|
||||
</div>
|
||||
</fieldset>
|
||||
{error('file') && <p className='field-error'>{error('file')}</p>}
|
||||
{message && (
|
||||
<p className='confirmation' role='status'>
|
||||
{message.type === 'outcome'
|
||||
? outcomeSummary(message.outcome, t)
|
||||
: t('diagnosticsWritten', { path: message.path })}
|
||||
</p>
|
||||
)}
|
||||
<div className='dialog-actions'>
|
||||
<button type='button' className='button muted' onClick={onClose}>
|
||||
{t('close')}
|
||||
</button>
|
||||
<button type='submit' className='button primary' disabled={sending}>
|
||||
{t('save')}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The firewall rule for these settings (#88): the HTTP port, and the UDP range
|
||||
* of the media, one port per viewer. Mirrors `Settings::media_ports`.
|
||||
*/
|
||||
function firewall(settings: Settings): { port: number; first: number; last: number } {
|
||||
const first = settings.media_port || settings.port + 1;
|
||||
return { port: settings.port, first, last: first + MEDIA_PORTS - 1 };
|
||||
}
|
||||
|
||||
/** `rs_store::MAX_LIMIT`: one media port per possible viewer. */
|
||||
const MEDIA_PORTS = 20;
|
||||
|
||||
function Field({
|
||||
id,
|
||||
label,
|
||||
help,
|
||||
error,
|
||||
children,
|
||||
}: {
|
||||
id: string;
|
||||
label: string;
|
||||
help?: string;
|
||||
error?: string | undefined;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className={`field${error ? ' has-error' : ''}`}>
|
||||
<label htmlFor={id}>{label}</label>
|
||||
{children}
|
||||
{error ? (
|
||||
<span className='field-error' role='alert'>
|
||||
{error}
|
||||
</span>
|
||||
) : (
|
||||
help && <span className='help'>{help}</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import type { Share } from '../bindings/Share';
|
||||
import type { ViewerDevice } from '../bindings/ViewerDevice';
|
||||
import { useI18n } from '../i18n';
|
||||
import { displayCode, displayName, duration, expiry } from '../lib/view';
|
||||
|
||||
type Props = {
|
||||
share: Share;
|
||||
onDisconnect: (connection: number) => void;
|
||||
onNewCode: () => void;
|
||||
onTrust: (connection: number) => void;
|
||||
onRename: (connection: number, alias: string | null) => void;
|
||||
};
|
||||
|
||||
export function SharePanel({ share, onDisconnect, onNewCode, onTrust, onRename }: Props) {
|
||||
const { t } = useI18n();
|
||||
const now = useNow();
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
const copy = async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(share.url);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 1500);
|
||||
} catch {
|
||||
setCopied(false);
|
||||
}
|
||||
};
|
||||
|
||||
const [address] = share.listen.split(':');
|
||||
const byAddress = share.url.split('/r/')[0] ?? share.url;
|
||||
// The name is offered first only once another machine answered over mDNS
|
||||
// (#25): otherwise the address, which always works, comes first.
|
||||
const named = share.local_name;
|
||||
const home = named?.confirmed ? named.url.replace(/\/$/, '') : byAddress;
|
||||
const remaining = expiry(share.expires_ms, now, t);
|
||||
return (
|
||||
<section className='share'>
|
||||
<div className='card qr-card'>
|
||||
<h2>{t('scan')}</h2>
|
||||
{/* SVG produced by the host (rs-signaling::qr), never by an outside input. */}
|
||||
<div
|
||||
className='qr'
|
||||
role='img'
|
||||
aria-label={share.url}
|
||||
// biome-ignore lint/security/noDangerouslySetInnerHtml: SVG generated by the local host
|
||||
dangerouslySetInnerHTML={{ __html: share.qr_svg }}
|
||||
/>
|
||||
<label className='link'>
|
||||
<span>{t('link')}</span>
|
||||
<span className='link-row'>
|
||||
<input readOnly value={share.url} onFocus={(e) => e.target.select()} />
|
||||
<button type='button' className='button' onClick={copy}>
|
||||
{copied ? t('copied') : t('copy')}
|
||||
</button>
|
||||
</span>
|
||||
</label>
|
||||
<div className={`short-code ${share.access_expired ? 'code-expired' : ''}`}>
|
||||
<span className='muted'>
|
||||
{t('code')} {t('codeHelp', { home })}
|
||||
</span>
|
||||
{named && (
|
||||
<span className='muted local-name'>
|
||||
{named.confirmed
|
||||
? t('localNameAddress', { address: byAddress })
|
||||
: t('localNameUnconfirmed', { url: named.url.replace(/\/$/, '') })}
|
||||
</span>
|
||||
)}
|
||||
<strong className='code-value' aria-live='polite'>
|
||||
{displayCode(share.code)}
|
||||
</strong>
|
||||
{remaining && (
|
||||
<span className={share.access_expired ? 'warning-text' : 'muted'}>{remaining}</span>
|
||||
)}
|
||||
<button
|
||||
type='button'
|
||||
className='button muted code-new'
|
||||
title={t('newCodeHelp')}
|
||||
onClick={onNewCode}
|
||||
>
|
||||
{t('newCode')}
|
||||
</button>
|
||||
</div>
|
||||
{share.fingerprint && (
|
||||
<p className='fingerprint'>
|
||||
{t('fingerprint')}: <code>{share.fingerprint}</code>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className='card'>
|
||||
<dl className='facts'>
|
||||
<dt>{t('source')}</dt>
|
||||
<dd>
|
||||
{displayName(share.source.label, t)}
|
||||
<span className='muted'>
|
||||
{' '}
|
||||
{share.source.width} × {share.source.height}
|
||||
</span>
|
||||
</dd>
|
||||
<dt>{t('listen')}</dt>
|
||||
<dd>
|
||||
{share.interface ? `${share.interface} (${address})` : t('allInterfaces')}
|
||||
<span className='muted'>
|
||||
{' '}
|
||||
{t('port', { port: share.listen.split(':').pop() ?? '' })}
|
||||
</span>
|
||||
</dd>
|
||||
<dt>{t('since')}</dt>
|
||||
<dd>{duration(share.started_ms, now)}</dd>
|
||||
</dl>
|
||||
|
||||
<h2 className='viewers-title'>
|
||||
{t('viewers')}
|
||||
<span className='counter'>
|
||||
{t('seats', { n: share.devices.length, limit: share.limit })}
|
||||
</span>
|
||||
</h2>
|
||||
{share.devices.length === 0 ? (
|
||||
<p className='help'>{t('nobody')}</p>
|
||||
) : (
|
||||
<ul className='devices'>
|
||||
{share.devices.map((device) => (
|
||||
<li key={device.connection}>
|
||||
<DeviceLabel device={device} onRename={onRename} />
|
||||
<span className='muted'>
|
||||
{[device.platform, device.address].filter(Boolean).join(' · ')}
|
||||
{' · '}
|
||||
<span title={t('macHelp')}>
|
||||
{device.mac ? t('mac', { mac: device.mac }) : t('macUnknown')}
|
||||
</span>
|
||||
{' · '}
|
||||
{duration(device.since_ms, now)}
|
||||
</span>
|
||||
<span className='device-actions'>
|
||||
{device.can_trust && (
|
||||
<button
|
||||
type='button'
|
||||
className='button muted'
|
||||
title={t('trustHelp')}
|
||||
onClick={() => onTrust(device.connection)}
|
||||
>
|
||||
{t('trust')}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type='button'
|
||||
className='button muted danger'
|
||||
title={t('disconnectHelp')}
|
||||
onClick={() => onDisconnect(device.connection)}
|
||||
>
|
||||
{t('disconnect')}
|
||||
</button>
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{share.refusals.length > 0 && (
|
||||
<div className='card'>
|
||||
<h2 className='viewers-title'>
|
||||
{t('refused')}
|
||||
<span className='counter'>{share.refusals.length}</span>
|
||||
</h2>
|
||||
<ul className='devices'>
|
||||
{share.refusals.slice(0, 5).map((refusal) => (
|
||||
<li key={`${refusal.at_ms}-${refusal.address}-${refusal.cause}`}>
|
||||
<span className='device-name'>{refusal.device || t('unknownDevice')}</span>
|
||||
<span className='muted'>
|
||||
{t(`refusal.${refusal.cause}`)} · {refusal.address} ·{' '}
|
||||
{duration(refusal.at_ms, now)}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The device name, renamed in place by the host (#37). React renders it as
|
||||
* text: a name with markup shows as typed. An alias shows the announced name
|
||||
* next to it, with the way back to it.
|
||||
*/
|
||||
function DeviceLabel({
|
||||
device,
|
||||
onRename,
|
||||
}: {
|
||||
device: ViewerDevice;
|
||||
onRename: (connection: number, alias: string | null) => void;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const [draft, setDraft] = useState<string | null>(null);
|
||||
if (draft !== null) {
|
||||
const commit = () => {
|
||||
const alias = draft.trim();
|
||||
setDraft(null);
|
||||
if (alias !== device.name) onRename(device.connection, alias || null);
|
||||
};
|
||||
return (
|
||||
<span className='device-name'>
|
||||
<input
|
||||
// biome-ignore lint/a11y/noAutofocus: the field opens on the user's click.
|
||||
autoFocus
|
||||
aria-label={t('rename')}
|
||||
value={draft}
|
||||
maxLength={40}
|
||||
onChange={(e) => setDraft(e.target.value)}
|
||||
onBlur={commit}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') e.currentTarget.blur();
|
||||
if (e.key === 'Escape') setDraft(null);
|
||||
}}
|
||||
/>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span className='device-name'>
|
||||
<button
|
||||
type='button'
|
||||
className='link-button'
|
||||
title={t('renameHelp')}
|
||||
onClick={() => setDraft(device.name)}
|
||||
>
|
||||
{device.name}
|
||||
</button>
|
||||
{device.trusted && <span className='trusted-mark'>{t('trusted')}</span>}
|
||||
{device.aliased && (
|
||||
<button
|
||||
type='button'
|
||||
className='link-button muted alias-reset'
|
||||
title={t('aliasResetHelp')}
|
||||
onClick={() => onRename(device.connection, null)}
|
||||
>
|
||||
{t('aliasReset', { name: device.announced })}
|
||||
</button>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** The current time, refreshed every second for the displayed durations. */
|
||||
function useNow(): number {
|
||||
const [now, setNow] = useState(() => Date.now());
|
||||
useEffect(() => {
|
||||
const timer = setInterval(() => setNow(Date.now()), 1000);
|
||||
return () => clearInterval(timer);
|
||||
}, []);
|
||||
return now;
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
import { useId, useMemo, useState } from 'react';
|
||||
import type { SourceChoice } from '../bindings/SourceChoice';
|
||||
import type { SourceOption } from '../bindings/SourceOption';
|
||||
import { useI18n } from '../i18n';
|
||||
import { displayName, filter, isVirtual, isVirtualSize, key, VIRTUAL_SIZES } from '../lib/view';
|
||||
|
||||
type Props = {
|
||||
sources: SourceOption[] | null;
|
||||
selection: SourceChoice | null;
|
||||
enabled: boolean;
|
||||
onPick: (choice: SourceChoice) => void;
|
||||
onRefresh: () => void;
|
||||
/** Saves a new size for the virtual screen (#89); rejects with its message. */
|
||||
onVirtualSize: (size: [number, number]) => Promise<void>;
|
||||
};
|
||||
|
||||
/** Beyond this, the list gets long to scan: the search field appears. */
|
||||
const SEARCH_THRESHOLD = 6;
|
||||
|
||||
export function SourcePicker({
|
||||
sources,
|
||||
selection,
|
||||
enabled,
|
||||
onPick,
|
||||
onRefresh,
|
||||
onVirtualSize,
|
||||
}: Props) {
|
||||
const { t } = useI18n();
|
||||
const [search, setSearch] = useState('');
|
||||
const visible = useMemo(() => filter(sources ?? [], search, t), [sources, search, t]);
|
||||
const picked = selection ? key(selection) : null;
|
||||
|
||||
return (
|
||||
<section className='picker' aria-labelledby='picker-title'>
|
||||
<div className='picker-header'>
|
||||
<h2 id='picker-title'>{t('pickTitle')}</h2>
|
||||
{sources && sources.length > SEARCH_THRESHOLD && (
|
||||
<input
|
||||
type='search'
|
||||
className='search'
|
||||
placeholder={t('search')}
|
||||
aria-label={t('search')}
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
/>
|
||||
)}
|
||||
<button type='button' className='button muted' onClick={onRefresh} disabled={!enabled}>
|
||||
{t('refresh')}
|
||||
</button>
|
||||
</div>
|
||||
{sources === null && <p className='help'>{t('loadingSources')}</p>}
|
||||
{sources !== null && visible.length === 0 && <p className='help'>{t('noSource')}</p>}
|
||||
<ul className='sources'>
|
||||
{visible.map((source) => {
|
||||
const id = key(source.choice);
|
||||
const name = displayName(source.label, t);
|
||||
const selected = id === picked;
|
||||
return (
|
||||
<li key={id}>
|
||||
<button
|
||||
type='button'
|
||||
className={`source${selected ? ' selected' : ''}${source.available ? '' : ' unavailable'}`}
|
||||
aria-pressed={selected}
|
||||
disabled={!enabled || !source.available}
|
||||
onClick={() => onPick(source.choice)}
|
||||
>
|
||||
<span className='thumbnail'>
|
||||
{source.thumbnail ? (
|
||||
<img src={source.thumbnail} alt='' />
|
||||
) : (
|
||||
<span className='thumbnail-empty' aria-hidden='true'>
|
||||
{source.kind === 'window' ? '▭' : '▣'}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<span className='source-name' title={name}>
|
||||
{name}
|
||||
</span>
|
||||
{source.width > 0 && (
|
||||
<span className='source-size'>
|
||||
{source.width} × {source.height}
|
||||
</span>
|
||||
)}
|
||||
{source.note && <span className='source-note'>{t(`notes.${source.note}`)}</span>}
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
{selection?.type === 'portal' && isVirtual(selection) && selection.size && (
|
||||
<VirtualSize size={selection.size} enabled={enabled} onChange={onVirtualSize} />
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
const CUSTOM = 'custom';
|
||||
const SEPARATOR = 'x';
|
||||
|
||||
/** The value of a size in the select, not a displayed text. */
|
||||
function sizeValue([width, height]: [number, number]): string {
|
||||
return [width, height].join(SEPARATOR);
|
||||
}
|
||||
|
||||
/** The size of the virtual screen: a common one, or any even size (#89). */
|
||||
function VirtualSize({
|
||||
size,
|
||||
enabled,
|
||||
onChange,
|
||||
}: {
|
||||
size: [number, number];
|
||||
enabled: boolean;
|
||||
onChange: (size: [number, number]) => Promise<void>;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const id = useId();
|
||||
const preset = VIRTUAL_SIZES.find(([w, h]) => w === size[0] && h === size[1]);
|
||||
const [custom, setCustom] = useState(!preset);
|
||||
const [width, setWidth] = useState(String(size[0]));
|
||||
const [height, setHeight] = useState(String(size[1]));
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const apply = async (next: [number, number]) => {
|
||||
if (!isVirtualSize(next)) {
|
||||
setError(t('virtualSizeInvalid'));
|
||||
return;
|
||||
}
|
||||
setError(null);
|
||||
try {
|
||||
await onChange(next);
|
||||
} catch (e) {
|
||||
setError(String(e));
|
||||
}
|
||||
};
|
||||
const typed: [number, number] = [Number(width), Number(height)];
|
||||
|
||||
return (
|
||||
<div className='virtual-size'>
|
||||
<label htmlFor={`${id}-size`}>{t('virtualSize')}</label>
|
||||
<select
|
||||
id={`${id}-size`}
|
||||
disabled={!enabled}
|
||||
value={custom || !preset ? CUSTOM : sizeValue(preset)}
|
||||
onChange={(e) => {
|
||||
if (e.target.value === CUSTOM) {
|
||||
setCustom(true);
|
||||
return;
|
||||
}
|
||||
setCustom(false);
|
||||
const [w, h] = e.target.value.split(SEPARATOR).map(Number);
|
||||
setWidth(String(w));
|
||||
setHeight(String(h));
|
||||
void apply([w ?? 0, h ?? 0]);
|
||||
}}
|
||||
>
|
||||
{VIRTUAL_SIZES.map(([w, h]) => (
|
||||
<option key={sizeValue([w, h])} value={sizeValue([w, h])}>
|
||||
{w} × {h}
|
||||
</option>
|
||||
))}
|
||||
<option value={CUSTOM}>{t('virtualSizeCustom')}</option>
|
||||
</select>
|
||||
{(custom || !preset) && (
|
||||
<>
|
||||
<input
|
||||
type='number'
|
||||
className='size-input'
|
||||
min={640}
|
||||
max={7680}
|
||||
step={2}
|
||||
aria-label={t('virtualWidth')}
|
||||
value={width}
|
||||
disabled={!enabled}
|
||||
onChange={(e) => setWidth(e.target.value)}
|
||||
/>
|
||||
<input
|
||||
type='number'
|
||||
className='size-input'
|
||||
min={480}
|
||||
max={4320}
|
||||
step={2}
|
||||
aria-label={t('virtualHeight')}
|
||||
value={height}
|
||||
disabled={!enabled}
|
||||
onChange={(e) => setHeight(e.target.value)}
|
||||
/>
|
||||
<button
|
||||
type='button'
|
||||
className='button muted'
|
||||
disabled={!enabled || (typed[0] === size[0] && typed[1] === size[1])}
|
||||
onClick={() => void apply(typed)}
|
||||
>
|
||||
{t('apply')}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
<span className='help'>{t('virtualSizeHelp')}</span>
|
||||
{error && (
|
||||
<span className='field-error' role='alert'>
|
||||
{error}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { createContext, type ReactNode, useContext, useMemo } from 'react';
|
||||
|
||||
import {
|
||||
type AvailableLanguage,
|
||||
type Catalog,
|
||||
createTranslator,
|
||||
FALLBACK_LANGUAGE,
|
||||
pickLanguage,
|
||||
type Translate,
|
||||
} from '../../viewer/src/lib/i18n';
|
||||
|
||||
/**
|
||||
* Texts of the shell (#21). The same files as the viewer (`locales/*.json`),
|
||||
* embedded at build time: the shell has no server to ask when no share is
|
||||
* running. A file added to the folder is one more language, with no code to
|
||||
* change.
|
||||
*/
|
||||
|
||||
type LocaleFile = Catalog & { _language: AvailableLanguage };
|
||||
|
||||
const FILES = Object.values(
|
||||
import.meta.glob<LocaleFile>('../../../locales/*.json', { eager: true, import: 'default' }),
|
||||
);
|
||||
|
||||
/** The embedded languages, by code. */
|
||||
export const LANGUAGES: AvailableLanguage[] = FILES.map((f) => f._language).sort((a, b) =>
|
||||
a.name.localeCompare(b.name),
|
||||
);
|
||||
|
||||
function catalog(code: string): Catalog | undefined {
|
||||
return FILES.find((f) => f._language.code === code);
|
||||
}
|
||||
|
||||
/**
|
||||
* The language to display: the setting if it names an embedded language,
|
||||
* otherwise the desktop's (`navigator.languages` reflects the session locale).
|
||||
*/
|
||||
export function effectiveLanguage(setting: string | null, preferences: readonly string[]): string {
|
||||
const codes = LANGUAGES.map((l) => l.code);
|
||||
if (setting && codes.includes(setting)) return setting;
|
||||
return pickLanguage(preferences, codes);
|
||||
}
|
||||
|
||||
/** The shell translation in `code`, English as fallback. */
|
||||
export function translatorFor(code: string): Translate {
|
||||
const catalogs = [catalog(code), catalog(FALLBACK_LANGUAGE)].filter(
|
||||
(c): c is Catalog => c !== undefined,
|
||||
);
|
||||
return createTranslator(code, 'desktop', catalogs);
|
||||
}
|
||||
|
||||
type Context = { t: Translate; language: string };
|
||||
|
||||
const I18n = createContext<Context | null>(null);
|
||||
|
||||
export function useI18n(): Context {
|
||||
const context = useContext(I18n);
|
||||
if (!context) throw new Error('useI18n outside of I18nProvider');
|
||||
return context;
|
||||
}
|
||||
|
||||
/** Changing `language` retranslates everything at the next render, without a restart. */
|
||||
export function I18nProvider({ language, children }: { language: string; children: ReactNode }) {
|
||||
const value = useMemo(() => ({ t: translatorFor(language), language }), [language]);
|
||||
return <I18n.Provider value={value}>{children}</I18n.Provider>;
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
import { listen } from '@tauri-apps/api/event';
|
||||
import type { HostState } from '../bindings/HostState';
|
||||
import type { InterfaceOption } from '../bindings/InterfaceOption';
|
||||
import type { Rejection } from '../bindings/Rejection';
|
||||
import type { Settings } from '../bindings/Settings';
|
||||
import type { SettingsOutcome } from '../bindings/SettingsOutcome';
|
||||
import type { SourceChoice } from '../bindings/SourceChoice';
|
||||
import type { SourceOption } from '../bindings/SourceOption';
|
||||
import { noticeOf, type TrayTexts } from './view';
|
||||
|
||||
/**
|
||||
* What the interface can ask of the host. A single real implementation,
|
||||
* through the Tauri commands; the tests provide a fake one.
|
||||
*/
|
||||
export type Host = {
|
||||
state(): Promise<HostState>;
|
||||
/** Returns the function that stops listening. */
|
||||
listen(callback: (state: HostState) => void): Promise<() => void>;
|
||||
sources(): Promise<SourceOption[]>;
|
||||
start(choice: SourceChoice): Promise<void>;
|
||||
stop(): Promise<void>;
|
||||
disconnect(connection: number): Promise<boolean>;
|
||||
/** New QR code and new short code (#19). */
|
||||
regenerateAccess(): Promise<boolean>;
|
||||
/** Trusts the device on this connection: it comes back without a link (#34). */
|
||||
trustDevice(connection: number): Promise<void>;
|
||||
/** Stops trusting a key; a device connected with it is sent away. */
|
||||
revokeDevice(key: string): Promise<void>;
|
||||
/** The host's name for a device (#37); `null` gives back the announced one. */
|
||||
renameDevice(connection: number, alias: string | null): Promise<void>;
|
||||
/** Shares another source without cutting viewers off (#26). */
|
||||
switchSource(choice: SourceChoice): Promise<void>;
|
||||
settings(): Promise<Settings>;
|
||||
/** Rejects with the list of refused values. */
|
||||
updateSettings(settings: Settings): Promise<SettingsOutcome>;
|
||||
interfaces(): Promise<InterfaceOption[]>;
|
||||
/** Returns the path of the written archive. */
|
||||
exportDiagnostics(): Promise<string>;
|
||||
/** The texts of the system tray menu, in the language of the interface. */
|
||||
translateTray(texts: TrayTexts): Promise<void>;
|
||||
/** The host asks for confirmation before quitting (#43). */
|
||||
listenQuit(callback: () => void): Promise<() => void>;
|
||||
quit(dontAskAgain: boolean): Promise<void>;
|
||||
};
|
||||
|
||||
export const tauriHost: Host = {
|
||||
state: () => invoke<HostState>('state'),
|
||||
listen: (callback) => listen<HostState>('state', (event) => callback(event.payload)),
|
||||
sources: () => invoke<SourceOption[]>('sources'),
|
||||
start: (choice) => invoke<void>('start', { choice }),
|
||||
stop: () => invoke<void>('stop'),
|
||||
disconnect: (connection) => invoke<boolean>('disconnect', { connection }),
|
||||
regenerateAccess: () => invoke<boolean>('regenerate_access'),
|
||||
trustDevice: (connection) => invoke<void>('trust_device', { connection }),
|
||||
revokeDevice: (key) => invoke<void>('revoke_device', { key }),
|
||||
switchSource: (choice) => invoke<void>('switch_source', { choice }),
|
||||
renameDevice: (connection, alias) => invoke<void>('rename_device', { connection, alias }),
|
||||
settings: () => invoke<Settings>('settings'),
|
||||
updateSettings: (settings) => invoke<SettingsOutcome>('update_settings', { settings }),
|
||||
interfaces: () => invoke<InterfaceOption[]>('interfaces'),
|
||||
exportDiagnostics: () => invoke<string>('export_diagnostics'),
|
||||
translateTray: (texts) => invoke<void>('translate_tray', { texts }),
|
||||
listenQuit: (callback) => listen('confirm-quit', () => callback()),
|
||||
quit: (dontAskAgain) => invoke<void>('quit', { dontAskAgain }),
|
||||
};
|
||||
|
||||
/** Rejections from Rust arrive as is; any other failure becomes a global rejection. */
|
||||
export function rejectionsOf(error: unknown): Rejection[] {
|
||||
if (Array.isArray(error)) {
|
||||
return error as Rejection[];
|
||||
}
|
||||
return [{ field: 'file', message: noticeOf(error) }];
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { HostState } from '../bindings/HostState';
|
||||
import type { Share } from '../bindings/Share';
|
||||
import type { SourceChoice } from '../bindings/SourceChoice';
|
||||
import type { SourceOption } from '../bindings/SourceOption';
|
||||
import { effectiveLanguage, LANGUAGES, translatorFor } from '../i18n';
|
||||
import {
|
||||
actions,
|
||||
displayCode,
|
||||
displayName,
|
||||
duration,
|
||||
expiry,
|
||||
filter,
|
||||
isVirtualSize,
|
||||
key,
|
||||
noticeOf,
|
||||
outcomeSummary,
|
||||
say,
|
||||
status,
|
||||
trayTexts,
|
||||
VIRTUAL_SIZES,
|
||||
withSize,
|
||||
} from './view';
|
||||
|
||||
const t = translatorFor('fr');
|
||||
|
||||
function state(phase: HostState['phase'], share: Share | null = null): HostState {
|
||||
return {
|
||||
phase,
|
||||
share,
|
||||
error: null,
|
||||
stop: null,
|
||||
warnings: [],
|
||||
sleep_inhibited: [],
|
||||
pending_settings: [],
|
||||
settings_recovered: null,
|
||||
capabilities: {
|
||||
session: 'wayland',
|
||||
desktop: 'Gnome',
|
||||
portal: true,
|
||||
virtual_display: true,
|
||||
pipewire: true,
|
||||
autostart: true,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const pattern = { type: 'synthetic', width: 1280, height: 720 } as const;
|
||||
|
||||
describe('the buttons follow the host state (#15, no button that lies)', () => {
|
||||
it('stopped: start only with a chosen source', () => {
|
||||
expect(actions(state('stopped'), null, false).start).toEqual({ visible: true, enabled: false });
|
||||
expect(actions(state('stopped'), pattern, false).start).toEqual({
|
||||
visible: true,
|
||||
enabled: true,
|
||||
});
|
||||
expect(actions(state('stopped'), pattern, false).stop.visible).toBe(false);
|
||||
});
|
||||
|
||||
it('a command in flight is not sent twice', () => {
|
||||
const a = actions(state('stopped'), pattern, true);
|
||||
expect(a.start.enabled).toBe(false);
|
||||
expect(a.pick).toBe(false);
|
||||
});
|
||||
|
||||
it('while starting: neither start nor change the source, cancel possible', () => {
|
||||
const a = actions(state('starting'), pattern, true);
|
||||
expect(a.start.visible).toBe(false);
|
||||
expect(a.pick).toBe(false);
|
||||
expect(a.cancel).toEqual({ visible: true, enabled: true });
|
||||
});
|
||||
|
||||
it('live: stop only', () => {
|
||||
const a = actions(state('live'), pattern, false);
|
||||
expect(a.stop).toEqual({ visible: true, enabled: true });
|
||||
expect(a.start.visible).toBe(false);
|
||||
expect(a.cancel.visible).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('status', () => {
|
||||
it('counts the viewers', () => {
|
||||
const share = { devices: [{}, {}] } as unknown as Share;
|
||||
expect(status(state('live', share), t).text).toBe('En direct, 2 spectateurs');
|
||||
const nobody = status(state('live', { devices: [] } as unknown as Share), t);
|
||||
expect(nobody).toEqual({ text: 'En direct, personne ne regarde', tone: 'live' });
|
||||
expect(status(state('starting'), t).tone).toBe('waiting');
|
||||
const en = translatorFor('en');
|
||||
expect(status(state('live', share), en).text).toBe('Live, 2 viewers');
|
||||
});
|
||||
});
|
||||
|
||||
describe('sources', () => {
|
||||
const source = (name: string, id: string): SourceOption => ({
|
||||
choice: { type: 'x11', id },
|
||||
kind: 'window',
|
||||
name,
|
||||
label: { type: 'title', text: name },
|
||||
width: 800,
|
||||
height: 600,
|
||||
thumbnail: null,
|
||||
note: null,
|
||||
available: true,
|
||||
});
|
||||
|
||||
it('the search ignores accents and case', () => {
|
||||
const list = [source('Présentation.odp', 'a'), source('Terminal', 'b')];
|
||||
expect(filter(list, 'presen', t).map((s) => s.name)).toEqual(['Présentation.odp']);
|
||||
expect(filter(list, ' ', t)).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('the search looks at the displayed name, in the language of the interface (#21)', () => {
|
||||
const pattern: SourceOption = {
|
||||
...source('Mire de test', 'm'),
|
||||
choice: { type: 'synthetic', width: 64, height: 64 },
|
||||
label: { type: 'test_pattern' },
|
||||
};
|
||||
expect(filter([pattern], 'test pattern', translatorFor('en'))).toHaveLength(1);
|
||||
expect(displayName({ type: 'monitor', output: 'HDMI-1', primary: true }, t)).toBe(
|
||||
'HDMI-1 (principal)',
|
||||
);
|
||||
});
|
||||
|
||||
it('every label has a name in English and in French', () => {
|
||||
const labels = [
|
||||
'screen',
|
||||
'window',
|
||||
'virtual_screen',
|
||||
'test_pattern',
|
||||
'recorded_pattern',
|
||||
'all_screens',
|
||||
'entire_screen',
|
||||
'chosen_screen',
|
||||
'chosen_window',
|
||||
] as const;
|
||||
for (const type of labels) {
|
||||
expect(displayName({ type }, t)).not.toBe('');
|
||||
expect(displayName({ type }, translatorFor('en'))).not.toBe('');
|
||||
}
|
||||
});
|
||||
|
||||
it('the key tells an existing screen from a virtual one', () => {
|
||||
expect(key({ type: 'portal', virtual_display: false, window: true, size: null })).not.toBe(
|
||||
key({ type: 'portal', virtual_display: false, window: false, size: null }),
|
||||
);
|
||||
expect(key({ type: 'portal', virtual_display: true, window: false, size: null })).not.toBe(
|
||||
key({ type: 'portal', virtual_display: false, window: false, size: null }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('texts', () => {
|
||||
it('durations stay short', () => {
|
||||
expect(duration(0, 42_000)).toBe('42 s');
|
||||
expect(duration(0, 5 * 60_000)).toBe('5 min');
|
||||
expect(duration(0, 65 * 60_000)).toBe('1 h 05');
|
||||
expect(duration(10_000, 0)).toBe('0 s');
|
||||
});
|
||||
|
||||
it('a pending setting is said', () => {
|
||||
expect(outcomeSummary({ immediate: ['limit'], next_share: [] }, t)).toContain('appliqués');
|
||||
const pending = {
|
||||
code: 'pending_port',
|
||||
params: { field: 'port' },
|
||||
text: 'port: changing the port would cut viewers off',
|
||||
};
|
||||
expect(outcomeSummary({ immediate: [], next_share: [pending] }, t)).toContain(
|
||||
'prochain partage',
|
||||
);
|
||||
});
|
||||
|
||||
it('a host text follows the interface language (#75)', () => {
|
||||
const busy = {
|
||||
code: 'port_in_use_free',
|
||||
params: { port: '8099', free: '8100' },
|
||||
text: 'port 8099 is already used by another program: port 8100 is free',
|
||||
};
|
||||
const en = translatorFor('en');
|
||||
expect(say(busy, en)).toContain('8100');
|
||||
expect(say(busy, t)).toContain('8100');
|
||||
expect(say(busy, t)).not.toBe(say(busy, en));
|
||||
// A code this shell does not know yet: the host's sentence, not nothing.
|
||||
const newer = { code: 'from_the_future', params: {}, text: 'A newer host speaks.' };
|
||||
expect(say(newer, t)).toBe('A newer host speaks.');
|
||||
expect(noticeOf('boom').text).toBe('boom');
|
||||
expect(noticeOf(busy)).toBe(busy);
|
||||
});
|
||||
});
|
||||
|
||||
describe('short code (#19)', () => {
|
||||
it('shows in two groups of three', () => {
|
||||
expect(displayCode('k7m4pq')).toBe('K7M 4PQ');
|
||||
});
|
||||
|
||||
it('says what is left, in seconds during the last minute', () => {
|
||||
expect(expiry(null, 0, t)).toBeNull();
|
||||
expect(expiry(10 * 60_000, 0, t)).toContain('10 min');
|
||||
expect(expiry(30_000, 0, t)).toContain('30 s');
|
||||
expect(expiry(0, 1, t)).toBe(t('codeExpired'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('language (#21)', () => {
|
||||
it('French and English are embedded', () => {
|
||||
const codes = LANGUAGES.map((l) => l.code);
|
||||
expect(codes).toContain('fr');
|
||||
expect(codes).toContain('en');
|
||||
expect(LANGUAGES.find((l) => l.code === 'fr')?.name).toBe('Français');
|
||||
});
|
||||
|
||||
it('the setting wins, then the desktop language, then English', () => {
|
||||
expect(effectiveLanguage('fr', ['en-US'])).toBe('fr');
|
||||
expect(effectiveLanguage(null, ['fr-FR'])).toBe('fr');
|
||||
expect(effectiveLanguage(null, ['de-DE'])).toBe('en');
|
||||
expect(effectiveLanguage('xx', ['fr-BE'])).toBe('fr');
|
||||
});
|
||||
|
||||
it('the system tray gets the three forms, {count} to replace', () => {
|
||||
const tray = trayTexts(t);
|
||||
expect(tray.live.zero).toBe('En direct, personne ne regarde');
|
||||
expect(tray.live.one).toBe('En direct, 1 spectateur');
|
||||
expect(tray.live.other).toBe('En direct, {count} spectateurs');
|
||||
});
|
||||
});
|
||||
|
||||
describe('virtual screen size (#89)', () => {
|
||||
it('every offered size is accepted, odd or out of bounds ones are not', () => {
|
||||
for (const size of VIRTUAL_SIZES) expect(isVirtualSize(size)).toBe(true);
|
||||
expect(isVirtualSize([1281, 800])).toBe(false);
|
||||
expect(isVirtualSize([320, 240])).toBe(false);
|
||||
expect(isVirtualSize([8192, 4320])).toBe(false);
|
||||
expect(isVirtualSize([Number.NaN, 800])).toBe(false);
|
||||
});
|
||||
|
||||
it('only a virtual screen changes size', () => {
|
||||
const virtual: SourceChoice = {
|
||||
type: 'portal',
|
||||
virtual_display: true,
|
||||
window: false,
|
||||
size: [1920, 1080],
|
||||
};
|
||||
expect(withSize(virtual, [1280, 800])).toEqual({ ...virtual, size: [1280, 800] });
|
||||
const screen: SourceChoice = {
|
||||
type: 'portal',
|
||||
virtual_display: false,
|
||||
window: false,
|
||||
size: null,
|
||||
};
|
||||
expect(withSize(screen, [1280, 800])).toBe(screen);
|
||||
// The identity does not depend on the size: the selection survives.
|
||||
expect(key(withSize(virtual, [1280, 800]))).toBe(key(virtual));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,269 @@
|
||||
import type { Translate } from '../../../viewer/src/lib/i18n';
|
||||
import type { HostState } from '../bindings/HostState';
|
||||
import type { Label } from '../bindings/Label';
|
||||
import type { Notice } from '../bindings/Notice';
|
||||
import type { SettingsOutcome } from '../bindings/SettingsOutcome';
|
||||
import type { SourceChoice } from '../bindings/SourceChoice';
|
||||
import type { SourceOption } from '../bindings/SourceOption';
|
||||
|
||||
/**
|
||||
* What the buttons show, derived from the host state and nothing else.
|
||||
*
|
||||
* This is the criterion of #15, "no button that lies": a button has no state
|
||||
* of its own. `sending` only says that a command went out and that its answer
|
||||
* has not come back, so as not to send it twice.
|
||||
*/
|
||||
export type Actions = {
|
||||
/** The source list is clickable. */
|
||||
pick: boolean;
|
||||
start: { visible: boolean; enabled: boolean };
|
||||
cancel: { visible: boolean; enabled: boolean };
|
||||
stop: { visible: boolean; enabled: boolean };
|
||||
};
|
||||
|
||||
export function actions(
|
||||
state: HostState,
|
||||
selection: SourceChoice | null,
|
||||
sending: boolean,
|
||||
): Actions {
|
||||
switch (state.phase) {
|
||||
case 'stopped':
|
||||
return {
|
||||
pick: !sending,
|
||||
start: { visible: true, enabled: selection !== null && !sending },
|
||||
cancel: { visible: false, enabled: false },
|
||||
stop: { visible: false, enabled: false },
|
||||
};
|
||||
case 'starting':
|
||||
return {
|
||||
pick: false,
|
||||
start: { visible: false, enabled: false },
|
||||
cancel: { visible: true, enabled: true },
|
||||
stop: { visible: false, enabled: false },
|
||||
};
|
||||
case 'live':
|
||||
return {
|
||||
pick: false,
|
||||
start: { visible: false, enabled: false },
|
||||
cancel: { visible: false, enabled: false },
|
||||
stop: { visible: true, enabled: !sending },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export type Status = { text: string; tone: 'idle' | 'waiting' | 'live' };
|
||||
|
||||
export function status(state: HostState, t: Translate): Status {
|
||||
switch (state.phase) {
|
||||
case 'stopped':
|
||||
return { text: t('statusStopped'), tone: 'idle' };
|
||||
case 'starting':
|
||||
return { text: t('statusStarting'), tone: 'waiting' };
|
||||
case 'live': {
|
||||
const n = state.share?.devices.length ?? 0;
|
||||
return { text: t('statusLive', { count: n }), tone: 'live' };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sizes offered for a virtual screen (#89): common tablet and monitor
|
||||
* resolutions, in landscape. Any other even size can be typed.
|
||||
*/
|
||||
export const VIRTUAL_SIZES: [number, number][] = [
|
||||
[1280, 800],
|
||||
[1920, 1080],
|
||||
[1920, 1200],
|
||||
[2048, 1536],
|
||||
[2360, 1640],
|
||||
[2560, 1600],
|
||||
[2732, 2048],
|
||||
[3840, 2160],
|
||||
];
|
||||
|
||||
/** Mirrors `rs_store::is_virtual_size`: even, from 640 × 480 to 7680 × 4320. */
|
||||
export function isVirtualSize([width, height]: [number, number]): boolean {
|
||||
return (
|
||||
Number.isInteger(width) &&
|
||||
Number.isInteger(height) &&
|
||||
width % 2 === 0 &&
|
||||
height % 2 === 0 &&
|
||||
width >= 640 &&
|
||||
width <= 7680 &&
|
||||
height >= 480 &&
|
||||
height <= 4320
|
||||
);
|
||||
}
|
||||
|
||||
/** Is this choice a virtual screen, whose size can be chosen? */
|
||||
export function isVirtual(choice: SourceChoice | null): boolean {
|
||||
return choice?.type === 'portal' && choice.virtual_display;
|
||||
}
|
||||
|
||||
/** The same virtual screen at another size; any other choice unchanged. */
|
||||
export function withSize(choice: SourceChoice, size: [number, number]): SourceChoice {
|
||||
return choice.type === 'portal' && choice.virtual_display ? { ...choice, size } : choice;
|
||||
}
|
||||
|
||||
/** Stable identity of a choice, for the selection and React keys. */
|
||||
export function key(choice: SourceChoice): string {
|
||||
switch (choice.type) {
|
||||
case 'x11':
|
||||
return `x11:${choice.id}`;
|
||||
case 'windows':
|
||||
return `windows:${choice.id}`;
|
||||
case 'portal':
|
||||
if (choice.virtual_display) return 'portal:virtual';
|
||||
return choice.window ? 'portal:window' : 'portal:screen';
|
||||
case 'synthetic':
|
||||
return 'synthetic';
|
||||
case 'playback':
|
||||
return `playback:${choice.path}`;
|
||||
}
|
||||
}
|
||||
|
||||
function normalize(text: string): string {
|
||||
return text
|
||||
.normalize('NFD')
|
||||
.replace(/\p{Diacritic}/gu, '')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Search by displayed name, ignoring accents and case: one searches for what
|
||||
* one reads, in the language of the interface.
|
||||
*/
|
||||
export function filter(sources: SourceOption[], search: string, t: Translate): SourceOption[] {
|
||||
const wanted = normalize(search.trim());
|
||||
if (wanted === '') {
|
||||
return sources;
|
||||
}
|
||||
return sources.filter((s) => normalize(displayName(s.label, t)).includes(wanted));
|
||||
}
|
||||
|
||||
/** The name of a source in the language of the interface (#21). */
|
||||
export function displayName(label: Label, t: Translate): string {
|
||||
switch (label.type) {
|
||||
case 'title':
|
||||
return label.text;
|
||||
case 'monitor':
|
||||
return label.primary ? t('sources.primary', { output: label.output }) : label.output;
|
||||
case 'screen':
|
||||
return t('sources.screen');
|
||||
case 'window':
|
||||
return t('sources.window');
|
||||
case 'virtual_screen':
|
||||
return t('sources.virtual_screen');
|
||||
case 'test_pattern':
|
||||
return t('sources.test_pattern');
|
||||
case 'recorded_pattern':
|
||||
return t('sources.recorded_pattern');
|
||||
case 'all_screens':
|
||||
return t('sources.all_screens');
|
||||
case 'entire_screen':
|
||||
return t('sources.entire_screen');
|
||||
case 'chosen_screen':
|
||||
return t('sources.chosen_screen');
|
||||
case 'chosen_window':
|
||||
return t('sources.chosen_window');
|
||||
}
|
||||
}
|
||||
|
||||
/** Readable duration since a Unix date in milliseconds. */
|
||||
export function duration(sinceMs: number, nowMs: number): string {
|
||||
const seconds = Math.max(0, Math.floor((nowMs - sinceMs) / 1000));
|
||||
if (seconds < 60) {
|
||||
return `${seconds} s`;
|
||||
}
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
if (minutes < 60) {
|
||||
return `${minutes} min`;
|
||||
}
|
||||
const hours = Math.floor(minutes / 60);
|
||||
return `${hours} h ${String(minutes % 60).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* A text produced by the host, in the interface language (#75): the code is
|
||||
* looked up under `host`, the English sentence of the host stands in for a
|
||||
* code this shell does not know yet.
|
||||
*/
|
||||
export function say(notice: Notice, t: Translate): string {
|
||||
return t(`host.${notice.code}`, notice.params) || notice.text;
|
||||
}
|
||||
|
||||
/** Turns any failure into a notice: a command rejects with one, or with anything else. */
|
||||
export function noticeOf(error: unknown): Notice {
|
||||
if (error && typeof error === 'object' && 'code' in error && 'text' in error) {
|
||||
return error as Notice;
|
||||
}
|
||||
return { code: '', params: {}, text: String(error) };
|
||||
}
|
||||
|
||||
/** What is said after saving settings. */
|
||||
export function outcomeSummary(outcome: SettingsOutcome, t: Translate): string {
|
||||
if (outcome.next_share.length > 0) {
|
||||
return t('settingsPending', {
|
||||
fields: outcome.next_share.map((n) => say(n, t)).join('; '),
|
||||
});
|
||||
}
|
||||
if (outcome.immediate.length > 0) {
|
||||
return t('settingsApplied');
|
||||
}
|
||||
return t('settingsUnchanged');
|
||||
}
|
||||
|
||||
/** The short code as it is read and dictated: `K7M 4PQ`. */
|
||||
export function displayCode(code: string): string {
|
||||
const upper = code.toUpperCase();
|
||||
return upper.length === 6 ? `${upper.slice(0, 3)} ${upper.slice(3)}` : upper;
|
||||
}
|
||||
|
||||
/**
|
||||
* What remains of the access code, in plain words, or `null` if it does not
|
||||
* expire. Under a minute, it counts in seconds: that is when the host must
|
||||
* know that a newcomer is about to be refused.
|
||||
*/
|
||||
export function expiry(expiresMs: number | null, now: number, t: Translate): string | null {
|
||||
if (expiresMs === null) return null;
|
||||
const remaining = expiresMs - now;
|
||||
if (remaining <= 0) return t('codeExpired');
|
||||
if (remaining < 60_000)
|
||||
return t('codeExpiresIn', { duration: `${Math.ceil(remaining / 1000)} s` });
|
||||
return t('codeExpiresIn', { duration: `${Math.ceil(remaining / 60_000)} min` });
|
||||
}
|
||||
|
||||
/** What the system tray menu shows, translated (#21, #22). */
|
||||
export type TrayTexts = {
|
||||
none: string;
|
||||
starting: string;
|
||||
/** Forms of the live status, by exact number then category. */
|
||||
live: { zero: string; one: string; other: string };
|
||||
open: string;
|
||||
start: string;
|
||||
resume: string;
|
||||
stop: string;
|
||||
quit: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The texts of the system tray. Rust does not know the plural rules of each
|
||||
* language: it gets the forms for 0, 1 and the rest, with `{count}` to
|
||||
* replace.
|
||||
*/
|
||||
export function trayTexts(t: Translate): TrayTexts {
|
||||
return {
|
||||
none: t('tray.none'),
|
||||
starting: t('tray.starting'),
|
||||
live: {
|
||||
zero: t('tray.live', { count: 0 }),
|
||||
one: t('tray.live', { count: 1 }),
|
||||
other: t('tray.live', { count: '{count}' }),
|
||||
},
|
||||
open: t('tray.open'),
|
||||
start: t('tray.start'),
|
||||
resume: t('tray.resume'),
|
||||
stop: t('tray.stop'),
|
||||
quit: t('tray.quit'),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { StrictMode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { App } from './App';
|
||||
import { tauriHost } from './lib/host';
|
||||
import './styles.css';
|
||||
|
||||
const root = document.getElementById('root');
|
||||
if (!root) throw new Error('root element missing');
|
||||
|
||||
createRoot(root).render(
|
||||
<StrictMode>
|
||||
<App host={tauriHost} />
|
||||
</StrictMode>,
|
||||
);
|
||||
@@ -0,0 +1,629 @@
|
||||
/* Desktop shell. System fonts, no remote resource. Sizes in rem: the
|
||||
interface follows the desktop scale factor (HiDPI) without images to double. */
|
||||
|
||||
:root {
|
||||
--bg: #f5f6f8;
|
||||
--surface: #ffffff;
|
||||
--border: #d9dee5;
|
||||
--text: #18202a;
|
||||
--muted: #5d6b7c;
|
||||
--accent: #2563eb;
|
||||
--accent-text: #ffffff;
|
||||
/* Dark enough for text on a light background: AA contrast (4.5:1) checked
|
||||
for each text and background pair (#28). */
|
||||
--live: #15803d;
|
||||
--waiting: #b45309;
|
||||
--danger: #b91c1c;
|
||||
--warning-bg: #fff7e6;
|
||||
--error-bg: #fdecec;
|
||||
--info-bg: #eaf1ff;
|
||||
--radius: 10px;
|
||||
color-scheme: light;
|
||||
font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Cantarell", sans-serif;
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
:root[data-theme="dark"] {
|
||||
--bg: #0d1116;
|
||||
--surface: #151b23;
|
||||
--border: #2a3441;
|
||||
--text: #e9eef5;
|
||||
--muted: #97a5b6;
|
||||
--accent: #4c9aff;
|
||||
--accent-text: #0d1116;
|
||||
--live: #3ddc84;
|
||||
--waiting: #f5a524;
|
||||
--danger: #ff6b6b;
|
||||
--warning-bg: #2b2210;
|
||||
--error-bg: #2e1517;
|
||||
--info-bg: #13213a;
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root[data-theme="system"] {
|
||||
--bg: #0d1116;
|
||||
--surface: #151b23;
|
||||
--border: #2a3441;
|
||||
--text: #e9eef5;
|
||||
--muted: #97a5b6;
|
||||
--accent: #4c9aff;
|
||||
--accent-text: #0d1116;
|
||||
--live: #3ddc84;
|
||||
--waiting: #f5a524;
|
||||
--danger: #ff6b6b;
|
||||
--warning-bg: #2b2210;
|
||||
--error-bg: #2e1517;
|
||||
--info-bg: #13213a;
|
||||
color-scheme: dark;
|
||||
}
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html,
|
||||
body,
|
||||
#root {
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
h1,
|
||||
h2 {
|
||||
margin: 0;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 1.15rem;
|
||||
}
|
||||
|
||||
h2 {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.loading {
|
||||
display: grid;
|
||||
height: 100%;
|
||||
place-items: center;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.app {
|
||||
display: flex;
|
||||
height: 100%;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.header,
|
||||
.action-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
padding: 0.75rem 1.25rem;
|
||||
background: var(--surface);
|
||||
}
|
||||
|
||||
.header {
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.action-bar {
|
||||
border-top: 1px solid var(--border);
|
||||
min-height: 3.75rem;
|
||||
}
|
||||
|
||||
.spacer {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.content {
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
padding: 1.25rem;
|
||||
}
|
||||
|
||||
.badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
padding: 0.2rem 0.65rem;
|
||||
border-radius: 999px;
|
||||
border: 1px solid var(--border);
|
||||
color: var(--muted);
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.badge::before {
|
||||
content: "";
|
||||
width: 0.5rem;
|
||||
height: 0.5rem;
|
||||
border-radius: 50%;
|
||||
background: currentColor;
|
||||
}
|
||||
|
||||
.badge.live {
|
||||
color: var(--live);
|
||||
border-color: currentColor;
|
||||
}
|
||||
|
||||
.badge.waiting {
|
||||
color: var(--waiting);
|
||||
border-color: currentColor;
|
||||
}
|
||||
|
||||
.sleep {
|
||||
color: var(--muted);
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.button {
|
||||
padding: 0.5rem 1rem;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--surface);
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.button:hover:not(:disabled) {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.button:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.button.primary {
|
||||
background: var(--accent);
|
||||
border-color: var(--accent);
|
||||
color: var(--accent-text);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.button.danger {
|
||||
color: var(--danger);
|
||||
border-color: var(--danger);
|
||||
}
|
||||
|
||||
.button.muted {
|
||||
padding: 0.35rem 0.75rem;
|
||||
}
|
||||
|
||||
.help,
|
||||
.muted {
|
||||
color: var(--muted);
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.banner {
|
||||
margin-bottom: 1rem;
|
||||
padding: 0.65rem 0.9rem;
|
||||
border-radius: var(--radius);
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.banner.error {
|
||||
background: var(--error-bg);
|
||||
border-color: var(--danger);
|
||||
}
|
||||
|
||||
.banner.warning {
|
||||
background: var(--warning-bg);
|
||||
border-color: var(--waiting);
|
||||
}
|
||||
|
||||
.banner.info {
|
||||
background: var(--info-bg);
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.picker-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.picker-header h2 {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.search,
|
||||
.form input:not([type="checkbox"]),
|
||||
.form select,
|
||||
.link input {
|
||||
padding: 0.45rem 0.6rem;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.search {
|
||||
width: 16rem;
|
||||
}
|
||||
|
||||
.sources {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(13rem, 1fr));
|
||||
gap: 0.9rem;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.source {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
flex-direction: column;
|
||||
gap: 0.3rem;
|
||||
padding: 0.6rem;
|
||||
border: 2px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
background: var(--surface);
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.source:hover:not(:disabled) {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.source.selected {
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 25%, transparent);
|
||||
}
|
||||
|
||||
.source:disabled {
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.source.unavailable {
|
||||
border-style: dashed;
|
||||
}
|
||||
|
||||
.thumbnail {
|
||||
display: grid;
|
||||
aspect-ratio: 16 / 9;
|
||||
place-items: center;
|
||||
overflow: hidden;
|
||||
border-radius: 6px;
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
/* The text keeps its contrast: only the picture fades. The note says why the
|
||||
source cannot be shared (#17). */
|
||||
.source:disabled .thumbnail {
|
||||
opacity: 0.45;
|
||||
}
|
||||
|
||||
.thumbnail img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.thumbnail-empty {
|
||||
color: var(--muted);
|
||||
font-size: 2.5rem;
|
||||
}
|
||||
|
||||
.source-name {
|
||||
overflow: hidden;
|
||||
font-weight: 600;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.source-size,
|
||||
.source-note {
|
||||
color: var(--muted);
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.waiting {
|
||||
margin: 0;
|
||||
color: var(--waiting);
|
||||
}
|
||||
|
||||
.share {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(18rem, 22rem) 1fr;
|
||||
gap: 1.25rem;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
@media (max-width: 860px) {
|
||||
.share {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
.card {
|
||||
padding: 1.1rem;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
background: var(--surface);
|
||||
}
|
||||
|
||||
.qr-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.9rem;
|
||||
}
|
||||
|
||||
.qr {
|
||||
padding: 0.75rem;
|
||||
border-radius: 8px;
|
||||
background: #ffffff;
|
||||
line-height: 0;
|
||||
}
|
||||
|
||||
.qr svg {
|
||||
width: 100%;
|
||||
height: auto;
|
||||
}
|
||||
|
||||
.link {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.35rem;
|
||||
font-size: 0.85rem;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.link-row {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.link input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-family: ui-monospace, monospace;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.fingerprint code {
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.facts {
|
||||
display: grid;
|
||||
grid-template-columns: auto 1fr;
|
||||
gap: 0.4rem 1rem;
|
||||
margin: 0 0 1.25rem;
|
||||
}
|
||||
|
||||
.facts dt {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.facts dd {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.viewers-title {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 0.6rem;
|
||||
margin-bottom: 0.6rem;
|
||||
}
|
||||
|
||||
.counter {
|
||||
color: var(--muted);
|
||||
font-size: 0.85rem;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.devices {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.devices li {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr auto;
|
||||
align-items: center;
|
||||
gap: 0.15rem 0.75rem;
|
||||
padding: 0.6rem 0;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.devices li .muted {
|
||||
grid-column: 1;
|
||||
}
|
||||
|
||||
.devices li .button {
|
||||
grid-column: 2;
|
||||
grid-row: 1 / span 2;
|
||||
}
|
||||
|
||||
.devices li .device-actions {
|
||||
grid-column: 2;
|
||||
grid-row: 1 / span 2;
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.device-name {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.link-button {
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
cursor: text;
|
||||
}
|
||||
|
||||
.alias-reset {
|
||||
margin-left: 0.5rem;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 400;
|
||||
text-decoration: underline;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.device-name input {
|
||||
font: inherit;
|
||||
padding: 0.1rem 0.3rem;
|
||||
}
|
||||
|
||||
.trusted-mark {
|
||||
margin-left: 0.5rem;
|
||||
color: var(--live);
|
||||
font-size: 0.8rem;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 1rem;
|
||||
background: rgb(0 0 0 / 45%);
|
||||
}
|
||||
|
||||
.dialog {
|
||||
width: min(34rem, 100%);
|
||||
max-height: 100%;
|
||||
overflow: auto;
|
||||
padding: 1.25rem;
|
||||
border-radius: var(--radius);
|
||||
background: var(--surface);
|
||||
}
|
||||
|
||||
.form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.9rem;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.3rem;
|
||||
}
|
||||
|
||||
.field label {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.field.has-error input,
|
||||
.field.has-error select {
|
||||
border-color: var(--danger);
|
||||
}
|
||||
|
||||
.checkbox {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.debug {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 0.6rem;
|
||||
margin: 0;
|
||||
padding: 0.75rem;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
}
|
||||
|
||||
.debug legend {
|
||||
padding: 0 0.3rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.virtual-size {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
margin-top: 0.9rem;
|
||||
}
|
||||
|
||||
.size-input {
|
||||
width: 5.5rem;
|
||||
}
|
||||
|
||||
.field-error {
|
||||
color: var(--danger);
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.confirmation {
|
||||
margin: 0;
|
||||
color: var(--live);
|
||||
}
|
||||
|
||||
.dialog-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.6rem;
|
||||
}
|
||||
|
||||
/* Short code (#19): readable from afar, easy to dictate. */
|
||||
.short-code {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.35rem 0.75rem;
|
||||
align-items: baseline;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.short-code > .muted:first-child {
|
||||
flex-basis: 100%;
|
||||
}
|
||||
|
||||
.short-code > .local-name {
|
||||
flex-basis: 100%;
|
||||
order: 1;
|
||||
}
|
||||
|
||||
.code-value {
|
||||
font:
|
||||
700 1.6rem / 1.1 ui-monospace,
|
||||
"SF Mono",
|
||||
Menlo,
|
||||
monospace;
|
||||
letter-spacing: 0.12em;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.code-expired .code-value {
|
||||
color: var(--muted);
|
||||
text-decoration: line-through;
|
||||
}
|
||||
|
||||
.code-new {
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.warning-text {
|
||||
color: var(--waiting);
|
||||
font-weight: 600;
|
||||
}
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"lib": [
|
||||
"ES2022",
|
||||
"DOM",
|
||||
"DOM.Iterable"
|
||||
],
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"skipLibCheck": true,
|
||||
"noEmit": true
|
||||
},
|
||||
"include": [
|
||||
"src"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import react from '@vitejs/plugin-react';
|
||||
import { defineConfig } from 'vite';
|
||||
|
||||
// Served by Tauri from `dist`: no server, no remote resource.
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
clearScreen: false,
|
||||
build: {
|
||||
target: 'es2022',
|
||||
sourcemap: true,
|
||||
},
|
||||
server: {
|
||||
port: 5175,
|
||||
strictPort: true,
|
||||
},
|
||||
});
|
||||
Generated
+23
-44
@@ -1,13 +1,15 @@
|
||||
{
|
||||
"name": "@rustscreen/viewer",
|
||||
"version": "0.1.1",
|
||||
"version": "0.5.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@rustscreen/viewer",
|
||||
"version": "0.1.1",
|
||||
"version": "0.5.0",
|
||||
"dependencies": {
|
||||
"@noble/ed25519": "^3.2.0",
|
||||
"@noble/hashes": "^2.4.0",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0"
|
||||
},
|
||||
@@ -126,9 +128,6 @@
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT OR Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -146,9 +145,6 @@
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT OR Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -166,9 +162,6 @@
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT OR Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -186,9 +179,6 @@
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT OR Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -260,6 +250,25 @@
|
||||
"@jridgewell/sourcemap-codec": "^1.4.14"
|
||||
}
|
||||
},
|
||||
"node_modules/@noble/ed25519": {
|
||||
"version": "3.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@noble/ed25519/-/ed25519-3.2.0.tgz",
|
||||
"integrity": "sha512-criDgRlnUA09hchYrTy/JUWPIEap5rZxQe6wDWzRx51oWWpDRcUpuNzlgPxDJaOK6AsW9c0wKcj3rKRv6t+bPQ==",
|
||||
"funding": {
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/@noble/hashes": {
|
||||
"version": "2.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.4.0.tgz",
|
||||
"integrity": "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==",
|
||||
"engines": {
|
||||
"node": ">= 20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/@oxc-project/types": {
|
||||
"version": "0.155.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.155.0.tgz",
|
||||
@@ -380,9 +389,6 @@
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -400,9 +406,6 @@
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -420,9 +423,6 @@
|
||||
"ppc64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -440,9 +440,6 @@
|
||||
"s390x"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -460,9 +457,6 @@
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -480,9 +474,6 @@
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1243,9 +1234,6 @@
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MPL-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1267,9 +1255,6 @@
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MPL-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1291,9 +1276,6 @@
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MPL-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1315,9 +1297,6 @@
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MPL-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
{
|
||||
"name": "@rustscreen/viewer",
|
||||
"private": true,
|
||||
"version": "0.1.1",
|
||||
"version": "0.5.0",
|
||||
"type": "module",
|
||||
"description": "Client navigateur de rustscreen: reçoit le flux WebRTC de l'hôte.",
|
||||
"description": "rustscreen browser client: receives the WebRTC stream from the host.",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc --noEmit && vite build",
|
||||
"preview": "vite preview",
|
||||
"lint": "biome lint src",
|
||||
"lint": "biome lint src && node ../../scripts/check-i18n.mjs apps/viewer/src viewer",
|
||||
"format": "biome format --write src",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@noble/ed25519": "^3.2.0",
|
||||
"@noble/hashes": "^2.4.0",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0"
|
||||
},
|
||||
|
||||
+205
-34
@@ -1,37 +1,77 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
|
||||
import { ErrorPanel } from './components/ErrorPanel';
|
||||
import { Pairing } from './components/Pairing';
|
||||
import { SettingsPanel } from './components/SettingsPanel';
|
||||
import { StatsBar } from './components/StatsBar';
|
||||
import { StatusBadge } from './components/StatusBadge';
|
||||
import { VideoStage } from './components/VideoStage';
|
||||
import { useI18n } from './i18n';
|
||||
import {
|
||||
barsVisible,
|
||||
IDLE_DELAY_MS,
|
||||
isCompact,
|
||||
readPinned,
|
||||
readStatsShown,
|
||||
savePinned,
|
||||
saveStatsShown,
|
||||
} from './lib/controls';
|
||||
import { parseRoomLocation, signalingUrl } from './lib/room';
|
||||
import {
|
||||
nextRotation,
|
||||
type Rotation,
|
||||
readMirror,
|
||||
readRotation,
|
||||
saveMirror,
|
||||
saveRotation,
|
||||
} from './lib/rotation';
|
||||
import { type VideoStats, ViewerSession, type ViewerState } from './lib/session';
|
||||
import { strings } from './strings';
|
||||
import { isTrusted } from './lib/trust';
|
||||
import { useActivity } from './lib/useActivity';
|
||||
import type { SourceInfo } from './proto';
|
||||
|
||||
const SWITCH_NOTICE_MS = 2500;
|
||||
|
||||
export function App() {
|
||||
const { t } = useI18n();
|
||||
const location = useMemo(
|
||||
() => parseRoomLocation(window.location.pathname, window.location.search),
|
||||
() => parseRoomLocation(window.location.pathname, window.location.search, window.location.hash),
|
||||
[],
|
||||
);
|
||||
// A device the host trusts comes back from the bare home page, without a
|
||||
// link: it proves its key instead (#34).
|
||||
const byKey = useMemo(
|
||||
() => !location.ok && location.reason === 'missing_room' && isTrusted(),
|
||||
[location],
|
||||
);
|
||||
const [state, setState] = useState<ViewerState>({ kind: 'connecting', attempt: 0 });
|
||||
const [stream, setStream] = useState<MediaStream | null>(null);
|
||||
const [stats, setStats] = useState<VideoStats | null>(null);
|
||||
const [attemptKey, setAttemptKey] = useState(0);
|
||||
const [isFullscreen, setIsFullscreen] = useState(false);
|
||||
const [settingsOpen, setSettingsOpen] = useState(false);
|
||||
const [statsShown, setStatsShown] = useState(() => readStatsShown());
|
||||
const [rotation, setRotation] = useState<Rotation>(() => readRotation());
|
||||
const [mirror, setMirror] = useState(() => readMirror());
|
||||
const [pinned, setPinned] = useState(() => readPinned());
|
||||
const [held, setHeld] = useState(false);
|
||||
const [switched, setSwitched] = useState<SourceInfo | null>(null);
|
||||
const active = useActivity(IDLE_DELAY_MS);
|
||||
const sessionRef = useRef<ViewerSession | null>(null);
|
||||
const containerRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
// Une session par montage. Le nettoyage est obligatoire: sans lui, le double
|
||||
// montage de StrictMode ouvre deux WebSocket et deux négociations.
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: attemptKey est la clé de relance du bouton « réessayer », volontairement sans usage dans le corps.
|
||||
// One session per mount. The cleanup is mandatory: without it, the double
|
||||
// mount of StrictMode opens two WebSockets and two negotiations.
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: attemptKey is the restart key of the "retry" button, deliberately unused in the body.
|
||||
useEffect(() => {
|
||||
if (!location.ok) return;
|
||||
if (!location.ok && !byKey) return;
|
||||
const session = new ViewerSession({
|
||||
room: location.value.room,
|
||||
token: location.value.token,
|
||||
room: location.ok ? location.value.room : null,
|
||||
token: location.ok ? location.value.token : null,
|
||||
wsUrl: signalingUrl(window.location),
|
||||
onState: setState,
|
||||
onStream: setStream,
|
||||
onSourceChanged: setSwitched,
|
||||
});
|
||||
sessionRef.current = session;
|
||||
session.start();
|
||||
@@ -39,10 +79,10 @@ export function App() {
|
||||
session.stop();
|
||||
sessionRef.current = null;
|
||||
};
|
||||
}, [location, attemptKey]);
|
||||
}, [location, byKey, attemptKey]);
|
||||
|
||||
useEffect(() => {
|
||||
if (state.kind !== 'streaming') {
|
||||
if (state.kind !== 'streaming' || !statsShown) {
|
||||
setStats(null);
|
||||
return;
|
||||
}
|
||||
@@ -56,7 +96,14 @@ export function App() {
|
||||
cancelled = true;
|
||||
clearInterval(timer);
|
||||
};
|
||||
}, [state.kind]);
|
||||
}, [state.kind, statsShown]);
|
||||
|
||||
// The notice of a source switch stays briefly, then goes.
|
||||
useEffect(() => {
|
||||
if (!switched) return;
|
||||
const timer = setTimeout(() => setSwitched(null), SWITCH_NOTICE_MS);
|
||||
return () => clearTimeout(timer);
|
||||
}, [switched]);
|
||||
|
||||
useEffect(() => {
|
||||
const onChange = () => setIsFullscreen(Boolean(document.fullscreenElement));
|
||||
@@ -74,66 +121,190 @@ export function App() {
|
||||
}
|
||||
}, []);
|
||||
|
||||
const showStats = useCallback((shown: boolean) => {
|
||||
saveStatsShown(shown);
|
||||
setStatsShown(shown);
|
||||
}, []);
|
||||
|
||||
const rename = useCallback((name: string) => sessionRef.current?.rename(name), []);
|
||||
|
||||
const rotate = useCallback(() => {
|
||||
setRotation((current) => {
|
||||
const next = nextRotation(current);
|
||||
saveRotation(next);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const toggleMirror = useCallback(() => {
|
||||
setMirror((current) => {
|
||||
saveMirror(!current);
|
||||
return !current;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const togglePinned = useCallback(() => {
|
||||
setPinned((current) => {
|
||||
savePinned(!current);
|
||||
return !current;
|
||||
});
|
||||
}, []);
|
||||
|
||||
// Restarts a series of attempts on the existing session, without reloading
|
||||
// the page: the requested quality and the wake listeners are kept. A
|
||||
// session stopped for good is replaced by a new one.
|
||||
const retry = useCallback(() => {
|
||||
setState({ kind: 'connecting', attempt: 0 });
|
||||
setStats(null);
|
||||
if (sessionRef.current?.retry()) return;
|
||||
setState({ kind: 'connecting', attempt: 0 });
|
||||
setAttemptKey((key) => key + 1);
|
||||
}, []);
|
||||
|
||||
if (!location.ok) {
|
||||
return (
|
||||
<div className='app app-centered'>
|
||||
<div className='panel' role='alert'>
|
||||
<h1>{strings.appName}</h1>
|
||||
<p>{location.reason === 'missing_token' ? strings.missingToken : strings.missingUrl}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
const untrusted = state.kind === 'failed' && state.code === 'not_trusted';
|
||||
if (!location.ok && (!byKey || untrusted)) {
|
||||
// Without a session in the address, offer the short code (#19). The bare
|
||||
// home page is not an error: it is the way in without a camera.
|
||||
const notice = untrusted
|
||||
? t('errors.not_trusted')
|
||||
: {
|
||||
missing_room: null,
|
||||
missing_token: t('missingToken'),
|
||||
malformed: t('missingUrl'),
|
||||
newer_link: t('newerLink'),
|
||||
}[location.reason];
|
||||
return <Pairing notice={notice} />;
|
||||
}
|
||||
|
||||
const live = state.kind === 'streaming';
|
||||
// Décision #65: HTTP assumé sur le LAN. Le spectateur doit savoir ce qui est
|
||||
// chiffré (le média) et ce qui ne l'est pas (la page et le signalement).
|
||||
// Decision #65: HTTP on the LAN is assumed. The viewer must know what is
|
||||
// encrypted (the media) and what is not (the page and signalling).
|
||||
const insecure =
|
||||
window.location.protocol === 'http:' &&
|
||||
window.location.hostname !== 'localhost' &&
|
||||
window.location.hostname !== '127.0.0.1';
|
||||
|
||||
const compact = isCompact(isFullscreen, pinned);
|
||||
const visible = barsVisible({ compact, live, active, held });
|
||||
// The bars stay shown while the pointer or the focus is on them: a button
|
||||
// about to be touched must not disappear.
|
||||
const hold = {
|
||||
onPointerEnter: () => setHeld(true),
|
||||
onPointerLeave: () => setHeld(false),
|
||||
onFocus: () => setHeld(true),
|
||||
onBlur: () => setHeld(false),
|
||||
};
|
||||
const classes = [
|
||||
'app',
|
||||
isFullscreen ? 'app-fullscreen' : '',
|
||||
compact ? 'app-compact' : '',
|
||||
visible ? '' : 'app-hidden',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' ');
|
||||
|
||||
return (
|
||||
<div className={`app ${isFullscreen ? 'app-fullscreen' : ''}`} ref={containerRef}>
|
||||
<header className='topbar'>
|
||||
<span className='brand'>{strings.appName}</span>
|
||||
<div className={classes} ref={containerRef}>
|
||||
<header className='topbar' {...hold}>
|
||||
<span className='brand'>{t('appName')}</span>
|
||||
<StatusBadge state={state} />
|
||||
{insecure && (
|
||||
<span className='badge badge-warn' title={strings.insecureHint}>
|
||||
{strings.insecureBadge}
|
||||
<span className='badge badge-warn' title={t('insecureHint')}>
|
||||
{t('insecureBadge')}
|
||||
</span>
|
||||
)}
|
||||
<span className='spacer' />
|
||||
{live && (
|
||||
<button
|
||||
type='button'
|
||||
className='button button-ghost'
|
||||
onClick={rotate}
|
||||
aria-label={t('rotate', { degrees: rotation })}
|
||||
title={t('rotate', { degrees: rotation })}
|
||||
>
|
||||
↻
|
||||
</button>
|
||||
)}
|
||||
{live && (
|
||||
<button
|
||||
type='button'
|
||||
className='button button-ghost'
|
||||
onClick={toggleMirror}
|
||||
aria-pressed={mirror}
|
||||
aria-label={t('mirror')}
|
||||
title={t('mirror')}
|
||||
>
|
||||
⇋
|
||||
</button>
|
||||
)}
|
||||
{live && !isFullscreen && (
|
||||
<button
|
||||
type='button'
|
||||
className='button button-ghost'
|
||||
onClick={togglePinned}
|
||||
aria-pressed={pinned}
|
||||
aria-label={t(pinned ? 'unpin' : 'pin')}
|
||||
title={t(pinned ? 'unpin' : 'pin')}
|
||||
>
|
||||
{pinned ? '▣' : '▢'}
|
||||
</button>
|
||||
)}
|
||||
{live && (
|
||||
<button
|
||||
type='button'
|
||||
className='button button-ghost'
|
||||
onClick={toggleFullscreen}
|
||||
aria-label={isFullscreen ? strings.exitFullscreen : strings.fullscreen}
|
||||
title={isFullscreen ? strings.exitFullscreen : strings.fullscreen}
|
||||
aria-label={isFullscreen ? t('exitFullscreen') : t('fullscreen')}
|
||||
title={isFullscreen ? t('exitFullscreen') : t('fullscreen')}
|
||||
>
|
||||
{isFullscreen ? '⤡' : '⤢'}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type='button'
|
||||
className='button button-ghost'
|
||||
onClick={() => setSettingsOpen(true)}
|
||||
aria-haspopup='dialog'
|
||||
aria-label={t('settings')}
|
||||
title={t('settings')}
|
||||
>
|
||||
⚙
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<main className='content'>
|
||||
<VideoStage
|
||||
stream={stream}
|
||||
live={live}
|
||||
label={live ? strings.streaming : strings.negotiating}
|
||||
label={live ? t('streaming') : t('negotiating')}
|
||||
rotation={rotation}
|
||||
mirror={mirror}
|
||||
/>
|
||||
{switched && (
|
||||
<div className='switch-notice' role='status'>
|
||||
{t('sourceChanged', {
|
||||
kind: t(`sourceKinds.${switched.kind}`),
|
||||
width: switched.width,
|
||||
height: switched.height,
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
{state.kind === 'failed' && <ErrorPanel state={state} onRetry={retry} />}
|
||||
</main>
|
||||
|
||||
<footer className='footer'>
|
||||
<StatsBar stats={stats} />
|
||||
</footer>
|
||||
{statsShown && stats && (
|
||||
<footer className='footer' {...hold}>
|
||||
<StatsBar stats={stats} />
|
||||
</footer>
|
||||
)}
|
||||
{settingsOpen && (
|
||||
<SettingsPanel
|
||||
onClose={() => setSettingsOpen(false)}
|
||||
onRename={rename}
|
||||
stats={{ shown: statsShown, onChange: showStats }}
|
||||
fingerprint={location.ok ? location.value.fingerprint : null}
|
||||
trusted={isTrusted()}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { useId, useState } from 'react';
|
||||
|
||||
import { useI18n } from '../i18n';
|
||||
import { NAME_MAX, readName, saveName, suggestedName } from '../lib/deviceName';
|
||||
|
||||
type Props = {
|
||||
/** The name changed: the session tells the host. */
|
||||
onRename: (name: string) => void;
|
||||
/** Show the label instead of keeping it for screen readers. */
|
||||
label?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* The name of this device, as the host sees it (#36). Kept by the browser;
|
||||
* empty, it goes back to the suggestion. React shows it as text: markup typed
|
||||
* here stays visible as typed.
|
||||
*/
|
||||
export function DeviceName({ onRename, label = false }: Props) {
|
||||
const { t } = useI18n();
|
||||
const id = useId();
|
||||
const suggestion = suggestedName(navigator.userAgent);
|
||||
const [name, setName] = useState(() => readName() ?? '');
|
||||
|
||||
const commit = () => {
|
||||
saveName(name);
|
||||
const kept = readName() ?? '';
|
||||
setName(kept);
|
||||
onRename(kept || suggestion);
|
||||
};
|
||||
|
||||
return (
|
||||
<span className='device-name'>
|
||||
<label htmlFor={id} className={label ? undefined : 'visually-hidden'}>
|
||||
{t('deviceName')}
|
||||
</label>
|
||||
<input
|
||||
id={id}
|
||||
value={name}
|
||||
placeholder={suggestion}
|
||||
maxLength={NAME_MAX}
|
||||
title={t('deviceNameHelp')}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
onBlur={commit}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') e.currentTarget.blur();
|
||||
}}
|
||||
/>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { strings } from '../strings';
|
||||
import type { ViewerState } from '../lib/session';
|
||||
import { useI18n } from '../i18n';
|
||||
import { isRetryable, messageFor, type ViewerState } from '../lib/session';
|
||||
|
||||
type Props = {
|
||||
state: Extract<ViewerState, { kind: 'failed' }>;
|
||||
@@ -7,19 +7,20 @@ type Props = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Panneau d'erreur. Il dit ce qui s'est passé, si réessayer peut aider, et ne
|
||||
* propose le bouton que dans ce cas: un bouton qui échoue toujours est pire
|
||||
* qu'une explication.
|
||||
* Error panel. It says what happened, whether retrying can help, and offers
|
||||
* the button only in that case: a button that always fails is worse than an
|
||||
* explanation.
|
||||
*/
|
||||
export function ErrorPanel({ state, onRetry }: Props) {
|
||||
const retryable = state.code === 'network' || state.code === 'internal';
|
||||
const { t } = useI18n();
|
||||
const retryable = isRetryable(state.code);
|
||||
return (
|
||||
<div className='panel' role='alert'>
|
||||
<h2>{strings.failedTitle}</h2>
|
||||
<p>{state.message}</p>
|
||||
<h2>{t('failedTitle')}</h2>
|
||||
<p>{messageFor(state.code, t)}</p>
|
||||
{retryable && (
|
||||
<button type='button' className='button' onClick={onRetry}>
|
||||
{strings.retry}
|
||||
{t('retry')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
import { type FormEvent, useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useI18n } from '../i18n';
|
||||
import { exchangeCode, qrDetector } from '../lib/pairing';
|
||||
import { isCompleteCode, normalizeCode, sessionFromScan } from '../lib/room';
|
||||
import { SettingsPanel } from './SettingsPanel';
|
||||
|
||||
/** A sample code, in the format the host shows: not a sentence. */
|
||||
const SAMPLE_CODE = 'K7M 4PQ';
|
||||
|
||||
type Props = {
|
||||
/** Why we land here without a session, to say before the form. */
|
||||
notice: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Home page without a session (#19): type the short code shown by the host,
|
||||
* or scan its QR code when the browser can.
|
||||
*/
|
||||
export function Pairing({ notice }: Props) {
|
||||
const { t } = useI18n();
|
||||
const [code, setCode] = useState('');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [scanning, setScanning] = useState(false);
|
||||
const [canScan] = useState(() => qrDetector() !== null);
|
||||
const [settingsOpen, setSettingsOpen] = useState(false);
|
||||
|
||||
const submit = useCallback(
|
||||
async (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
const normalized = normalizeCode(code);
|
||||
if (!isCompleteCode(normalized)) {
|
||||
setError(t('codeIncomplete'));
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const outcome = await exchangeCode(normalized);
|
||||
setBusy(false);
|
||||
switch (outcome.kind) {
|
||||
case 'accepted':
|
||||
window.location.assign(outcome.path);
|
||||
return;
|
||||
case 'unknown':
|
||||
setError(t('codeUnknown'));
|
||||
return;
|
||||
case 'expired':
|
||||
setError(t('codeExpired'));
|
||||
return;
|
||||
case 'too_many_attempts':
|
||||
setError(t('codeTooMany', { seconds: outcome.retryAfterS }));
|
||||
return;
|
||||
case 'network':
|
||||
setError(t('codeNetwork'));
|
||||
}
|
||||
},
|
||||
[code, t],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className='app app-centered'>
|
||||
<div className='panel pairing'>
|
||||
<div className='pairing-header'>
|
||||
<h1>{t('appName')}</h1>
|
||||
<button
|
||||
type='button'
|
||||
className='button button-ghost'
|
||||
onClick={() => setSettingsOpen(true)}
|
||||
aria-haspopup='dialog'
|
||||
aria-label={t('settings')}
|
||||
title={t('settings')}
|
||||
>
|
||||
⚙
|
||||
</button>
|
||||
</div>
|
||||
{notice && <p role='alert'>{notice}</p>}
|
||||
<form onSubmit={submit} className='pairing-form'>
|
||||
<label htmlFor='code'>{t('codeLabel')}</label>
|
||||
<input
|
||||
id='code'
|
||||
className='pairing-code'
|
||||
value={code}
|
||||
onChange={(event) => setCode(event.target.value.toUpperCase())}
|
||||
autoComplete='off'
|
||||
autoCapitalize='characters'
|
||||
spellCheck={false}
|
||||
maxLength={8}
|
||||
placeholder={SAMPLE_CODE}
|
||||
aria-describedby={error ? 'code-error' : undefined}
|
||||
aria-invalid={error !== null}
|
||||
/>
|
||||
<button type='submit' className='button' disabled={busy}>
|
||||
{t('codeSubmit')}
|
||||
</button>
|
||||
</form>
|
||||
{error && (
|
||||
<p id='code-error' className='pairing-error' role='alert'>
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<p className='pairing-hint'>{t('codeHint')}</p>
|
||||
{canScan && !scanning && (
|
||||
<button type='button' className='button button-ghost' onClick={() => setScanning(true)}>
|
||||
{t('scanButton')}
|
||||
</button>
|
||||
)}
|
||||
{scanning && <Scanner onClose={() => setScanning(false)} onError={setError} />}
|
||||
</div>
|
||||
{/* The name is kept for the first connection; no session to tell yet. */}
|
||||
{settingsOpen && <SettingsPanel onClose={() => setSettingsOpen(false)} onRename={() => {}} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Rear camera, reading the QR code four times per second. */
|
||||
function Scanner({ onClose, onError }: { onClose: () => void; onError: (m: string) => void }) {
|
||||
const { t } = useI18n();
|
||||
const videoRef = useRef<HTMLVideoElement | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const detector = qrDetector();
|
||||
if (!detector) return;
|
||||
let stream: MediaStream | null = null;
|
||||
let timer: ReturnType<typeof setInterval> | undefined;
|
||||
let stopped = false;
|
||||
void navigator.mediaDevices
|
||||
.getUserMedia({ video: { facingMode: 'environment' }, audio: false })
|
||||
.then((media) => {
|
||||
if (stopped) {
|
||||
for (const track of media.getTracks()) track.stop();
|
||||
return;
|
||||
}
|
||||
stream = media;
|
||||
const video = videoRef.current;
|
||||
if (!video) return;
|
||||
video.srcObject = media;
|
||||
void video.play().catch(() => undefined);
|
||||
timer = setInterval(() => {
|
||||
void detector
|
||||
.detect(video)
|
||||
.then((codes) => {
|
||||
for (const found of codes) {
|
||||
const target = sessionFromScan(found.rawValue);
|
||||
if (target) {
|
||||
window.location.assign(target);
|
||||
return;
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}, 250);
|
||||
})
|
||||
.catch(() => {
|
||||
onError(t('scanDenied'));
|
||||
onClose();
|
||||
});
|
||||
return () => {
|
||||
stopped = true;
|
||||
clearInterval(timer);
|
||||
for (const track of stream?.getTracks() ?? []) track.stop();
|
||||
};
|
||||
}, [onClose, onError, t]);
|
||||
|
||||
return (
|
||||
<div className='scanner'>
|
||||
<video
|
||||
ref={videoRef}
|
||||
className='scanner-video'
|
||||
playsInline
|
||||
muted
|
||||
aria-label={t('scanButton')}
|
||||
/>
|
||||
<button type='button' className='button button-ghost' onClick={onClose}>
|
||||
{t('scanClose')}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import { useEffect, useId, useRef, useState } from 'react';
|
||||
|
||||
import { browserLanguage, useI18n } from '../i18n';
|
||||
import { applyTheme, readTheme, saveTheme, THEMES, type Theme } from '../lib/theme';
|
||||
import { DeviceName } from './DeviceName';
|
||||
|
||||
/** Value of the language select that follows the browser. */
|
||||
const BROWSER = '';
|
||||
|
||||
type Props = {
|
||||
onClose: () => void;
|
||||
/** The name changed: the session tells the host. */
|
||||
onRename: (name: string) => void;
|
||||
/** The statistics strip, when there is a stream to measure. */
|
||||
stats?: { shown: boolean; onChange: (shown: boolean) => void };
|
||||
/** Certificate fingerprint from the link, to compare with the host's. */
|
||||
fingerprint?: string | null;
|
||||
/** The host trusts this device (#34). */
|
||||
trusted?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* What this device can set (#92), behind the gear of the top bar: the page
|
||||
* itself only shows the shared screen. Every choice is kept by the browser.
|
||||
*/
|
||||
export function SettingsPanel({ onClose, onRename, stats, fingerprint, trusted }: Props) {
|
||||
const { t, languages, chosen, setLanguage } = useI18n();
|
||||
const id = useId();
|
||||
const [theme, setTheme] = useState<Theme>(() => readTheme());
|
||||
const dialog = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
// The focus enters the panel, and goes back where it was when it closes.
|
||||
useEffect(() => {
|
||||
const previous = document.activeElement as HTMLElement | null;
|
||||
dialog.current?.querySelector<HTMLElement>('input, select, button')?.focus();
|
||||
return () => previous?.focus?.();
|
||||
}, []);
|
||||
|
||||
const changeTheme = (next: Theme) => {
|
||||
applyTheme(next);
|
||||
saveTheme(next);
|
||||
setTheme(next);
|
||||
};
|
||||
const browser = languages.find((l) => l.code === browserLanguage(languages));
|
||||
|
||||
return (
|
||||
<div
|
||||
className='overlay'
|
||||
onPointerDown={(e) => {
|
||||
if (e.target === e.currentTarget) onClose();
|
||||
}}
|
||||
>
|
||||
<div
|
||||
ref={dialog}
|
||||
className='settings-panel'
|
||||
role='dialog'
|
||||
aria-modal='true'
|
||||
aria-labelledby={`${id}-title`}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Escape') onClose();
|
||||
}}
|
||||
>
|
||||
<div className='settings-header'>
|
||||
<h2 id={`${id}-title`}>{t('settings')}</h2>
|
||||
<button type='button' className='button button-ghost' onClick={onClose}>
|
||||
{t('close')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className='settings-field'>
|
||||
<DeviceName onRename={onRename} label />
|
||||
<span className='settings-help'>{t('deviceNameHelp')}</span>
|
||||
</div>
|
||||
|
||||
{languages.length > 1 && (
|
||||
<div className='settings-field'>
|
||||
<label htmlFor={`${id}-language`}>{t('language')}</label>
|
||||
<select
|
||||
id={`${id}-language`}
|
||||
value={chosen ?? BROWSER}
|
||||
onChange={(e) => setLanguage(e.target.value === BROWSER ? null : e.target.value)}
|
||||
>
|
||||
<option value={BROWSER}>{t('languageBrowser', { name: browser?.name ?? '' })}</option>
|
||||
{/* Each language in its own: whoever cannot read the current one finds theirs. */}
|
||||
{languages.map((l) => (
|
||||
<option key={l.code} value={l.code} lang={l.code}>
|
||||
{l.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className='settings-field'>
|
||||
<label htmlFor={`${id}-theme`}>{t('theme')}</label>
|
||||
<select
|
||||
id={`${id}-theme`}
|
||||
value={theme}
|
||||
onChange={(e) => changeTheme(e.target.value as Theme)}
|
||||
>
|
||||
{THEMES.map((th) => (
|
||||
<option key={th} value={th}>
|
||||
{t(`themes.${th}`)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{stats && (
|
||||
<label className='settings-check'>
|
||||
<input
|
||||
type='checkbox'
|
||||
checked={stats.shown}
|
||||
onChange={(e) => stats.onChange(e.target.checked)}
|
||||
/>
|
||||
{t('showStats')}
|
||||
</label>
|
||||
)}
|
||||
|
||||
{(fingerprint || trusted) && (
|
||||
<dl className='settings-info'>
|
||||
{trusted && (
|
||||
<div>
|
||||
<dt>{t('trustedBadge')}</dt>
|
||||
<dd>{t('trustedHint')}</dd>
|
||||
</div>
|
||||
)}
|
||||
{fingerprint && (
|
||||
<div>
|
||||
<dt>{t('fingerprint')}</dt>
|
||||
<dd className='mono'>{fingerprint}</dd>
|
||||
</div>
|
||||
)}
|
||||
</dl>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,18 +1,19 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
|
||||
import { useI18n } from '../i18n';
|
||||
import type { VideoStats } from '../lib/session';
|
||||
import { strings } from '../strings';
|
||||
|
||||
type Props = {
|
||||
stats: VideoStats | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Bandeau de statistiques. Le débit n'est pas fourni par `getStats` en une
|
||||
* valeur: on le calcule entre deux relevés, ce qui évite d'afficher un chiffre
|
||||
* qui ne veut rien dire sur la première seconde.
|
||||
* Statistics strip. `getStats` does not give the bitrate as a single value:
|
||||
* it is computed between two samples, which avoids showing a meaningless
|
||||
* figure during the first second.
|
||||
*/
|
||||
export function StatsBar({ stats }: Props) {
|
||||
const { t, language } = useI18n();
|
||||
const previous = useRef<{ bytes: number; at: number } | null>(null);
|
||||
const [kbps, setKbps] = useState<number | null>(null);
|
||||
|
||||
@@ -37,23 +38,29 @@ export function StatsBar({ stats }: Props) {
|
||||
return (
|
||||
<dl className='stats'>
|
||||
<div>
|
||||
<dt>{strings.statsResolution}</dt>
|
||||
<dt>{t('statsResolution')}</dt>
|
||||
<dd>
|
||||
{stats.width}×{stats.height}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{strings.statsRate}</dt>
|
||||
<dt>{t('statsRate')}</dt>
|
||||
<dd>{stats.fps}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{strings.statsFrames}</dt>
|
||||
<dt>{t('statsFrames')}</dt>
|
||||
<dd>{formatCount(stats.frames)}</dd>
|
||||
</div>
|
||||
{kbps !== null && (
|
||||
<div>
|
||||
<dt>{strings.statsBitrate}</dt>
|
||||
<dd>{kbps >= 1000 ? `${(kbps / 1000).toFixed(1)} Mbit/s` : `${kbps} kbit/s`}</dd>
|
||||
<dt>{t('statsBitrate')}</dt>
|
||||
<dd>
|
||||
{kbps >= 1000
|
||||
? t('mbps', {
|
||||
value: (kbps / 1000).toLocaleString(language, { maximumFractionDigits: 1 }),
|
||||
})
|
||||
: t('kbps', { value: kbps })}
|
||||
</dd>
|
||||
</div>
|
||||
)}
|
||||
</dl>
|
||||
|
||||
@@ -1,29 +1,31 @@
|
||||
import { useI18n } from '../i18n';
|
||||
import type { Translate } from '../lib/i18n';
|
||||
import type { ViewerState } from '../lib/session';
|
||||
import { strings } from '../strings';
|
||||
|
||||
/** Traduit l'état de session en un libellé court et une couleur. */
|
||||
export function describe(state: ViewerState): { text: string; tone: string } {
|
||||
/** Turns the session state into a short label and a colour. */
|
||||
export function describe(state: ViewerState, t: Translate): { text: string; tone: string } {
|
||||
switch (state.kind) {
|
||||
case 'connecting':
|
||||
return { text: strings.connecting, tone: 'pending' };
|
||||
return { text: t('connecting'), tone: 'pending' };
|
||||
case 'negotiating':
|
||||
return { text: strings.negotiating, tone: 'pending' };
|
||||
return { text: t('negotiating'), tone: 'pending' };
|
||||
case 'streaming':
|
||||
return { text: strings.streaming, tone: 'live' };
|
||||
return { text: t('streaming'), tone: 'live' };
|
||||
case 'reconnecting':
|
||||
return {
|
||||
text: strings.reconnecting(Math.ceil(state.delayMs / 1000)),
|
||||
text: t('reconnecting', { seconds: Math.ceil(state.delayMs / 1000) }),
|
||||
tone: 'pending',
|
||||
};
|
||||
case 'ended':
|
||||
return { text: strings.ended, tone: 'neutral' };
|
||||
return { text: t('ended'), tone: 'neutral' };
|
||||
case 'failed':
|
||||
return { text: strings.failedTitle, tone: 'error' };
|
||||
return { text: t('failedTitle'), tone: 'error' };
|
||||
}
|
||||
}
|
||||
|
||||
export function StatusBadge({ state }: { state: ViewerState }) {
|
||||
const { text, tone } = describe(state);
|
||||
const { t } = useI18n();
|
||||
const { text, tone } = describe(state, t);
|
||||
return (
|
||||
<span className={`badge badge-${tone}`} role='status' aria-live='polite'>
|
||||
{tone === 'live' && <span className='badge-dot' aria-hidden='true' />}
|
||||
|
||||
@@ -1,17 +1,25 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
|
||||
import { probeRequested, startProbe } from '../lib/perfProbe';
|
||||
import { type Rotation, rotatedBox } from '../lib/rotation';
|
||||
|
||||
type Props = {
|
||||
stream: MediaStream | null;
|
||||
live: boolean;
|
||||
label: string;
|
||||
rotation: Rotation;
|
||||
mirror: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* La scène vidéo. La balise reste montée même sans flux: la démonter pour la
|
||||
* remonter à chaque négociation ferait sauter le plein écran sur iOS.
|
||||
* The video stage. The element stays mounted even without a stream:
|
||||
* unmounting and remounting it at every negotiation would drop full screen on
|
||||
* iOS. A rotation changes its box and its transform, never the stream (#30).
|
||||
*/
|
||||
export function VideoStage({ stream, live, label }: Props) {
|
||||
export function VideoStage({ stream, live, label, rotation, mirror }: Props) {
|
||||
const videoRef = useRef<HTMLVideoElement | null>(null);
|
||||
const stageRef = useRef<HTMLDivElement | null>(null);
|
||||
const [size, setSize] = useState<{ width: number; height: number } | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const video = videoRef.current;
|
||||
@@ -20,15 +28,64 @@ export function VideoStage({ stream, live, label }: Props) {
|
||||
video.srcObject = stream;
|
||||
}
|
||||
if (stream) {
|
||||
// `play()` peut être refusé si l'utilisateur n'a pas interagi; la
|
||||
// vidéo est muette, donc en pratique il passe. On ignore l'échec.
|
||||
// `play()` may be refused if the user has not interacted; the video
|
||||
// is muted, so in practice it goes through. The failure is ignored.
|
||||
void video.play().catch(() => undefined);
|
||||
}
|
||||
}, [stream]);
|
||||
|
||||
// Latency probe for the bench (#86), only when the URL asks for it.
|
||||
useEffect(() => {
|
||||
const video = videoRef.current;
|
||||
if (!video || !probeRequested(window.location.search)) return;
|
||||
return startProbe(video);
|
||||
}, []);
|
||||
|
||||
// The turned box depends on the stage size: full screen, switching to
|
||||
// portrait, the virtual keyboard all change it.
|
||||
useEffect(() => {
|
||||
const stage = stageRef.current;
|
||||
if (!stage || typeof ResizeObserver === 'undefined') return;
|
||||
const observer = new ResizeObserver(([entry]) => {
|
||||
if (!entry) return;
|
||||
const { width, height } = entry.contentRect;
|
||||
setSize({ width, height });
|
||||
});
|
||||
observer.observe(stage);
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
|
||||
// Without rotation, the element keeps its box: the mirror alone flips it.
|
||||
const style =
|
||||
rotation === 0
|
||||
? mirror
|
||||
? { transform: 'scaleX(-1)' }
|
||||
: undefined
|
||||
: size
|
||||
? (() => {
|
||||
const box = rotatedBox(size.width, size.height, rotation, mirror);
|
||||
return {
|
||||
inset: 'auto',
|
||||
left: '50%',
|
||||
top: '50%',
|
||||
width: `${box.width}px`,
|
||||
height: `${box.height}px`,
|
||||
transform: box.transform,
|
||||
};
|
||||
})()
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
<div className='stage'>
|
||||
<video ref={videoRef} className='stage-video' playsInline muted autoPlay aria-label={label} />
|
||||
<div className='stage' ref={stageRef}>
|
||||
<video
|
||||
ref={videoRef}
|
||||
className='stage-video'
|
||||
style={style}
|
||||
playsInline
|
||||
muted
|
||||
autoPlay
|
||||
aria-label={label}
|
||||
/>
|
||||
{!live && (
|
||||
<div className='stage-veil' role='status' aria-live='polite'>
|
||||
<span className='stage-dot' aria-hidden='true' />
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
import { createContext, type ReactNode, useCallback, useContext, useMemo, useState } from 'react';
|
||||
|
||||
import {
|
||||
type AvailableLanguage,
|
||||
type Catalog,
|
||||
createTranslator,
|
||||
FALLBACK_LANGUAGE,
|
||||
pickLanguage,
|
||||
type Translate,
|
||||
} from './lib/i18n';
|
||||
import { browserStorage, readMigrated } from './lib/storage';
|
||||
|
||||
/**
|
||||
* Viewer texts (#21). The catalog comes from the host (`/locales/`): adding a
|
||||
* language to the host makes it available here, without rebuilding the
|
||||
* viewer. The choice is kept by the device alone, like the theme.
|
||||
*/
|
||||
|
||||
const KEY = 'rustscreen.language';
|
||||
/** Key before #83. */
|
||||
const LEGACY_KEY = 'rustscreen.langue';
|
||||
|
||||
type Context = {
|
||||
t: Translate;
|
||||
language: string;
|
||||
languages: AvailableLanguage[];
|
||||
/** The language this device chose, `null` when it follows the browser. */
|
||||
chosen: string | null;
|
||||
/** A language served by the host, or `null` to follow the browser (#92). */
|
||||
setLanguage: (code: string | null) => void;
|
||||
};
|
||||
|
||||
const I18n = createContext<Context | null>(null);
|
||||
|
||||
export function useI18n(): Context {
|
||||
const context = useContext(I18n);
|
||||
if (!context) throw new Error('useI18n outside of I18nProvider');
|
||||
return context;
|
||||
}
|
||||
|
||||
type Loaded = { language: string; catalogs: Catalog[] };
|
||||
|
||||
export function I18nProvider({
|
||||
initial,
|
||||
languages,
|
||||
children,
|
||||
}: {
|
||||
initial: Loaded;
|
||||
languages: AvailableLanguage[];
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const [loaded, setLoaded] = useState(initial);
|
||||
const [chosen, setChosen] = useState(() => chosenLanguage(languages));
|
||||
|
||||
const setLanguage = useCallback(
|
||||
(choice: string | null) => {
|
||||
saveLanguage(choice);
|
||||
setChosen(choice);
|
||||
const code = choice ?? browserLanguage(languages);
|
||||
// The change takes effect on the next render: no reload, the session
|
||||
// and the stream go on.
|
||||
void loadCatalogs(code).then((catalogs) => {
|
||||
if (catalogs.length === 0) return;
|
||||
document.documentElement.lang = code;
|
||||
setLoaded({ language: code, catalogs });
|
||||
});
|
||||
},
|
||||
[languages],
|
||||
);
|
||||
|
||||
const value = useMemo(
|
||||
() => ({
|
||||
t: createTranslator(loaded.language, 'viewer', loaded.catalogs),
|
||||
language: loaded.language,
|
||||
languages,
|
||||
chosen,
|
||||
setLanguage,
|
||||
}),
|
||||
[loaded, languages, chosen, setLanguage],
|
||||
);
|
||||
return <I18n.Provider value={value}>{children}</I18n.Provider>;
|
||||
}
|
||||
|
||||
/** The languages the host serves, empty if it does not answer. */
|
||||
export async function loadLanguages(): Promise<AvailableLanguage[]> {
|
||||
try {
|
||||
const response = await fetch('/locales/index.json');
|
||||
if (!response.ok) return [];
|
||||
return (await response.json()) as AvailableLanguage[];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/** The wanted language then English, whichever of the two exist. */
|
||||
export async function loadCatalogs(code: string): Promise<Catalog[]> {
|
||||
const codes = code === FALLBACK_LANGUAGE ? [code] : [code, FALLBACK_LANGUAGE];
|
||||
const catalogs = await Promise.all(
|
||||
codes.map(async (c) => {
|
||||
try {
|
||||
const response = await fetch(`/locales/${encodeURIComponent(c)}.json`);
|
||||
return response.ok ? ((await response.json()) as Catalog) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}),
|
||||
);
|
||||
return catalogs.filter((c): c is Catalog => c !== null);
|
||||
}
|
||||
|
||||
/** The choice kept by the device, otherwise the browser language. */
|
||||
export function initialLanguage(available: AvailableLanguage[]): string {
|
||||
return chosenLanguage(available) ?? browserLanguage(available);
|
||||
}
|
||||
|
||||
/** The language of the browser, among those the host serves. */
|
||||
export function browserLanguage(available: AvailableLanguage[]): string {
|
||||
return pickLanguage(
|
||||
navigator.languages ?? [navigator.language],
|
||||
available.map((l) => l.code),
|
||||
);
|
||||
}
|
||||
|
||||
/** The language this device chose, if the host still serves it. */
|
||||
function chosenLanguage(available: AvailableLanguage[]): string | null {
|
||||
const saved = readLanguage();
|
||||
return saved && available.some((l) => l.code === saved) ? saved : null;
|
||||
}
|
||||
|
||||
function readLanguage(): string | null {
|
||||
try {
|
||||
const storage = browserStorage();
|
||||
return storage ? readMigrated(storage, KEY, LEGACY_KEY) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function saveLanguage(code: string | null): void {
|
||||
try {
|
||||
if (code === null) {
|
||||
window.localStorage.removeItem(KEY);
|
||||
window.localStorage.removeItem(LEGACY_KEY);
|
||||
} else {
|
||||
window.localStorage.setItem(KEY, code);
|
||||
}
|
||||
} catch {
|
||||
// Private browsing: the choice holds for the page only.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { ViewerSession, type ViewerState } from './session';
|
||||
import { fromSecret, isTrusted, rememberTrust } from './trust';
|
||||
|
||||
/** WebSocket that opens, records what is sent, and lets the test answer. */
|
||||
class ScriptedWebSocket {
|
||||
static readonly OPEN = 1;
|
||||
static readonly CLOSING = 2;
|
||||
static readonly CLOSED = 3;
|
||||
static last: ScriptedWebSocket | null = null;
|
||||
|
||||
readyState = 0;
|
||||
sent: Array<Record<string, unknown>> = [];
|
||||
private listeners = new Map<string, Array<(event: unknown) => void>>();
|
||||
|
||||
constructor(public readonly url: string) {
|
||||
ScriptedWebSocket.last = this;
|
||||
queueMicrotask(() => {
|
||||
this.readyState = ScriptedWebSocket.OPEN;
|
||||
this.emit('open', {});
|
||||
});
|
||||
}
|
||||
|
||||
addEventListener(type: string, listener: (event: unknown) => void): void {
|
||||
const list = this.listeners.get(type) ?? [];
|
||||
list.push(listener);
|
||||
this.listeners.set(type, list);
|
||||
}
|
||||
|
||||
send(data: string): void {
|
||||
this.sent.push(JSON.parse(data));
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.readyState = ScriptedWebSocket.CLOSED;
|
||||
}
|
||||
|
||||
answer(message: Record<string, unknown>): void {
|
||||
this.emit('message', { data: JSON.stringify(message) });
|
||||
}
|
||||
|
||||
private emit(type: string, event: unknown): void {
|
||||
for (const listener of this.listeners.get(type) ?? []) listener(event);
|
||||
}
|
||||
}
|
||||
|
||||
class StubPeerConnection {
|
||||
close(): void {}
|
||||
}
|
||||
|
||||
const SECRET = '9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60';
|
||||
const NONCE = '000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f';
|
||||
|
||||
function memoryStorage() {
|
||||
const map = new Map<string, string>();
|
||||
return {
|
||||
getItem: (k: string) => map.get(k) ?? null,
|
||||
setItem: (k: string, v: string) => void map.set(k, v),
|
||||
removeItem: (k: string) => void map.delete(k),
|
||||
};
|
||||
}
|
||||
|
||||
describe('coming back by key (#34)', () => {
|
||||
let storage: ReturnType<typeof memoryStorage>;
|
||||
|
||||
beforeEach(() => {
|
||||
storage = memoryStorage();
|
||||
vi.stubGlobal('WebSocket', ScriptedWebSocket);
|
||||
vi.stubGlobal('RTCPeerConnection', StubPeerConnection);
|
||||
vi.stubGlobal('window', { localStorage: storage });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
function session(states: ViewerState[]) {
|
||||
return new ViewerSession({
|
||||
room: null,
|
||||
token: null,
|
||||
key: fromSecret(SECRET),
|
||||
wsUrl: 'ws://127.0.0.1:1/ws',
|
||||
watchLifecycle: false,
|
||||
onState: (state) => states.push(state),
|
||||
onStream: () => undefined,
|
||||
});
|
||||
}
|
||||
|
||||
it('announces its public key without a link, then signs the challenge', async () => {
|
||||
const viewer = session([]);
|
||||
viewer.start();
|
||||
await Promise.resolve();
|
||||
const ws = ScriptedWebSocket.last;
|
||||
expect(ws?.sent[0]).toMatchObject({
|
||||
type: 'hello',
|
||||
room: null,
|
||||
token: null,
|
||||
key: fromSecret(SECRET).publicKey,
|
||||
});
|
||||
ws?.answer({ type: 'challenge', nonce: NONCE });
|
||||
await Promise.resolve();
|
||||
expect(ws?.sent[1]).toEqual({ type: 'proof', signature: fromSecret(SECRET).sign(NONCE) });
|
||||
viewer.stop();
|
||||
});
|
||||
|
||||
it('forgets the trust when the host refuses the key', async () => {
|
||||
rememberTrust(true, storage);
|
||||
const states: ViewerState[] = [];
|
||||
const viewer = session(states);
|
||||
viewer.start();
|
||||
await Promise.resolve();
|
||||
ScriptedWebSocket.last?.answer({ type: 'error', code: 'not_trusted', message: '' });
|
||||
await Promise.resolve();
|
||||
expect(isTrusted(storage)).toBe(false);
|
||||
expect(states.at(-1)).toEqual({ kind: 'failed', code: 'not_trusted' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('source switch (#26)', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('WebSocket', ScriptedWebSocket);
|
||||
vi.stubGlobal('RTCPeerConnection', StubPeerConnection);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('reports the new source without leaving the session', async () => {
|
||||
const states: ViewerState[] = [];
|
||||
const switched: unknown[] = [];
|
||||
const viewer = new ViewerSession({
|
||||
room: 'abc234',
|
||||
token: '0123456789abcdef0123456789abcdef',
|
||||
key: null,
|
||||
wsUrl: 'ws://127.0.0.1:1/ws',
|
||||
watchLifecycle: false,
|
||||
onState: (state) => states.push(state),
|
||||
onStream: () => undefined,
|
||||
onSourceChanged: (source) => switched.push(source),
|
||||
});
|
||||
viewer.start();
|
||||
await Promise.resolve();
|
||||
const source = {
|
||||
id: 'x11',
|
||||
kind: 'window',
|
||||
name: '',
|
||||
width: 800,
|
||||
height: 600,
|
||||
available: true,
|
||||
};
|
||||
ScriptedWebSocket.last?.answer({ type: 'source_changed', source });
|
||||
await Promise.resolve();
|
||||
expect(switched).toEqual([source]);
|
||||
expect(states.some((s) => s.kind === 'failed' || s.kind === 'reconnecting')).toBe(false);
|
||||
viewer.stop();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import {
|
||||
barsVisible,
|
||||
isCompact,
|
||||
readPinned,
|
||||
readStatsShown,
|
||||
savePinned,
|
||||
saveStatsShown,
|
||||
} from './controls';
|
||||
|
||||
describe('bars that fade out (#31, #81)', () => {
|
||||
const base = { compact: true, live: true, active: false, held: false };
|
||||
|
||||
it('fade out when live, idle, in compact mode', () => {
|
||||
expect(barsVisible(base)).toBe(false);
|
||||
});
|
||||
|
||||
it('come back on activity, and stay under the pointer or the focus', () => {
|
||||
expect(barsVisible({ ...base, active: true })).toBe(true);
|
||||
expect(barsVisible({ ...base, held: true })).toBe(true);
|
||||
});
|
||||
|
||||
it('stay visible when the session is not live', () => {
|
||||
expect(barsVisible({ ...base, live: false })).toBe(true);
|
||||
});
|
||||
|
||||
it('stay visible when pinned in a window, never in full screen', () => {
|
||||
expect(isCompact(false, true)).toBe(false);
|
||||
expect(isCompact(false, false)).toBe(true);
|
||||
expect(isCompact(true, true)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('pinned controls', () => {
|
||||
function memory(initial: Record<string, string> = {}) {
|
||||
const values = new Map(Object.entries(initial));
|
||||
return {
|
||||
values,
|
||||
getItem: (k: string) => values.get(k) ?? null,
|
||||
setItem: (k: string, v: string) => void values.set(k, v),
|
||||
removeItem: (k: string) => void values.delete(k),
|
||||
};
|
||||
}
|
||||
|
||||
it('are kept by the device', () => {
|
||||
const storage = memory();
|
||||
expect(readPinned(storage)).toBe(false);
|
||||
savePinned(true, storage);
|
||||
expect(readPinned(storage)).toBe(true);
|
||||
});
|
||||
|
||||
it('migrate the choice stored before #83', () => {
|
||||
const storage = memory({ 'rustscreen.controles-epingles': '1' });
|
||||
expect(readPinned(storage)).toBe(true);
|
||||
expect(storage.values.get('rustscreen.pinned-controls')).toBe('1');
|
||||
expect(storage.values.has('rustscreen.controles-epingles')).toBe(false);
|
||||
});
|
||||
|
||||
it('statistics are hidden until asked for, then kept (#92)', () => {
|
||||
const storage = memory();
|
||||
expect(readStatsShown(storage)).toBe(false);
|
||||
saveStatsShown(true, storage);
|
||||
expect(readStatsShown(storage)).toBe(true);
|
||||
expect(readStatsShown(null)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* Viewer bars that fade out (#31 in a window, #81 in full screen).
|
||||
*
|
||||
* After a few seconds without activity, the top bar and the footer disappear
|
||||
* and the picture takes the whole space. A mouse move, a touch or a key brings
|
||||
* them back. They stay visible as long as the session is not live: a dropout
|
||||
* must show without touching the screen.
|
||||
*/
|
||||
import { browserStorage, type KeyValueStore, readMigrated } from './storage';
|
||||
|
||||
/** Delay without activity before hiding the bars. */
|
||||
export const IDLE_DELAY_MS = 3000;
|
||||
|
||||
export type BarsState = {
|
||||
/** Compact mode: full screen, or a window without pinned controls. */
|
||||
compact: boolean;
|
||||
/** The session is live. */
|
||||
live: boolean;
|
||||
/** Activity within the last `IDLE_DELAY_MS`. */
|
||||
active: boolean;
|
||||
/** The pointer is over a bar, or keyboard focus is in one. */
|
||||
held: boolean;
|
||||
};
|
||||
|
||||
export function barsVisible({ compact, live, active, held }: BarsState): boolean {
|
||||
return !compact || !live || active || held;
|
||||
}
|
||||
|
||||
/** Compact mode: always in full screen, by default in a window. */
|
||||
export function isCompact(fullscreen: boolean, pinned: boolean): boolean {
|
||||
return fullscreen || !pinned;
|
||||
}
|
||||
|
||||
const KEY = 'rustscreen.pinned-controls';
|
||||
/** Key before #83. */
|
||||
const LEGACY_KEY = 'rustscreen.controles-epingles';
|
||||
|
||||
export function readPinned(storage: KeyValueStore | null = browserStorage()): boolean {
|
||||
try {
|
||||
return storage !== null && readMigrated(storage, KEY, LEGACY_KEY) === '1';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function savePinned(
|
||||
pinned: boolean,
|
||||
storage: KeyValueStore | null = browserStorage(),
|
||||
): void {
|
||||
try {
|
||||
storage?.setItem(KEY, pinned ? '1' : '0');
|
||||
} catch {
|
||||
// Private browsing: the choice holds for the page only.
|
||||
}
|
||||
}
|
||||
|
||||
/** Show the statistics strip (#92): off by default, the picture comes first. */
|
||||
const STATS_KEY = 'rustscreen.show-stats';
|
||||
|
||||
export function readStatsShown(storage: KeyValueStore | null = browserStorage()): boolean {
|
||||
try {
|
||||
return storage?.getItem(STATS_KEY) === '1';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function saveStatsShown(
|
||||
shown: boolean,
|
||||
storage: KeyValueStore | null = browserStorage(),
|
||||
): void {
|
||||
try {
|
||||
storage?.setItem(STATS_KEY, shown ? '1' : '0');
|
||||
} catch {
|
||||
// Private browsing: the choice holds for the page only.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { deviceId } from './device';
|
||||
import type { KeyValueStore } from './storage';
|
||||
|
||||
function memory(
|
||||
initial: Record<string, string> = {},
|
||||
): KeyValueStore & { values: Map<string, string> } {
|
||||
const values = new Map(Object.entries(initial));
|
||||
return {
|
||||
values,
|
||||
getItem: (k) => values.get(k) ?? null,
|
||||
setItem: (k, v) => {
|
||||
values.set(k, v);
|
||||
},
|
||||
removeItem: (k) => {
|
||||
values.delete(k);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const denied: KeyValueStore = {
|
||||
getItem: () => {
|
||||
throw new Error('denied');
|
||||
},
|
||||
setItem: () => {
|
||||
throw new Error('denied');
|
||||
},
|
||||
removeItem: () => {
|
||||
throw new Error('denied');
|
||||
},
|
||||
};
|
||||
|
||||
describe('device id', () => {
|
||||
it('does without randomUUID, missing outside a secure context (HTTP on the LAN)', () => {
|
||||
vi.stubGlobal('crypto', { getRandomValues: globalThis.crypto.getRandomValues.bind(crypto) });
|
||||
try {
|
||||
expect(deviceId(memory())).toMatch(/^[0-9a-f]{32}$/);
|
||||
} finally {
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
|
||||
it('stays the same from one connection to the next', () => {
|
||||
const storage = memory();
|
||||
expect(deviceId(storage)).toBe(deviceId(storage));
|
||||
});
|
||||
|
||||
it('survives a denied storage', () => {
|
||||
expect(deviceId(denied)).toBe(deviceId(denied));
|
||||
});
|
||||
});
|
||||
|
||||
describe('device id migration (#83)', () => {
|
||||
const legacy = '0123456789abcdef0123456789abcdef';
|
||||
|
||||
it('keeps the id stored under the old French key, moved to the new one', () => {
|
||||
const storage = memory({ 'rustscreen.appareil': legacy });
|
||||
expect(deviceId(storage)).toBe(legacy);
|
||||
expect(storage.values.get('rustscreen.device')).toBe(legacy);
|
||||
expect(storage.values.has('rustscreen.appareil')).toBe(false);
|
||||
expect(deviceId(storage)).toBe(legacy);
|
||||
});
|
||||
|
||||
it('prefers the new key when both exist', () => {
|
||||
const current = 'fedcba9876543210fedcba9876543210';
|
||||
const storage = memory({ 'rustscreen.device': current, 'rustscreen.appareil': legacy });
|
||||
expect(deviceId(storage)).toBe(current);
|
||||
});
|
||||
|
||||
it('keeps the old key when the new one cannot be written', () => {
|
||||
const storage = memory({ 'rustscreen.appareil': legacy });
|
||||
storage.setItem = () => {
|
||||
throw new Error('quota');
|
||||
};
|
||||
expect(deviceId(storage)).toBe(legacy);
|
||||
expect(storage.values.get('rustscreen.appareil')).toBe(legacy);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* Id of this device, stable from one visit to the next.
|
||||
*
|
||||
* Two constraints:
|
||||
*
|
||||
* - the viewer is served over HTTP on the LAN address, which is not a secure
|
||||
* context: `crypto.randomUUID()` does not exist there, while
|
||||
* `crypto.getRandomValues()` does. A `randomUUID` made the `hello` fail on
|
||||
* every device other than the host itself;
|
||||
* - the host recognises a device it disconnected by this id: drawn at every
|
||||
* connection, reloading the page would be enough to come back.
|
||||
*
|
||||
* Local storage may be denied (private browsing): the id then lasts for the
|
||||
* page only.
|
||||
*/
|
||||
import { browserStorage, type KeyValueStore, readMigrated } from './storage';
|
||||
|
||||
const KEY = 'rustscreen.device';
|
||||
/** Key before #83. Never regenerate an id because of the rename. */
|
||||
const LEGACY_KEY = 'rustscreen.appareil';
|
||||
const ID_PATTERN = /^[0-9a-f]{32}$/;
|
||||
|
||||
let pageId: string | null = null;
|
||||
|
||||
export function deviceId(storage: KeyValueStore | null = browserStorage()): string {
|
||||
try {
|
||||
const known = storage ? readMigrated(storage, KEY, LEGACY_KEY) : null;
|
||||
if (known && ID_PATTERN.test(known)) {
|
||||
return known;
|
||||
}
|
||||
} catch {
|
||||
// Storage denied: page id below.
|
||||
}
|
||||
const fresh = pageId ?? randomId();
|
||||
pageId = fresh;
|
||||
try {
|
||||
storage?.setItem(KEY, fresh);
|
||||
} catch {
|
||||
// Same.
|
||||
}
|
||||
return fresh;
|
||||
}
|
||||
|
||||
function randomId(): string {
|
||||
const bytes = new Uint8Array(16);
|
||||
crypto.getRandomValues(bytes);
|
||||
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { cleanName, NAME_MAX, readName, saveName, suggestedName } from './deviceName';
|
||||
|
||||
function memory() {
|
||||
const map = new Map<string, string>();
|
||||
return {
|
||||
getItem: (k: string) => map.get(k) ?? null,
|
||||
setItem: (k: string, v: string) => void map.set(k, v),
|
||||
removeItem: (k: string) => void map.delete(k),
|
||||
};
|
||||
}
|
||||
|
||||
describe('device name (#36)', () => {
|
||||
it('is cleaned like the host does, markup kept as text', () => {
|
||||
expect(cleanName(' iPad\tdu\n salon ')).toBe('iPad du salon');
|
||||
expect(cleanName('<b>Kitchen</b>')).toBe('<b>Kitchen</b>');
|
||||
expect(cleanName('é'.repeat(60))).toHaveLength(NAME_MAX);
|
||||
});
|
||||
|
||||
it('is suggested from the device and the browser', () => {
|
||||
const ipad =
|
||||
'Mozilla/5.0 (iPad; CPU OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1';
|
||||
expect(suggestedName(ipad)).toBe('iPad Safari');
|
||||
const pixel =
|
||||
'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Mobile Safari/537.36';
|
||||
expect(suggestedName(pixel)).toBe('Android Chrome');
|
||||
expect(
|
||||
suggestedName('Mozilla/5.0 (X11; Linux x86_64; rv:120.0) Gecko/20100101 Firefox/120.0'),
|
||||
).toBe('Linux Firefox');
|
||||
});
|
||||
|
||||
it('is kept, and an empty one goes back to the suggestion', () => {
|
||||
const storage = memory();
|
||||
expect(readName(storage)).toBeNull();
|
||||
saveName(' Salon ', storage);
|
||||
expect(readName(storage)).toBe('Salon');
|
||||
saveName(' ', storage);
|
||||
expect(readName(storage)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* The name this device gives itself (#36): chosen by the user, kept by the
|
||||
* browser, suggested from the device and the browser until then.
|
||||
*
|
||||
* The host may give its own name to the device (#37): that one shows on the
|
||||
* host side, this one stays the device's choice. The name is text: the host
|
||||
* cleans it the same way (`rs_proto::clean_name`), and every interface shows
|
||||
* markup literally.
|
||||
*/
|
||||
import { browserStorage, type KeyValueStore } from './storage';
|
||||
|
||||
const KEY = 'rustscreen.name';
|
||||
/** `rs_proto::DEVICE_NAME_MAX`. */
|
||||
export const NAME_MAX = 40;
|
||||
|
||||
/** Same rule as the host: control characters out, spaces collapsed, 40 at most. */
|
||||
export function cleanName(raw: string): string {
|
||||
return Array.from(
|
||||
raw
|
||||
// biome-ignore lint/suspicious/noControlCharactersInRegex: removing them is the point.
|
||||
.split(/[\s\u0000-\u001f\u007f-\u009f]+/)
|
||||
.filter(Boolean)
|
||||
.join(' '),
|
||||
)
|
||||
.slice(0, NAME_MAX)
|
||||
.join('')
|
||||
.trimEnd();
|
||||
}
|
||||
|
||||
/** A name from the device and the browser: proper nouns, readable in any language. */
|
||||
export function suggestedName(userAgent: string): string {
|
||||
const device = /iPad/.test(userAgent)
|
||||
? 'iPad'
|
||||
: /iPhone/.test(userAgent)
|
||||
? 'iPhone'
|
||||
: /Android/.test(userAgent)
|
||||
? 'Android'
|
||||
: /CrOS/.test(userAgent)
|
||||
? 'Chromebook'
|
||||
: /Mac OS X|Macintosh/.test(userAgent)
|
||||
? 'Mac'
|
||||
: /Windows/.test(userAgent)
|
||||
? 'Windows'
|
||||
: /Linux/.test(userAgent)
|
||||
? 'Linux'
|
||||
: '';
|
||||
const browser = /Edg\//.test(userAgent)
|
||||
? 'Edge'
|
||||
: /Firefox\//.test(userAgent)
|
||||
? 'Firefox'
|
||||
: /Chrome\//.test(userAgent)
|
||||
? 'Chrome'
|
||||
: /Safari\//.test(userAgent)
|
||||
? 'Safari'
|
||||
: '';
|
||||
return [device, browser].filter(Boolean).join(' ');
|
||||
}
|
||||
|
||||
/** The name the user chose, `null` if none. */
|
||||
export function readName(storage: KeyValueStore | null = browserStorage()): string | null {
|
||||
try {
|
||||
const name = cleanName(storage?.getItem(KEY) ?? '');
|
||||
return name || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Keeps the chosen name; an empty one goes back to the suggestion. */
|
||||
export function saveName(name: string, storage: KeyValueStore | null = browserStorage()): void {
|
||||
try {
|
||||
const clean = cleanName(name);
|
||||
if (clean) storage?.setItem(KEY, clean);
|
||||
else storage?.removeItem(KEY);
|
||||
} catch {
|
||||
// Private browsing: the name holds for this page only.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { type Catalog, createTranslator, pickLanguage } from './i18n';
|
||||
|
||||
const fr: Catalog = {
|
||||
viewer: {
|
||||
greeting: 'Bonjour {name}',
|
||||
viewers: { '0': 'personne', one: '{count} spectateur', other: '{count} spectateurs' },
|
||||
},
|
||||
};
|
||||
const en: Catalog = {
|
||||
viewer: {
|
||||
greeting: 'Hello {name}',
|
||||
onlyInEnglish: 'Only in English',
|
||||
viewers: { '0': 'nobody', one: '{count} viewer', other: '{count} viewers' },
|
||||
},
|
||||
};
|
||||
|
||||
describe('createTranslator (#21)', () => {
|
||||
it('interpolates the parameters', () => {
|
||||
const t = createTranslator('fr', 'viewer', [fr, en]);
|
||||
expect(t('greeting', { name: 'Ana' })).toBe('Bonjour Ana');
|
||||
});
|
||||
|
||||
it('picks the plural form of the language', () => {
|
||||
const t = createTranslator('fr', 'viewer', [fr, en]);
|
||||
expect(t('viewers', { count: 0 })).toBe('personne');
|
||||
expect(t('viewers', { count: 1 })).toBe('1 spectateur');
|
||||
expect(t('viewers', { count: 3 })).toBe('3 spectateurs');
|
||||
});
|
||||
|
||||
it('falls back to English for a missing key, never to the raw key', () => {
|
||||
const t = createTranslator('fr', 'viewer', [fr, en]);
|
||||
expect(t('onlyInEnglish')).toBe('Only in English');
|
||||
expect(t('no.where')).toBe('');
|
||||
});
|
||||
|
||||
it('a language unknown to Intl breaks nothing', () => {
|
||||
const t = createTranslator('xx-invalid-%', 'viewer', [en]);
|
||||
expect(t('viewers', { count: 2 })).toBe('2 viewers');
|
||||
});
|
||||
});
|
||||
|
||||
describe('pickLanguage', () => {
|
||||
it('follows the device language, exactly or by its primary language', () => {
|
||||
expect(pickLanguage(['fr-FR', 'en'], ['en', 'fr'])).toBe('fr');
|
||||
expect(pickLanguage(['fr-CA'], ['en', 'fr'])).toBe('fr');
|
||||
expect(pickLanguage(['pt-BR', 'pt'], ['en', 'pt-BR', 'pt'])).toBe('pt-BR');
|
||||
});
|
||||
|
||||
it('falls back to English for a missing language', () => {
|
||||
expect(pickLanguage(['de-DE', 'it'], ['en', 'fr'])).toBe('en');
|
||||
expect(pickLanguage([], ['en', 'fr'])).toBe('en');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* Translation (#21), without dependencies: key lookup, plurals,
|
||||
* interpolation, English fallback, language choice.
|
||||
*
|
||||
* Texts live in `locales/<language>.json`, at the repository root, one file
|
||||
* per language, one section per application (`viewer`, `desktop`). Adding a
|
||||
* language means adding a file: no code changes. The host embeds them and
|
||||
* serves them to the viewer (`/locales/`), the desktop shell embeds them at
|
||||
* build time.
|
||||
*
|
||||
* This module is pure: the desktop shell imports it as is, without React.
|
||||
*/
|
||||
|
||||
export type Catalog = { [key: string]: string | Catalog };
|
||||
export type Params = Record<string, string | number>;
|
||||
export type Translate = (key: string, params?: Params) => string;
|
||||
|
||||
/**
|
||||
* A language on offer, by its code and its name in that language, as listed
|
||||
* by the host's `/locales/index.json` and the `_language` header of each
|
||||
* locale file.
|
||||
*/
|
||||
export type AvailableLanguage = { code: string; name: string };
|
||||
|
||||
/** The fallback language: complete by contract, checked by `check-i18n`. */
|
||||
export const FALLBACK_LANGUAGE = 'en';
|
||||
|
||||
/**
|
||||
* A translation function for `section` (`viewer`, `desktop`), which looks in
|
||||
* `catalogs` in order: the chosen language, then English. A key found
|
||||
* nowhere gives an empty string, never the raw key.
|
||||
*/
|
||||
export function createTranslator(
|
||||
language: string,
|
||||
section: string,
|
||||
catalogs: Catalog[],
|
||||
): Translate {
|
||||
const rules = pluralRules(language);
|
||||
return (key, params) => {
|
||||
for (const catalog of catalogs) {
|
||||
const value = lookup(catalog, `${section}.${key}`);
|
||||
if (value === undefined) continue;
|
||||
const text = typeof value === 'string' ? value : plural(value, rules, params);
|
||||
if (text !== undefined) return interpolate(text, params);
|
||||
}
|
||||
return '';
|
||||
};
|
||||
}
|
||||
|
||||
function lookup(catalog: Catalog, path: string): string | Catalog | undefined {
|
||||
let node: string | Catalog | undefined = catalog;
|
||||
for (const part of path.split('.')) {
|
||||
if (node === undefined || typeof node === 'string') return undefined;
|
||||
node = node[part];
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
/**
|
||||
* A plural is an object of forms: an exact value (`"0"`), then the
|
||||
* `Intl.PluralRules` category (`one`, `few`, `other`...).
|
||||
*/
|
||||
function plural(
|
||||
forms: Catalog,
|
||||
rules: Intl.PluralRules,
|
||||
params: Params | undefined,
|
||||
): string | undefined {
|
||||
const count = params?.count;
|
||||
if (typeof count !== 'number') {
|
||||
return typeof forms.other === 'string' ? forms.other : undefined;
|
||||
}
|
||||
const exact = forms[String(count)];
|
||||
if (typeof exact === 'string') return exact;
|
||||
const category = forms[rules.select(count)];
|
||||
if (typeof category === 'string') return category;
|
||||
return typeof forms.other === 'string' ? forms.other : undefined;
|
||||
}
|
||||
|
||||
function pluralRules(language: string): Intl.PluralRules {
|
||||
try {
|
||||
return new Intl.PluralRules(language);
|
||||
} catch {
|
||||
return new Intl.PluralRules(FALLBACK_LANGUAGE);
|
||||
}
|
||||
}
|
||||
|
||||
function interpolate(text: string, params: Params | undefined): string {
|
||||
if (!params) return text;
|
||||
return text.replace(/\{(\w+)\}/g, (whole, name: string) =>
|
||||
name in params ? String(params[name]) : whole,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The language to show: the first of the device preferences that exists,
|
||||
* exactly (`pt-BR`) or by its primary language (`fr-CA` gives `fr`),
|
||||
* otherwise English.
|
||||
*/
|
||||
export function pickLanguage(preferences: readonly string[], available: readonly string[]): string {
|
||||
const codes = available.map((code) => code.toLowerCase());
|
||||
for (const preference of preferences) {
|
||||
const wanted = preference.toLowerCase();
|
||||
const exact = codes.indexOf(wanted);
|
||||
if (exact >= 0) return available[exact] ?? FALLBACK_LANGUAGE;
|
||||
const primary = wanted.split('-')[0];
|
||||
const close = codes.findIndex((code) => code.split('-')[0] === primary);
|
||||
if (close >= 0) return available[close] ?? FALLBACK_LANGUAGE;
|
||||
}
|
||||
return codes.includes(FALLBACK_LANGUAGE)
|
||||
? FALLBACK_LANGUAGE
|
||||
: (available[0] ?? FALLBACK_LANGUAGE);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* System events announcing that a reconnection is likely to succeed now:
|
||||
* network back, interface change, device wake-up, page restored from the
|
||||
* back/forward cache.
|
||||
*
|
||||
* This module decides nothing: it notifies the session, which alone knows
|
||||
* whether it is waiting, has given up or is already connected (see
|
||||
* `ViewerSession.wake`).
|
||||
*/
|
||||
|
||||
export type WakeReason = 'online' | 'network_change' | 'visible' | 'pageshow';
|
||||
|
||||
type NavigatorWithConnection = Navigator & { connection?: EventTarget };
|
||||
|
||||
/**
|
||||
* Attaches the listeners and returns the function that removes them. Each
|
||||
* target is optional: `navigator.connection` exists neither in Safari nor in
|
||||
* Firefox, and none of this exists in a test without a DOM.
|
||||
*/
|
||||
export function watchLifecycle(onWake: (reason: WakeReason) => void): () => void {
|
||||
const cleanups: Array<() => void> = [];
|
||||
const on = (
|
||||
target: EventTarget | null | undefined,
|
||||
type: string,
|
||||
handler: (event: Event) => void,
|
||||
) => {
|
||||
if (!target || typeof target.addEventListener !== 'function') return;
|
||||
target.addEventListener(type, handler);
|
||||
cleanups.push(() => target.removeEventListener(type, handler));
|
||||
};
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
on(window, 'online', () => onWake('online'));
|
||||
on(window, 'pageshow', (event) => {
|
||||
if ((event as PageTransitionEvent).persisted) onWake('pageshow');
|
||||
});
|
||||
}
|
||||
if (typeof document !== 'undefined') {
|
||||
on(document, 'visibilitychange', () => {
|
||||
if (document.visibilityState === 'visible') onWake('visible');
|
||||
});
|
||||
}
|
||||
if (typeof navigator !== 'undefined') {
|
||||
on((navigator as NavigatorWithConnection).connection, 'change', () => onWake('network_change'));
|
||||
}
|
||||
|
||||
return () => {
|
||||
for (const cleanup of cleanups.splice(0)) cleanup();
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { exchangeCode, qrDetector } from './pairing';
|
||||
|
||||
function respond(status: number, body: unknown): typeof fetch {
|
||||
return async () => new Response(JSON.stringify(body), { status });
|
||||
}
|
||||
|
||||
describe('exchangeCode', () => {
|
||||
it('returns the session path, versioned', async () => {
|
||||
const outcome = await exchangeCode(
|
||||
'k7m4pq',
|
||||
respond(200, {
|
||||
status: 'accepted',
|
||||
room: 'abc234',
|
||||
token: '0123456789abcdef0123456789abcdef',
|
||||
}),
|
||||
);
|
||||
expect(outcome).toEqual({
|
||||
kind: 'accepted',
|
||||
path: '/r/abc234?t=0123456789abcdef0123456789abcdef&v=1',
|
||||
});
|
||||
});
|
||||
|
||||
it('tells an unknown code, an expired one, and too many attempts apart', async () => {
|
||||
expect(await exchangeCode('x', respond(404, { status: 'unknown' }))).toEqual({
|
||||
kind: 'unknown',
|
||||
});
|
||||
expect(await exchangeCode('x', respond(410, { status: 'expired' }))).toEqual({
|
||||
kind: 'expired',
|
||||
});
|
||||
expect(
|
||||
await exchangeCode('x', respond(429, { status: 'too_many_attempts', retry_after_s: 42 })),
|
||||
).toEqual({ kind: 'too_many_attempts', retryAfterS: 42 });
|
||||
});
|
||||
|
||||
it('does not throw when the network fails', async () => {
|
||||
const broken: typeof fetch = async () => {
|
||||
throw new TypeError('network');
|
||||
};
|
||||
expect(await exchangeCode('x', broken)).toEqual({ kind: 'network' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('qrDetector', () => {
|
||||
it('steps aside when the browser has no BarcodeDetector', () => {
|
||||
expect(qrDetector()).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* Pairing without a camera (#19): the short code shown by the host, exchanged
|
||||
* for the room and the token. And, when the browser allows it, reading the QR
|
||||
* code from the page itself.
|
||||
*/
|
||||
|
||||
import { LINK_VERSION, type PairingResponse } from '../proto';
|
||||
|
||||
export type CodeOutcome =
|
||||
| { kind: 'accepted'; path: string }
|
||||
| { kind: 'unknown' }
|
||||
| { kind: 'expired' }
|
||||
| { kind: 'too_many_attempts'; retryAfterS: number }
|
||||
| { kind: 'network' };
|
||||
|
||||
/** Exchanges a code for the session path. Never throws. */
|
||||
export async function exchangeCode(
|
||||
code: string,
|
||||
fetchImpl: typeof fetch = fetch,
|
||||
): Promise<CodeOutcome> {
|
||||
let body: PairingResponse;
|
||||
try {
|
||||
const response = await fetchImpl('/api/code', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ code }),
|
||||
});
|
||||
body = (await response.json()) as PairingResponse;
|
||||
} catch {
|
||||
return { kind: 'network' };
|
||||
}
|
||||
switch (body.status) {
|
||||
case 'accepted':
|
||||
return {
|
||||
kind: 'accepted',
|
||||
path: `/r/${encodeURIComponent(body.room)}?t=${encodeURIComponent(body.token)}&v=${LINK_VERSION}`,
|
||||
};
|
||||
case 'unknown':
|
||||
return { kind: 'unknown' };
|
||||
case 'expired':
|
||||
return { kind: 'expired' };
|
||||
case 'too_many_attempts':
|
||||
return { kind: 'too_many_attempts', retryAfterS: body.retry_after_s };
|
||||
default:
|
||||
return { kind: 'network' };
|
||||
}
|
||||
}
|
||||
|
||||
/** The subset of the BarcodeDetector API in use. */
|
||||
type Detector = {
|
||||
detect(source: CanvasImageSource): Promise<Array<{ rawValue: string }>>;
|
||||
};
|
||||
type DetectorConstructor = new (options: { formats: string[] }) => Detector;
|
||||
|
||||
/**
|
||||
* A QR code reader, if this browser exposes one. It also needs a camera, hence
|
||||
* a secure context: a page served over HTTP on the LAN does not get one, and
|
||||
* the short code takes over.
|
||||
*/
|
||||
export function qrDetector(): Detector | null {
|
||||
const scope = globalThis as unknown as {
|
||||
BarcodeDetector?: DetectorConstructor;
|
||||
isSecureContext?: boolean;
|
||||
navigator?: Navigator;
|
||||
};
|
||||
if (!scope.BarcodeDetector || !scope.isSecureContext) return null;
|
||||
if (!scope.navigator?.mediaDevices?.getUserMedia) return null;
|
||||
try {
|
||||
return new scope.BarcodeDetector({ formats: ['qr_code'] });
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { readStamp, STAMP_BITS, STAMP_BLOCK, STAMP_MARGIN, summarize } from './perfProbe';
|
||||
|
||||
function stripFor(millis: number): { rgba: Uint8ClampedArray; width: number } {
|
||||
const width = STAMP_MARGIN * 2 + STAMP_BITS * STAMP_BLOCK;
|
||||
const height = STAMP_MARGIN * 2 + 2 * STAMP_BLOCK;
|
||||
const rgba = new Uint8ClampedArray(width * height * 4);
|
||||
const paint = (bit: number, line: number, on: boolean) => {
|
||||
const y0 = STAMP_MARGIN + line * STAMP_BLOCK;
|
||||
const x0 = STAMP_MARGIN + bit * STAMP_BLOCK;
|
||||
for (let y = y0; y < y0 + STAMP_BLOCK; y++) {
|
||||
for (let x = x0; x < x0 + STAMP_BLOCK; x++) {
|
||||
rgba.fill(on ? 250 : 5, (y * width + x) * 4, (y * width + x) * 4 + 3);
|
||||
}
|
||||
}
|
||||
};
|
||||
for (let bit = 0; bit < STAMP_BITS; bit++) {
|
||||
const set = Math.floor(millis / 2 ** (STAMP_BITS - 1 - bit)) % 2 === 1;
|
||||
// Row 0: the bit; row 1: its complement, as the test pattern draws it.
|
||||
paint(bit, 0, set);
|
||||
paint(bit, 1, !set);
|
||||
}
|
||||
return { rgba, width };
|
||||
}
|
||||
|
||||
describe('latency probe (#86)', () => {
|
||||
it('reads back the capture instant written by the test pattern', () => {
|
||||
const millis = 1_793_034_067_276;
|
||||
const { rgba, width } = stripFor(millis);
|
||||
expect(readStamp(rgba, width)).toBe(millis);
|
||||
});
|
||||
|
||||
it('rejects a stamp blurred by compression instead of misreading it', () => {
|
||||
const { rgba, width } = stripFor(1_793_034_067_276);
|
||||
// Bit 11 (2048 ms) turns gray on its first row.
|
||||
const x = STAMP_MARGIN + 36 * STAMP_BLOCK + STAMP_BLOCK / 2;
|
||||
const y = STAMP_MARGIN + STAMP_BLOCK / 2;
|
||||
rgba.fill(128, (y * width + x) * 4, (y * width + x) * 4 + 3);
|
||||
expect(readStamp(rgba, width)).toBeNull();
|
||||
});
|
||||
|
||||
it('summarizes latency percentiles and displayed frames per second', () => {
|
||||
const times = Array.from({ length: 120 }, (_, i) => i * (1000 / 60));
|
||||
const summary = summarize([10, 20, 30, 40, 100], times, 2, 120, { width: 1920, height: 1080 });
|
||||
expect(summary.latencyMs).toEqual({ median: 30, p95: 100, max: 100 });
|
||||
expect(summary.fps).toBe(60);
|
||||
expect(summary.skipped).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,155 @@
|
||||
/**
|
||||
* Latency probe (#86), enabled with `?perf=1` in the session URL.
|
||||
*
|
||||
* The synthetic test pattern writes its capture instant (Unix milliseconds)
|
||||
* as a row of black and white blocks. For every displayed frame
|
||||
* (`requestVideoFrameCallback`), the probe reads that row back and measures
|
||||
* the end-to-end latency: capture, conversion, encoding, network, decoding
|
||||
* and display, on one clock when host and viewer share a machine. It also
|
||||
* counts displayed frames per second and skipped frames.
|
||||
*
|
||||
* The results are exposed on `window.__rustscreenPerf` for the bench script;
|
||||
* nothing is shown to the user.
|
||||
*/
|
||||
|
||||
/** Layout of the stamp, in step with `rs-capture/src/synthetic.rs`. */
|
||||
export const STAMP_BITS = 48;
|
||||
export const STAMP_BLOCK = 16;
|
||||
export const STAMP_MARGIN = 8;
|
||||
|
||||
/**
|
||||
* Reads the stamp from RGBA pixels of the top-left strip, `width` wide. The
|
||||
* second row holds the complement: a bit blurred by compression on either
|
||||
* row makes the whole stamp unreadable rather than wrong.
|
||||
*/
|
||||
export function readStamp(rgba: Uint8ClampedArray, width: number): number | null {
|
||||
let millis = 0;
|
||||
for (let bit = 0; bit < STAMP_BITS; bit++) {
|
||||
const x = STAMP_MARGIN + bit * STAMP_BLOCK + STAMP_BLOCK / 2;
|
||||
const at = (line: number) =>
|
||||
rgba[((STAMP_MARGIN + line * STAMP_BLOCK + STAMP_BLOCK / 2) * width + x) * 4 + 1];
|
||||
const value = at(0);
|
||||
const complement = at(1);
|
||||
if (value === undefined || complement === undefined) return null;
|
||||
if (Math.abs(value - complement) < 128) return null;
|
||||
millis = millis * 2 + (value > complement ? 1 : 0);
|
||||
}
|
||||
return millis;
|
||||
}
|
||||
|
||||
export type PerfSummary = {
|
||||
frames: number;
|
||||
/** Displayed frames per second over the last second. */
|
||||
fps: number;
|
||||
/** Frames the compositor never showed (`presentedFrames` gaps). */
|
||||
skipped: number;
|
||||
latencyMs: { median: number; p95: number; max: number } | null;
|
||||
width: number;
|
||||
height: number;
|
||||
};
|
||||
|
||||
const STAMP_MODULO = 2 ** STAMP_BITS;
|
||||
|
||||
export function summarize(
|
||||
latencies: number[],
|
||||
presentTimes: number[],
|
||||
skipped: number,
|
||||
frames: number,
|
||||
size: { width: number; height: number },
|
||||
): PerfSummary {
|
||||
const sorted = [...latencies].sort((a, b) => a - b);
|
||||
const pick = (q: number) =>
|
||||
sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))] ?? 0;
|
||||
const last = presentTimes.at(-1) ?? 0;
|
||||
const fps = presentTimes.filter((t) => last - t < 1000).length;
|
||||
return {
|
||||
frames,
|
||||
fps,
|
||||
skipped,
|
||||
latencyMs: sorted.length
|
||||
? { median: pick(0.5), p95: pick(0.95), max: sorted.at(-1) ?? 0 }
|
||||
: null,
|
||||
width: size.width,
|
||||
height: size.height,
|
||||
};
|
||||
}
|
||||
|
||||
type FrameCallbackVideo = HTMLVideoElement & {
|
||||
requestVideoFrameCallback?: (
|
||||
callback: (
|
||||
now: number,
|
||||
metadata: { presentedFrames: number; expectedDisplayTime: number },
|
||||
) => void,
|
||||
) => number;
|
||||
cancelVideoFrameCallback?: (handle: number) => void;
|
||||
};
|
||||
|
||||
/** Starts the probe on `video`; returns the function that stops it. */
|
||||
export function startProbe(video: HTMLVideoElement): () => void {
|
||||
const target = video as FrameCallbackVideo;
|
||||
if (!target.requestVideoFrameCallback) return () => undefined;
|
||||
const canvas = document.createElement('canvas');
|
||||
const width = STAMP_MARGIN * 2 + STAMP_BITS * STAMP_BLOCK;
|
||||
const height = STAMP_MARGIN * 2 + 2 * STAMP_BLOCK;
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
const context = canvas.getContext('2d', { willReadFrequently: true });
|
||||
const latencies: number[] = [];
|
||||
const presentTimes: number[] = [];
|
||||
let skipped = 0;
|
||||
let frames = 0;
|
||||
let lastPresented: number | null = null;
|
||||
let handle = 0;
|
||||
let stopped = false;
|
||||
|
||||
const onFrame = (
|
||||
_now: number,
|
||||
metadata: { presentedFrames: number; expectedDisplayTime: number },
|
||||
) => {
|
||||
if (stopped) return;
|
||||
frames++;
|
||||
if (lastPresented !== null && metadata.presentedFrames > lastPresented + 1) {
|
||||
skipped += metadata.presentedFrames - lastPresented - 1;
|
||||
}
|
||||
lastPresented = metadata.presentedFrames;
|
||||
presentTimes.push(metadata.expectedDisplayTime);
|
||||
if (presentTimes.length > 600) presentTimes.shift();
|
||||
if (context && video.videoWidth >= width) {
|
||||
context.drawImage(video, 0, 0, width, height, 0, 0, width, height);
|
||||
const stamp = readStamp(context.getImageData(0, 0, width, height).data, width);
|
||||
if (stamp !== null) {
|
||||
const shown = (performance.timeOrigin + metadata.expectedDisplayTime) % STAMP_MODULO;
|
||||
const latency = shown - stamp;
|
||||
if (latency > -50 && latency < 5000) {
|
||||
latencies.push(Math.max(0, latency));
|
||||
if (latencies.length > 3000) latencies.shift();
|
||||
}
|
||||
}
|
||||
}
|
||||
handle = target.requestVideoFrameCallback?.(onFrame) ?? 0;
|
||||
};
|
||||
handle = target.requestVideoFrameCallback(onFrame);
|
||||
|
||||
(window as unknown as { __rustscreenPerf?: unknown }).__rustscreenPerf = {
|
||||
summary: () =>
|
||||
summarize(latencies, presentTimes, skipped, frames, {
|
||||
width: video.videoWidth,
|
||||
height: video.videoHeight,
|
||||
}),
|
||||
reset: () => {
|
||||
latencies.length = 0;
|
||||
presentTimes.length = 0;
|
||||
skipped = 0;
|
||||
frames = 0;
|
||||
},
|
||||
};
|
||||
return () => {
|
||||
stopped = true;
|
||||
target.cancelVideoFrameCallback?.(handle);
|
||||
};
|
||||
}
|
||||
|
||||
/** The probe runs only when the URL asks for it. */
|
||||
export function probeRequested(search: string): boolean {
|
||||
return new URLSearchParams(search).get('perf') === '1';
|
||||
}
|
||||
@@ -3,9 +3,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { ViewerSession, type ViewerState } from './session';
|
||||
|
||||
/**
|
||||
* WebSocket qui échoue immédiatement, pour éprouver la reconnexion sans réseau
|
||||
* ni navigateur. Il n'ouvre jamais: `close` arrive tout de suite, exactement
|
||||
* comme un hôte éteint.
|
||||
* WebSocket that fails at once, to exercise reconnection without network or
|
||||
* browser. It never opens: `close` arrives straight away, exactly like a host
|
||||
* that is off.
|
||||
*/
|
||||
class FailingWebSocket {
|
||||
static readonly OPEN = 1;
|
||||
@@ -45,7 +45,7 @@ class StubPeerConnection {
|
||||
close(): void {}
|
||||
}
|
||||
|
||||
describe('reconnexion', () => {
|
||||
describe('reconnection', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
FailingWebSocket.instances = [];
|
||||
@@ -58,7 +58,7 @@ describe('reconnexion', () => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('réessaie, puis abandonne avec un message réseau', async () => {
|
||||
it('retries, then gives up with a network message', async () => {
|
||||
const states: ViewerState[] = [];
|
||||
const session = new ViewerSession({
|
||||
room: 'abc234',
|
||||
@@ -70,7 +70,7 @@ describe('reconnexion', () => {
|
||||
});
|
||||
|
||||
session.start();
|
||||
// Laisse passer les microtâches qui déclenchent la fermeture.
|
||||
// Lets the microtasks that trigger the close run.
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
@@ -87,7 +87,7 @@ describe('reconnexion', () => {
|
||||
expect(FailingWebSocket.instances.length).toBeLessThanOrEqual(3);
|
||||
});
|
||||
|
||||
it('stop() coupe la reconnexion et ne rappelle plus l’état', async () => {
|
||||
it('stop() cuts reconnection and no longer reports the state', async () => {
|
||||
const states: ViewerState[] = [];
|
||||
const session = new ViewerSession({
|
||||
room: 'abc234',
|
||||
@@ -106,7 +106,7 @@ describe('reconnexion', () => {
|
||||
expect(states.length).toBe(before);
|
||||
});
|
||||
|
||||
it('refuse de démarrer deux fois après stop()', async () => {
|
||||
it('refuses to start again after stop()', async () => {
|
||||
const session = new ViewerSession({
|
||||
room: 'abc234',
|
||||
token: '0123456789abcdef0123456789abcdef',
|
||||
|
||||
@@ -0,0 +1,501 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import type { ClientMessage, StreamSettings } from '../proto';
|
||||
import { ViewerSession, type ViewerState, WAKE_MIN_INTERVAL_MS } from './session';
|
||||
|
||||
/**
|
||||
* Resume after a network change (#39) and after sleep (#42).
|
||||
*
|
||||
* A fake host answers like the real one: `welcome` to `hello`, `answer` to the
|
||||
* offer, `settings_applied` with ITS default setting to a quality request.
|
||||
* When it is "off" (or the network is cut), the socket closes at once.
|
||||
*/
|
||||
|
||||
const BALANCED: StreamSettings = { quality: 'balanced', max_bitrate_kbps: 3000, max_fps: 30 };
|
||||
const SHARP: StreamSettings = { quality: 'sharp', max_bitrate_kbps: 8000, max_fps: 60 };
|
||||
const SAVER: StreamSettings = { quality: 'saver', max_bitrate_kbps: 1200, max_fps: 20 };
|
||||
|
||||
const host = { up: false };
|
||||
|
||||
type Listener = (event: unknown) => void;
|
||||
|
||||
class FakeWebSocket {
|
||||
static readonly CONNECTING = 0;
|
||||
static readonly OPEN = 1;
|
||||
static readonly CLOSING = 2;
|
||||
static readonly CLOSED = 3;
|
||||
static instances: FakeWebSocket[] = [];
|
||||
|
||||
readyState = FakeWebSocket.CONNECTING;
|
||||
sent: ClientMessage[] = [];
|
||||
private listeners = new Map<string, Listener[]>();
|
||||
|
||||
constructor(public readonly url: string) {
|
||||
FakeWebSocket.instances.push(this);
|
||||
const reachable = host.up;
|
||||
queueMicrotask(() => {
|
||||
if (this.readyState !== FakeWebSocket.CONNECTING) return;
|
||||
if (reachable) {
|
||||
this.readyState = FakeWebSocket.OPEN;
|
||||
this.emit('open', {});
|
||||
} else {
|
||||
this.drop();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
addEventListener(type: string, listener: Listener): void {
|
||||
const list = this.listeners.get(type) ?? [];
|
||||
list.push(listener);
|
||||
this.listeners.set(type, list);
|
||||
}
|
||||
|
||||
send(raw: string): void {
|
||||
const message = JSON.parse(raw) as ClientMessage;
|
||||
this.sent.push(message);
|
||||
if (message.type === 'hello') {
|
||||
this.reply({
|
||||
type: 'welcome',
|
||||
version: 1,
|
||||
room: 'abc234',
|
||||
source: null,
|
||||
settings: BALANCED,
|
||||
connected: 1,
|
||||
limit: 4,
|
||||
});
|
||||
} else if (message.type === 'offer') {
|
||||
this.reply({ type: 'answer', sdp: 'v=0' });
|
||||
} else if (message.type === 'quality_request') {
|
||||
// Like the current host: it sends back what it applies, not the request.
|
||||
this.reply({ type: 'settings_applied', settings: BALANCED });
|
||||
}
|
||||
}
|
||||
|
||||
/** Like a browser: a requested close is notified later. */
|
||||
close(): void {
|
||||
if (this.readyState === FakeWebSocket.CLOSED) return;
|
||||
this.readyState = FakeWebSocket.CLOSING;
|
||||
queueMicrotask(() => this.drop());
|
||||
}
|
||||
|
||||
/** Dropout as seen by the viewer: network lost or host stopped. */
|
||||
drop(): void {
|
||||
if (this.readyState === FakeWebSocket.CLOSED) return;
|
||||
this.readyState = FakeWebSocket.CLOSED;
|
||||
this.emit('close', {});
|
||||
}
|
||||
|
||||
private reply(message: unknown): void {
|
||||
queueMicrotask(() => {
|
||||
if (this.readyState !== FakeWebSocket.OPEN) return;
|
||||
this.emit('message', { data: JSON.stringify(message) });
|
||||
});
|
||||
}
|
||||
|
||||
private emit(type: string, event: unknown): void {
|
||||
for (const listener of this.listeners.get(type) ?? []) listener(event);
|
||||
}
|
||||
}
|
||||
|
||||
class FakePeerConnection extends EventTarget {
|
||||
static instances: FakePeerConnection[] = [];
|
||||
connectionState: RTCPeerConnectionState = 'new';
|
||||
iceGatheringState: RTCIceGatheringState = 'complete';
|
||||
localDescription: { type: string; sdp: string } | null = null;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
FakePeerConnection.instances.push(this);
|
||||
}
|
||||
|
||||
addTransceiver(): void {}
|
||||
async createOffer() {
|
||||
return { type: 'offer', sdp: 'v=0' };
|
||||
}
|
||||
async setLocalDescription(description: { type: string; sdp: string }) {
|
||||
this.localDescription = description;
|
||||
}
|
||||
async setRemoteDescription() {
|
||||
queueMicrotask(() => {
|
||||
if (host.up && this.connectionState === 'new') this.setConnectionState('connected');
|
||||
});
|
||||
}
|
||||
/** Like the browser: `close()` fires no event. */
|
||||
close(): void {
|
||||
this.connectionState = 'closed';
|
||||
}
|
||||
setConnectionState(state: RTCPeerConnectionState): void {
|
||||
this.connectionState = state;
|
||||
this.dispatchEvent(new Event('connectionstatechange'));
|
||||
}
|
||||
}
|
||||
|
||||
class FakeDocument extends EventTarget {
|
||||
visibilityState: DocumentVisibilityState = 'visible';
|
||||
setVisibility(state: DocumentVisibilityState): void {
|
||||
this.visibilityState = state;
|
||||
this.dispatchEvent(new Event('visibilitychange'));
|
||||
}
|
||||
}
|
||||
|
||||
let fakeWindow: EventTarget;
|
||||
let fakeDocument: FakeDocument;
|
||||
let connection: EventTarget;
|
||||
|
||||
function newSession(
|
||||
states: ViewerState[],
|
||||
extra: { maxAttempts?: number; quality?: StreamSettings } = {},
|
||||
) {
|
||||
return new ViewerSession({
|
||||
room: 'abc234',
|
||||
token: '0123456789abcdef0123456789abcdef',
|
||||
wsUrl: 'ws://192.168.1.20:8099/ws',
|
||||
onState: (state) => states.push(state),
|
||||
onStream: () => undefined,
|
||||
...extra,
|
||||
});
|
||||
}
|
||||
|
||||
/** Lets the microtasks run (open, host replies). */
|
||||
async function settle(ms = 0): Promise<void> {
|
||||
await vi.advanceTimersByTimeAsync(ms);
|
||||
}
|
||||
|
||||
function lastSocket(): FakeWebSocket {
|
||||
const ws = FakeWebSocket.instances.at(-1);
|
||||
if (!ws) throw new Error('no socket');
|
||||
return ws;
|
||||
}
|
||||
|
||||
function lastPeer(): FakePeerConnection {
|
||||
const pc = FakePeerConnection.instances.at(-1);
|
||||
if (!pc) throw new Error('no WebRTC connection');
|
||||
return pc;
|
||||
}
|
||||
|
||||
/** Clean cut: the socket drops, then the WebRTC connection fails. */
|
||||
function cut(): void {
|
||||
host.up = false;
|
||||
const pc = lastPeer();
|
||||
lastSocket().drop();
|
||||
pc.setConnectionState('failed');
|
||||
}
|
||||
|
||||
function goOnline(): void {
|
||||
fakeWindow.dispatchEvent(new Event('online'));
|
||||
}
|
||||
|
||||
/** Runs until giving up, host unreachable. */
|
||||
async function exhaust(): Promise<void> {
|
||||
for (let i = 0; i < 10; i += 1) await settle(15_000);
|
||||
}
|
||||
|
||||
describe('resume after a network change or sleep', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
host.up = false;
|
||||
FakeWebSocket.instances = [];
|
||||
FakePeerConnection.instances = [];
|
||||
fakeWindow = new EventTarget();
|
||||
fakeDocument = new FakeDocument();
|
||||
connection = new EventTarget();
|
||||
vi.stubGlobal('WebSocket', FakeWebSocket);
|
||||
vi.stubGlobal('RTCPeerConnection', FakePeerConnection);
|
||||
vi.stubGlobal('window', fakeWindow);
|
||||
vi.stubGlobal('document', fakeDocument);
|
||||
vi.stubGlobal('navigator', { userAgent: 'test', platform: 'test', connection });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('Wi-Fi to Ethernet: `online` restarts at once, the stream is back within 5 s', async () => {
|
||||
const states: ViewerState[] = [];
|
||||
host.up = true;
|
||||
const session = newSession(states);
|
||||
session.start();
|
||||
await settle();
|
||||
expect(states.at(-1)?.kind).toBe('streaming');
|
||||
|
||||
const cutAt = Date.now();
|
||||
cut();
|
||||
await settle();
|
||||
expect(states.at(-1)?.kind).toBe('reconnecting');
|
||||
// Wi-Fi is gone, the first attempts fail.
|
||||
await settle(3000);
|
||||
expect(states.at(-1)?.kind).toBe('reconnecting');
|
||||
const sockets = FakeWebSocket.instances.length;
|
||||
|
||||
// Ethernet arrives: no waiting for the timer (4 s at this point).
|
||||
host.up = true;
|
||||
goOnline();
|
||||
await settle();
|
||||
expect(FakeWebSocket.instances.length).toBe(sockets + 1);
|
||||
expect(states.at(-1)?.kind).toBe('streaming');
|
||||
expect(Date.now() - cutAt).toBeLessThan(5000);
|
||||
session.stop();
|
||||
});
|
||||
|
||||
it('`change` on navigator.connection restarts while waiting, and counts as an attempt', async () => {
|
||||
const states: ViewerState[] = [];
|
||||
const session = newSession(states, { maxAttempts: 6 });
|
||||
session.start();
|
||||
await settle();
|
||||
await settle(1000);
|
||||
await settle(2000);
|
||||
// Three attempts made, the fourth waits 4 s.
|
||||
expect(FakeWebSocket.instances).toHaveLength(3);
|
||||
expect(states.at(-1)).toMatchObject({ kind: 'reconnecting', attempt: 3, delayMs: 4000 });
|
||||
|
||||
connection.dispatchEvent(new Event('change'));
|
||||
await settle();
|
||||
expect(FakeWebSocket.instances).toHaveLength(4);
|
||||
expect(states).toContainEqual({ kind: 'connecting', attempt: 4 });
|
||||
// The failure of this attempt resumes with the next delay, not the first.
|
||||
expect(states.at(-1)).toMatchObject({ kind: 'reconnecting', attempt: 4, delayMs: 8000 });
|
||||
session.stop();
|
||||
});
|
||||
|
||||
it('limits restarts to one every 2 s, even when events pour in', async () => {
|
||||
const states: ViewerState[] = [];
|
||||
const session = newSession(states);
|
||||
session.start();
|
||||
await settle();
|
||||
expect(FakeWebSocket.instances).toHaveLength(1);
|
||||
|
||||
// Interface change: `online` and `change` arrive together.
|
||||
goOnline();
|
||||
connection.dispatchEvent(new Event('change'));
|
||||
fakeDocument.setVisibility('visible');
|
||||
await settle();
|
||||
expect(FakeWebSocket.instances).toHaveLength(2);
|
||||
|
||||
await settle(WAKE_MIN_INTERVAL_MS - 500);
|
||||
const before = FakeWebSocket.instances.length;
|
||||
goOnline();
|
||||
await settle();
|
||||
expect(FakeWebSocket.instances).toHaveLength(before);
|
||||
|
||||
await settle(500);
|
||||
const afterInterval = FakeWebSocket.instances.length;
|
||||
goOnline();
|
||||
await settle();
|
||||
expect(FakeWebSocket.instances).toHaveLength(afterInterval + 1);
|
||||
session.stop();
|
||||
});
|
||||
|
||||
it('leaves a streaming session alone', async () => {
|
||||
const states: ViewerState[] = [];
|
||||
host.up = true;
|
||||
const session = newSession(states);
|
||||
session.start();
|
||||
await settle();
|
||||
expect(states.at(-1)?.kind).toBe('streaming');
|
||||
|
||||
goOnline();
|
||||
connection.dispatchEvent(new Event('change'));
|
||||
fakeDocument.setVisibility('visible');
|
||||
await settle();
|
||||
expect(FakeWebSocket.instances).toHaveLength(1);
|
||||
expect(states.at(-1)?.kind).toBe('streaming');
|
||||
session.stop();
|
||||
});
|
||||
|
||||
it('after giving up, returning to the foreground opens ONE new series that ends', async () => {
|
||||
const states: ViewerState[] = [];
|
||||
const session = newSession(states, { maxAttempts: 3 });
|
||||
session.start();
|
||||
await exhaust();
|
||||
expect(states.at(-1)).toMatchObject({ kind: 'failed', code: 'network' });
|
||||
expect(FakeWebSocket.instances).toHaveLength(3);
|
||||
|
||||
// Going to sleep: nothing happens.
|
||||
fakeDocument.setVisibility('hidden');
|
||||
await exhaust();
|
||||
expect(FakeWebSocket.instances).toHaveLength(3);
|
||||
|
||||
// Wake-up, host still off: a series of three, then failure, no loop.
|
||||
fakeDocument.setVisibility('visible');
|
||||
await exhaust();
|
||||
expect(FakeWebSocket.instances).toHaveLength(6);
|
||||
expect(states.at(-1)).toMatchObject({ kind: 'failed', code: 'network' });
|
||||
await exhaust();
|
||||
expect(FakeWebSocket.instances).toHaveLength(6);
|
||||
session.stop();
|
||||
});
|
||||
|
||||
it('after giving up, `online` restarts and gets the stream back if the host returned', async () => {
|
||||
const states: ViewerState[] = [];
|
||||
const session = newSession(states, { maxAttempts: 2 });
|
||||
session.start();
|
||||
await exhaust();
|
||||
expect(states.at(-1)?.kind).toBe('failed');
|
||||
|
||||
host.up = true;
|
||||
goOnline();
|
||||
await settle();
|
||||
expect(states.at(-1)?.kind).toBe('streaming');
|
||||
session.stop();
|
||||
});
|
||||
|
||||
it('`pageshow` restarts only for a page restored from the cache', async () => {
|
||||
const states: ViewerState[] = [];
|
||||
const session = newSession(states, { maxAttempts: 2 });
|
||||
session.start();
|
||||
await exhaust();
|
||||
expect(FakeWebSocket.instances).toHaveLength(2);
|
||||
|
||||
fakeWindow.dispatchEvent(Object.assign(new Event('pageshow'), { persisted: false }));
|
||||
await settle();
|
||||
expect(FakeWebSocket.instances).toHaveLength(2);
|
||||
|
||||
fakeWindow.dispatchEvent(Object.assign(new Event('pageshow'), { persisted: true }));
|
||||
await settle();
|
||||
expect(FakeWebSocket.instances).toHaveLength(3);
|
||||
session.stop();
|
||||
});
|
||||
|
||||
it('wake-up on a silently dead transport: reconnection, and the close of the old socket does not break the new one', async () => {
|
||||
const states: ViewerState[] = [];
|
||||
host.up = true;
|
||||
const session = newSession(states);
|
||||
session.start();
|
||||
await settle();
|
||||
expect(states.at(-1)?.kind).toBe('streaming');
|
||||
|
||||
// The device slept: the connection died without any event being
|
||||
// handled, the socket still believes it is open.
|
||||
lastPeer().connectionState = 'disconnected';
|
||||
fakeDocument.setVisibility('visible');
|
||||
await settle();
|
||||
expect(FakeWebSocket.instances).toHaveLength(2);
|
||||
expect(FakeWebSocket.instances[0]?.readyState).toBe(FakeWebSocket.CLOSED);
|
||||
expect(states.at(-1)?.kind).toBe('streaming');
|
||||
|
||||
await settle(30_000);
|
||||
expect(FakeWebSocket.instances).toHaveLength(2);
|
||||
expect(states.at(-1)?.kind).toBe('streaming');
|
||||
session.stop();
|
||||
});
|
||||
|
||||
it('"Retry" starts a series without waiting for the interval, and nothing after stop()', async () => {
|
||||
const states: ViewerState[] = [];
|
||||
const session = newSession(states, { maxAttempts: 2 });
|
||||
session.start();
|
||||
await exhaust();
|
||||
goOnline();
|
||||
await exhaust();
|
||||
expect(FakeWebSocket.instances).toHaveLength(4);
|
||||
expect(states.at(-1)?.kind).toBe('failed');
|
||||
|
||||
host.up = true;
|
||||
expect(session.retry()).toBe(true);
|
||||
await settle();
|
||||
expect(states.at(-1)?.kind).toBe('streaming');
|
||||
|
||||
session.stop();
|
||||
expect(session.retry()).toBe(false);
|
||||
goOnline();
|
||||
await settle(WAKE_MIN_INTERVAL_MS);
|
||||
expect(FakeWebSocket.instances).toHaveLength(5);
|
||||
});
|
||||
|
||||
it('stop() removes the system listeners', async () => {
|
||||
const session = newSession([], { maxAttempts: 1 });
|
||||
session.start();
|
||||
await exhaust();
|
||||
session.stop();
|
||||
goOnline();
|
||||
fakeDocument.setVisibility('visible');
|
||||
connection.dispatchEvent(new Event('change'));
|
||||
await settle();
|
||||
expect(FakeWebSocket.instances).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('stable quality across reconnections', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
host.up = true;
|
||||
FakeWebSocket.instances = [];
|
||||
FakePeerConnection.instances = [];
|
||||
vi.stubGlobal('WebSocket', FakeWebSocket);
|
||||
vi.stubGlobal('RTCPeerConnection', FakePeerConnection);
|
||||
vi.stubGlobal('navigator', { userAgent: 'test', platform: 'test' });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
function qualityRequests(ws: FakeWebSocket): StreamSettings[] {
|
||||
return ws.sent.flatMap((message) =>
|
||||
message.type === 'quality_request' ? [message.settings] : [],
|
||||
);
|
||||
}
|
||||
|
||||
async function cutAndResume(states: ViewerState[]): Promise<void> {
|
||||
cut();
|
||||
await settle();
|
||||
host.up = true;
|
||||
await settle(1000);
|
||||
expect(states.at(-1)?.kind).toBe('streaming');
|
||||
}
|
||||
|
||||
it('three dropouts in a row keep the initial quality, never the minimum', async () => {
|
||||
const states: ViewerState[] = [];
|
||||
const session = newSession(states, { quality: SHARP });
|
||||
session.start();
|
||||
await settle();
|
||||
expect(states.at(-1)?.kind).toBe('streaming');
|
||||
|
||||
for (let i = 0; i < 3; i += 1) await cutAndResume(states);
|
||||
|
||||
expect(FakeWebSocket.instances).toHaveLength(4);
|
||||
for (const ws of FakeWebSocket.instances) {
|
||||
expect(qualityRequests(ws)).toEqual([SHARP]);
|
||||
// Requested after `welcome`, before the offer.
|
||||
const kinds = ws.sent.map((message) => message.type);
|
||||
expect(kinds).toEqual(['hello', 'quality_request', 'offer']);
|
||||
}
|
||||
// The host reply (its default setting) does not overwrite the choice.
|
||||
expect(session.requestedQuality).toEqual(SHARP);
|
||||
expect(session.requestedQuality).not.toEqual(SAVER);
|
||||
session.stop();
|
||||
});
|
||||
|
||||
it('the user last choice survives dropouts', async () => {
|
||||
const states: ViewerState[] = [];
|
||||
const session = newSession(states);
|
||||
session.start();
|
||||
await settle();
|
||||
expect(qualityRequests(lastSocket())).toEqual([]);
|
||||
|
||||
session.setQuality(SAVER);
|
||||
session.setQuality(SHARP);
|
||||
await settle();
|
||||
expect(qualityRequests(lastSocket())).toEqual([SAVER, SHARP]);
|
||||
|
||||
for (let i = 0; i < 3; i += 1) await cutAndResume(states);
|
||||
for (const ws of FakeWebSocket.instances.slice(1)) {
|
||||
expect(qualityRequests(ws)).toEqual([SHARP]);
|
||||
}
|
||||
expect(session.requestedQuality).toEqual(SHARP);
|
||||
session.stop();
|
||||
});
|
||||
|
||||
it('without a choice, no quality request: the host keeps its setting', async () => {
|
||||
const states: ViewerState[] = [];
|
||||
const session = newSession(states);
|
||||
session.start();
|
||||
await settle();
|
||||
for (let i = 0; i < 3; i += 1) await cutAndResume(states);
|
||||
for (const ws of FakeWebSocket.instances) {
|
||||
expect(qualityRequests(ws)).toEqual([]);
|
||||
}
|
||||
session.stop();
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,15 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { parseRoomLocation, signalingUrl } from './room';
|
||||
import {
|
||||
isCompleteCode,
|
||||
normalizeCode,
|
||||
parseRoomLocation,
|
||||
sessionFromScan,
|
||||
signalingUrl,
|
||||
} from './room';
|
||||
|
||||
describe('parseRoomLocation', () => {
|
||||
it('extrait la room et le jeton', () => {
|
||||
it('extracts the room and the token', () => {
|
||||
const result = parseRoomLocation('/r/abc234', '?t=0123456789abcdef0123456789abcdef');
|
||||
expect(result).toEqual({
|
||||
ok: true,
|
||||
@@ -11,11 +17,11 @@ describe('parseRoomLocation', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('refuse une adresse sans room', () => {
|
||||
it('rejects an address without a room', () => {
|
||||
expect(parseRoomLocation('/', '')).toEqual({ ok: false, reason: 'missing_room' });
|
||||
});
|
||||
|
||||
it('distingue un jeton absent d’un jeton mal formé', () => {
|
||||
it('tells a missing token from a malformed one', () => {
|
||||
expect(parseRoomLocation('/r/abc234', '')).toEqual({
|
||||
ok: false,
|
||||
reason: 'missing_token',
|
||||
@@ -26,14 +32,14 @@ describe('parseRoomLocation', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('refuse une room avec un caractère ambigu', () => {
|
||||
it('rejects a room with an ambiguous character', () => {
|
||||
expect(parseRoomLocation('/r/abc0o1', '?t=0123456789abcdef0123456789abcdef')).toEqual({
|
||||
ok: false,
|
||||
reason: 'malformed',
|
||||
});
|
||||
});
|
||||
|
||||
it('normalise une room en majuscules', () => {
|
||||
it('normalises an upper case room', () => {
|
||||
const result = parseRoomLocation('/r/ABC234', '?t=0123456789ABCDEF0123456789ABCDEF');
|
||||
expect(result).toEqual({
|
||||
ok: true,
|
||||
@@ -41,17 +47,69 @@ describe('parseRoomLocation', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('ignore les segments supplémentaires', () => {
|
||||
it('ignores extra segments', () => {
|
||||
const result = parseRoomLocation('/r/abc234/extra', '?t=0123456789abcdef0123456789abcdef');
|
||||
expect(result.ok).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('versioned link (#19)', () => {
|
||||
const token = '0123456789abcdef0123456789abcdef';
|
||||
|
||||
it('reads a version 1 link and its fingerprint', () => {
|
||||
const fp = 'ab'.repeat(32);
|
||||
const result = parseRoomLocation('/r/abc234', `?t=${token}&v=1`, `#fp=${fp}`);
|
||||
expect(result).toEqual({
|
||||
ok: true,
|
||||
value: { room: 'abc234', token, fingerprint: Array(32).fill('AB').join(':') },
|
||||
});
|
||||
});
|
||||
|
||||
it('accepts a link without version, the one of earlier releases', () => {
|
||||
expect(parseRoomLocation('/r/abc234', `?t=${token}`).ok).toBe(true);
|
||||
});
|
||||
|
||||
it('says a link comes from a newer version', () => {
|
||||
expect(parseRoomLocation('/r/abc234', `?t=${token}&v=2`)).toEqual({
|
||||
ok: false,
|
||||
reason: 'newer_link',
|
||||
});
|
||||
});
|
||||
|
||||
it('ignores a malformed fingerprint', () => {
|
||||
const result = parseRoomLocation('/r/abc234', `?t=${token}&v=1`, '#fp=zz');
|
||||
expect(result).toEqual({ ok: true, value: { room: 'abc234', token } });
|
||||
});
|
||||
});
|
||||
|
||||
describe('scanned QR code', () => {
|
||||
it('follows a session URL', () => {
|
||||
const url = 'http://192.168.1.20:8099/r/abc234?t=0123456789abcdef0123456789abcdef&v=1';
|
||||
expect(sessionFromScan(url)).toBe(url);
|
||||
});
|
||||
|
||||
it('rejects what is not a session', () => {
|
||||
expect(sessionFromScan('hello')).toBeNull();
|
||||
expect(sessionFromScan('javascript:alert(1)')).toBeNull();
|
||||
expect(sessionFromScan('https://example.com/')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('short code', () => {
|
||||
it('is typed as it is shown', () => {
|
||||
expect(normalizeCode(' K7M 4PQ ')).toBe('k7m4pq');
|
||||
expect(normalizeCode('k7m-4pq')).toBe('k7m4pq');
|
||||
expect(isCompleteCode('k7m4pq')).toBe(true);
|
||||
expect(isCompleteCode('k7m4p')).toBe(false);
|
||||
expect(isCompleteCode('k7m4p0')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('signalingUrl', () => {
|
||||
it('suit le schéma de la page', () => {
|
||||
it('follows the page scheme', () => {
|
||||
expect(signalingUrl({ protocol: 'http:', host: '127.0.0.1:8099' })).toBe(
|
||||
'ws://127.0.0.1:8099/ws',
|
||||
);
|
||||
expect(signalingUrl({ protocol: 'https:', host: 'hote.local' })).toBe('wss://hote.local/ws');
|
||||
expect(signalingUrl({ protocol: 'https:', host: 'host.local' })).toBe('wss://host.local/ws');
|
||||
});
|
||||
});
|
||||
+64
-15
@@ -1,47 +1,96 @@
|
||||
/**
|
||||
* Lecture de la session dans l'URL.
|
||||
* Reading the session from the URL.
|
||||
*
|
||||
* Forme attendue: `/r/<room>?t=<jeton>`. Les deux valeurs sont validées ici
|
||||
* plutôt que dans les composants, pour qu'un test puisse les couvrir et qu'une
|
||||
* URL mal formée produise un message clair au lieu d'une session vide.
|
||||
* Expected form: `/r/<room>?t=<token>&v=<version>`, followed over HTTPS by
|
||||
* `#fp=<fingerprint>` (#19). Values are validated here rather than in the
|
||||
* components, so that a test can cover them and a malformed URL gives a clear
|
||||
* message instead of an empty session.
|
||||
*/
|
||||
|
||||
import { LINK_VERSION } from '../proto';
|
||||
|
||||
export type RoomLocation = {
|
||||
room: string;
|
||||
token: string;
|
||||
/** SHA-256 fingerprint of the certificate, as hex pairs, over HTTPS. */
|
||||
fingerprint?: string;
|
||||
};
|
||||
|
||||
export type RoomLocationResult =
|
||||
| { ok: true; value: RoomLocation }
|
||||
| { ok: false; reason: 'missing_room' | 'missing_token' | 'malformed' };
|
||||
| { ok: false; reason: 'missing_room' | 'missing_token' | 'malformed' | 'newer_link' };
|
||||
|
||||
/** Six caractères, alphabet sans ambiguïté, aligné sur `RoomId` côté Rust. */
|
||||
/** Six characters, unambiguous alphabet, aligned with `RoomId` on the Rust side. */
|
||||
const ROOM_PATTERN = /^[2-9a-hjkmnp-z]{6}$/;
|
||||
/** Jeton hexadécimal de 128 bits. */
|
||||
/** 128-bit hex token. */
|
||||
const TOKEN_PATTERN = /^[0-9a-f]{32}$/;
|
||||
|
||||
export function parseRoomLocation(pathname: string, search: string): RoomLocationResult {
|
||||
/** SHA-256 fingerprint: 64 hex digits. */
|
||||
const FINGERPRINT_PATTERN = /^[0-9a-f]{64}$/;
|
||||
|
||||
export function parseRoomLocation(pathname: string, search: string, hash = ''): RoomLocationResult {
|
||||
const segments = pathname.split('/').filter(Boolean);
|
||||
// Deux formes acceptées: `/r/<room>` et `/<room>`. Le préfixe `r` évite de
|
||||
// confondre une room avec un chemin d'asset servi par le même serveur.
|
||||
// Two accepted forms: `/r/<room>` and `/<room>`. The `r` prefix avoids
|
||||
// mistaking a room for an asset path served by the same server.
|
||||
const raw = segments[0] === 'r' ? segments[1] : segments[0];
|
||||
if (!raw) {
|
||||
return { ok: false, reason: 'missing_room' };
|
||||
}
|
||||
// L'hôte normalise en minuscules; on fait pareil pour qu'une URL recopiée à
|
||||
// la main fonctionne malgré une majuscule.
|
||||
// The host normalises to lower case; so does this, so that a URL copied by
|
||||
// hand works despite a capital letter.
|
||||
const room = raw.toLowerCase();
|
||||
const token = (new URLSearchParams(search).get('t') ?? '').toLowerCase();
|
||||
const params = new URLSearchParams(search);
|
||||
// Without `v`, it is a link from 0.4 or earlier: same format as version
|
||||
// 1. A newer version says so, instead of being misread.
|
||||
const version = Number(params.get('v') ?? '1');
|
||||
if (!Number.isInteger(version) || version < 1) {
|
||||
return { ok: false, reason: 'malformed' };
|
||||
}
|
||||
if (version > LINK_VERSION) {
|
||||
return { ok: false, reason: 'newer_link' };
|
||||
}
|
||||
const token = (params.get('t') ?? '').toLowerCase();
|
||||
if (!token) {
|
||||
return { ok: false, reason: 'missing_token' };
|
||||
}
|
||||
if (!ROOM_PATTERN.test(room) || !TOKEN_PATTERN.test(token)) {
|
||||
return { ok: false, reason: 'malformed' };
|
||||
}
|
||||
return { ok: true, value: { room, token } };
|
||||
const fp = new URLSearchParams(hash.replace(/^#/, '')).get('fp')?.toLowerCase();
|
||||
const value: RoomLocation = { room, token };
|
||||
if (fp && FINGERPRINT_PATTERN.test(fp)) {
|
||||
value.fingerprint = fp.match(/../g)?.join(':').toUpperCase();
|
||||
}
|
||||
return { ok: true, value };
|
||||
}
|
||||
|
||||
/** URL du canal de signalement, qui suit le schéma de la page. */
|
||||
/**
|
||||
* The path to open for a scanned QR code, or `null` if it does not carry a
|
||||
* rustscreen session. Only `http` and `https` are followed: a QR code can
|
||||
* contain anything.
|
||||
*/
|
||||
export function sessionFromScan(text: string): string | null {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(text.trim());
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (url.protocol !== 'http:' && url.protocol !== 'https:') return null;
|
||||
const parsed = parseRoomLocation(url.pathname, url.search, url.hash);
|
||||
return parsed.ok ? url.href : null;
|
||||
}
|
||||
|
||||
/** Short code typed by hand: six characters of the room alphabet. */
|
||||
export function normalizeCode(input: string): string {
|
||||
return input.replace(/[\s-]/g, '').toLowerCase();
|
||||
}
|
||||
|
||||
export function isCompleteCode(code: string): boolean {
|
||||
return ROOM_PATTERN.test(code);
|
||||
}
|
||||
|
||||
/** URL of the signalling channel, which follows the page scheme. */
|
||||
export function signalingUrl(location: { protocol: string; host: string }): string {
|
||||
const scheme = location.protocol === 'https:' ? 'wss' : 'ws';
|
||||
return `${scheme}://${location.host}/ws`;
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import {
|
||||
displayedArea,
|
||||
nextRotation,
|
||||
readMirror,
|
||||
readRotation,
|
||||
rotatedBox,
|
||||
saveMirror,
|
||||
} from './rotation';
|
||||
|
||||
function memory(initial: Record<string, string> = {}) {
|
||||
const values = new Map(Object.entries(initial));
|
||||
return {
|
||||
values,
|
||||
getItem: (k: string) => values.get(k) ?? null,
|
||||
setItem: (k: string, v: string) => void values.set(k, v),
|
||||
removeItem: (k: string) => void values.delete(k),
|
||||
};
|
||||
}
|
||||
|
||||
describe('rotation (#30)', () => {
|
||||
it('makes a full turn in steps of 90 degrees', () => {
|
||||
expect(nextRotation(0)).toBe(90);
|
||||
expect(nextRotation(270)).toBe(0);
|
||||
});
|
||||
|
||||
it('swaps the box width and height on a quarter turn', () => {
|
||||
expect(rotatedBox(1000, 600, 90)).toMatchObject({ width: 600, height: 1000 });
|
||||
expect(rotatedBox(1000, 600, 180)).toMatchObject({ width: 1000, height: 600 });
|
||||
expect(rotatedBox(1000, 600, 270).transform).toContain('rotate(270deg)');
|
||||
});
|
||||
|
||||
it('keeps the whole picture and fills the stage in portrait', () => {
|
||||
// Tablet in portrait (800×1280), shared screen at 1920×1080.
|
||||
const stage = { width: 800, height: 1280 };
|
||||
const video = { width: 1920, height: 1080 };
|
||||
const upright = displayedArea(stage, video, 0);
|
||||
const turned = displayedArea(stage, video, 90);
|
||||
// Without rotation, the picture (800×450) fills barely more than a third of the stage.
|
||||
expect((upright.width * upright.height) / (800 * 1280)).toBeLessThan(0.36);
|
||||
// Turned, it fits whole and takes the full available height.
|
||||
expect(turned.width).toBeLessThanOrEqual(800);
|
||||
expect(turned.height).toBeLessThanOrEqual(1280);
|
||||
expect(Math.max(turned.width / 800, turned.height / 1280)).toBeCloseTo(1);
|
||||
// Turned (720×1280), it fills 90 % of it: the bars stay thin.
|
||||
expect((turned.width * turned.height) / (800 * 1280)).toBeGreaterThan(0.89);
|
||||
});
|
||||
|
||||
it('ignores an invalid stored value', () => {
|
||||
expect(readRotation(memory({ 'rustscreen.rotation': '45' }))).toBe(0);
|
||||
expect(readRotation(memory({ 'rustscreen.rotation': '270' }))).toBe(270);
|
||||
});
|
||||
});
|
||||
|
||||
describe('mirror (#29)', () => {
|
||||
it('flips the picture in screen space, after the rotation', () => {
|
||||
expect(rotatedBox(1000, 600, 90, true).transform).toBe(
|
||||
'translate(-50%, -50%) scaleX(-1) rotate(90deg)',
|
||||
);
|
||||
expect(rotatedBox(1000, 600, 0, false).transform).not.toContain('scaleX');
|
||||
});
|
||||
|
||||
it('is kept by the device', () => {
|
||||
const storage = memory();
|
||||
expect(readMirror(storage)).toBe(false);
|
||||
saveMirror(true, storage);
|
||||
expect(readMirror(storage)).toBe(true);
|
||||
});
|
||||
|
||||
it('migrates the choice stored before #83', () => {
|
||||
const storage = memory({ 'rustscreen.miroir': '1' });
|
||||
expect(readMirror(storage)).toBe(true);
|
||||
expect(storage.values.get('rustscreen.mirror')).toBe('1');
|
||||
expect(storage.values.has('rustscreen.miroir')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* Rotation of the stream in the viewer (#30), in steps of 90 degrees.
|
||||
*
|
||||
* A video turned a quarter turn swaps its width and height: the element is
|
||||
* therefore given the box of the turned stage, then rotated.
|
||||
* `object-fit: contain` keeps the whole picture in that box, cropping nothing
|
||||
* and with no bars wider than needed. Everything happens in the page: no
|
||||
* message to the host, no reconnection.
|
||||
*/
|
||||
import { browserStorage, type KeyValueStore, readMigrated } from './storage';
|
||||
|
||||
export type Rotation = 0 | 90 | 180 | 270;
|
||||
|
||||
const KEY = 'rustscreen.rotation';
|
||||
|
||||
export function nextRotation(rotation: Rotation): Rotation {
|
||||
return ((rotation + 90) % 360) as Rotation;
|
||||
}
|
||||
|
||||
/**
|
||||
* Size and transform of the video element in a `width`×`height` stage.
|
||||
*
|
||||
* The mirror (#29) applies in screen space, after the rotation: text reads
|
||||
* backwards for whoever looks at the screen, and the right way round in a
|
||||
* teleprompter's reflection, whatever the tablet's orientation.
|
||||
*/
|
||||
export function rotatedBox(
|
||||
width: number,
|
||||
height: number,
|
||||
rotation: Rotation,
|
||||
mirror = false,
|
||||
): { width: number; height: number; transform: string } {
|
||||
const quarter = rotation === 90 || rotation === 270;
|
||||
return {
|
||||
width: quarter ? height : width,
|
||||
height: quarter ? width : height,
|
||||
transform: `translate(-50%, -50%)${mirror ? ' scaleX(-1)' : ''} rotate(${rotation}deg)`,
|
||||
};
|
||||
}
|
||||
|
||||
const MIRROR_KEY = 'rustscreen.mirror';
|
||||
/** Key before #83. */
|
||||
const LEGACY_MIRROR_KEY = 'rustscreen.miroir';
|
||||
|
||||
export function readMirror(storage: KeyValueStore | null = browserStorage()): boolean {
|
||||
try {
|
||||
return storage !== null && readMigrated(storage, MIRROR_KEY, LEGACY_MIRROR_KEY) === '1';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function saveMirror(
|
||||
mirror: boolean,
|
||||
storage: KeyValueStore | null = browserStorage(),
|
||||
): void {
|
||||
try {
|
||||
storage?.setItem(MIRROR_KEY, mirror ? '1' : '0');
|
||||
} catch {
|
||||
// Private browsing: the choice holds for the page only.
|
||||
}
|
||||
}
|
||||
|
||||
type Size = { width: number; height: number };
|
||||
|
||||
/**
|
||||
* Part of the stage the picture fills, to check that no rotation wastes
|
||||
* space: it is what `contain` shows in the turned box.
|
||||
*/
|
||||
export function displayedArea(stage: Size, video: Size, rotation: Rotation): Size {
|
||||
const quarter = rotation === 90 || rotation === 270;
|
||||
const [vw, vh] = quarter ? [video.height, video.width] : [video.width, video.height];
|
||||
const scale = Math.min(stage.width / vw, stage.height / vh);
|
||||
return { width: vw * scale, height: vh * scale };
|
||||
}
|
||||
|
||||
export function readRotation(storage: KeyValueStore | null = browserStorage()): Rotation {
|
||||
try {
|
||||
const value = Number(storage?.getItem(KEY));
|
||||
if (value === 90 || value === 180 || value === 270) return value;
|
||||
} catch {
|
||||
// Storage denied: no rotation.
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
export function saveRotation(
|
||||
rotation: Rotation,
|
||||
storage: KeyValueStore | null = browserStorage(),
|
||||
): void {
|
||||
try {
|
||||
storage?.setItem(KEY, String(rotation));
|
||||
} catch {
|
||||
// Same.
|
||||
}
|
||||
}
|
||||
@@ -1,41 +1,83 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { backoffDelay, isTerminal, messageFor } from './session';
|
||||
import { createTranslator } from './i18n';
|
||||
import { backoffDelay, isRetryable, isTerminal, messageFor, minimizeJitterBuffer } from './session';
|
||||
|
||||
describe('backoffDelay', () => {
|
||||
it('double à chaque tentative puis plafonne', () => {
|
||||
it('doubles at each attempt then caps', () => {
|
||||
expect(backoffDelay(1)).toBe(1000);
|
||||
expect(backoffDelay(2)).toBe(2000);
|
||||
expect(backoffDelay(3)).toBe(4000);
|
||||
expect(backoffDelay(10)).toBe(15_000);
|
||||
});
|
||||
|
||||
it('ne produit jamais de délai absurde sur une entrée nulle', () => {
|
||||
it('never gives an absurd delay on a zero input', () => {
|
||||
expect(backoffDelay(0)).toBe(1000);
|
||||
expect(backoffDelay(-5)).toBe(1000);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isTerminal', () => {
|
||||
it('reconnaît les refus définitifs', () => {
|
||||
it('recognises final refusals', () => {
|
||||
for (const code of ['bad_token', 'bad_version', 'room_full']) {
|
||||
expect(isTerminal(code)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('laisse une chance aux erreurs transitoires', () => {
|
||||
it('gives transient errors a chance', () => {
|
||||
for (const code of ['network', 'internal', 'protocol_violation']) {
|
||||
expect(isTerminal(code)).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('messageFor', () => {
|
||||
it('traduit un code connu', () => {
|
||||
expect(messageFor('bad_token')).toContain('jeton');
|
||||
describe('isRetryable', () => {
|
||||
it('offers a new series after a network give-up or a passing error', () => {
|
||||
expect(isRetryable('network')).toBe(true);
|
||||
expect(isRetryable('internal')).toBe(true);
|
||||
});
|
||||
|
||||
it('retombe sur un message réseau pour un code inconnu', () => {
|
||||
expect(messageFor('quelque_chose_de_nouveau')).toContain('Connexion perdue');
|
||||
it('restarts neither a refusal on principle nor a protocol error', () => {
|
||||
for (const code of [
|
||||
'bad_token',
|
||||
'bad_version',
|
||||
'room_full',
|
||||
'protocol_violation',
|
||||
'unsupported',
|
||||
]) {
|
||||
expect(isRetryable(code)).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('messageFor', () => {
|
||||
const t = createTranslator('fr', 'viewer', [
|
||||
{
|
||||
viewer: {
|
||||
networkFallback: 'Connexion perdue.',
|
||||
errors: { bad_token: 'Jeton refusé.', token_expired: 'Jeton expiré.' },
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
it('translates a known code', () => {
|
||||
expect(messageFor('bad_token', t)).toBe('Jeton refusé.');
|
||||
expect(messageFor('token_expired', t)).not.toBe(messageFor('bad_token', t));
|
||||
});
|
||||
|
||||
it('falls back to the network message for an unknown code (newer host)', () => {
|
||||
expect(messageFor('something_new', t)).toBe('Connexion perdue.');
|
||||
});
|
||||
});
|
||||
|
||||
describe('minimizeJitterBuffer (#86)', () => {
|
||||
it('sets the standard target when the browser has it, the older hint otherwise', () => {
|
||||
const standard = { jitterBufferTarget: null } as unknown as RTCRtpReceiver;
|
||||
minimizeJitterBuffer(standard);
|
||||
expect((standard as unknown as { jitterBufferTarget: number }).jitterBufferTarget).toBe(0);
|
||||
const older = { playoutDelayHint: null } as unknown as RTCRtpReceiver;
|
||||
minimizeJitterBuffer(older);
|
||||
expect((older as unknown as { playoutDelayHint: number }).playoutDelayHint).toBe(0);
|
||||
expect(() => minimizeJitterBuffer({} as RTCRtpReceiver)).not.toThrow();
|
||||
});
|
||||
});
|
||||
+292
-59
@@ -1,22 +1,39 @@
|
||||
/**
|
||||
* Cycle de vie d'une session spectateur: WebSocket de signalement, offre
|
||||
* WebRTC, affichage, reconnexion.
|
||||
* Lifecycle of a viewer session: signalling WebSocket, WebRTC offer, display,
|
||||
* reconnection.
|
||||
*
|
||||
* Le composant React ne connaît que deux choses: un état à afficher et un flux
|
||||
* à poser dans une balise vidéo. Toute la mécanique vit ici, ce qui la rend
|
||||
* testable et évite les états incohérents du genre « connecté sans image ».
|
||||
* The React component knows only two things: a state to show and a stream to
|
||||
* put in a video element. All the machinery lives here, which makes it
|
||||
* testable and avoids inconsistent states such as "connected without picture".
|
||||
*/
|
||||
|
||||
import type {
|
||||
ClientMessage,
|
||||
DeviceInfo,
|
||||
ServerMessage,
|
||||
SourceInfo,
|
||||
StreamSettings,
|
||||
} from '../proto';
|
||||
import { PROTOCOL_VERSION } from '../proto';
|
||||
import type { ClientMessage, DeviceInfo, ServerMessage } from '../proto';
|
||||
import { errorMessages, strings } from '../strings';
|
||||
import { deviceId } from './device';
|
||||
import { cleanName, readName, suggestedName } from './deviceName';
|
||||
import type { Translate } from './i18n';
|
||||
import { type WakeReason, watchLifecycle } from './lifecycle';
|
||||
import { type DeviceKey, deviceKey, rememberTrust } from './trust';
|
||||
|
||||
export type ViewerErrorCode =
|
||||
| 'bad_token'
|
||||
| 'token_expired'
|
||||
/** The link was valid but another device used it first (#35). */
|
||||
| 'token_used'
|
||||
| 'bad_version'
|
||||
| 'room_full'
|
||||
| 'protocol_violation'
|
||||
| 'internal'
|
||||
| 'kicked'
|
||||
| 'share_ended'
|
||||
/** Came back by its key, and the host does not (or no longer) trust it (#34). */
|
||||
| 'not_trusted'
|
||||
| 'network'
|
||||
| 'unsupported';
|
||||
|
||||
@@ -25,38 +42,81 @@ export type ViewerState =
|
||||
| { kind: 'negotiating' }
|
||||
| { kind: 'streaming' }
|
||||
| { kind: 'reconnecting'; attempt: number; delayMs: number }
|
||||
| { kind: 'failed'; code: ViewerErrorCode; message: string }
|
||||
| { kind: 'failed'; code: ViewerErrorCode }
|
||||
| { kind: 'ended'; reason: string };
|
||||
|
||||
export type SessionOptions = {
|
||||
room: string;
|
||||
token: string;
|
||||
/** The link's room and token; both `null` for a trusted device without a link (#34). */
|
||||
room: string | null;
|
||||
token: string | null;
|
||||
/** Key of this device; by default the one kept by the browser, drawn if needed. */
|
||||
key?: DeviceKey | null;
|
||||
wsUrl: string;
|
||||
deviceName?: string;
|
||||
maxAttempts?: number;
|
||||
/**
|
||||
* Quality requested by the viewer. It is sent again after every
|
||||
* `welcome`, resumes included: a dropout never degrades it.
|
||||
*/
|
||||
quality?: StreamSettings;
|
||||
/** Listens to network, visibility and `pageshow` (default: yes). */
|
||||
watchLifecycle?: boolean;
|
||||
onState: (state: ViewerState) => void;
|
||||
onStream: (stream: MediaStream | null) => void;
|
||||
/** The host switched source during the share (#26): the stream stays. */
|
||||
onSourceChanged?: (source: SourceInfo) => void;
|
||||
};
|
||||
|
||||
/** Codes après lesquels réessayer ne sert à rien: l'hôte refuse par principe. */
|
||||
const TERMINAL_CODES: ReadonlySet<string> = new Set(['bad_token', 'bad_version', 'room_full']);
|
||||
/** Codes after which retrying is useless: the host refuses on principle. */
|
||||
const TERMINAL_CODES: ReadonlySet<string> = new Set([
|
||||
'bad_token',
|
||||
'token_expired',
|
||||
'token_used',
|
||||
'bad_version',
|
||||
'room_full',
|
||||
'kicked',
|
||||
'share_ended',
|
||||
'not_trusted',
|
||||
]);
|
||||
|
||||
/**
|
||||
* Codes after which a new series of attempts can help: the network or the
|
||||
* host may have come back. The "Retry" button and wake-ups use them.
|
||||
*/
|
||||
const RETRYABLE_CODES: ReadonlySet<string> = new Set(['network', 'internal']);
|
||||
|
||||
const DEFAULT_MAX_ATTEMPTS = 6;
|
||||
const MAX_BACKOFF_MS = 15_000;
|
||||
|
||||
/** Délai avant la n-ième tentative, plafonné. Fonction pure, testée. */
|
||||
/**
|
||||
* Minimum gap between two restarts triggered by the system. Switching from
|
||||
* Wi-Fi to Ethernet fires `online` and `change` almost together, a wake-up
|
||||
* fires `visibilitychange` and sometimes `pageshow`: one restart is enough.
|
||||
*/
|
||||
export const WAKE_MIN_INTERVAL_MS = 2000;
|
||||
|
||||
/** Delay before the n-th attempt, capped. Pure function, tested. */
|
||||
export function backoffDelay(attempt: number): number {
|
||||
const safe = Math.max(1, attempt);
|
||||
return Math.min(1000 * 2 ** (safe - 1), MAX_BACKOFF_MS);
|
||||
}
|
||||
|
||||
/** Un code d'erreur d'hôte est-il définitif ? Fonction pure, testée. */
|
||||
/** Is a host error code final? Pure function, tested. */
|
||||
export function isTerminal(code: string): boolean {
|
||||
return TERMINAL_CODES.has(code);
|
||||
}
|
||||
|
||||
export function messageFor(code: string): string {
|
||||
return errorMessages[code] ?? strings.networkFallback;
|
||||
/** Can a new series of attempts help? Pure function, tested. */
|
||||
export function isRetryable(code: string): boolean {
|
||||
return RETRYABLE_CODES.has(code);
|
||||
}
|
||||
|
||||
/**
|
||||
* The message for an error code, in the language of `t`. A code this viewer
|
||||
* does not know (newer host) becomes the generic network message.
|
||||
*/
|
||||
export function messageFor(code: string, t: Translate): string {
|
||||
return t(`errors.${code}`) || t('networkFallback');
|
||||
}
|
||||
|
||||
export class ViewerSession {
|
||||
@@ -64,36 +124,138 @@ export class ViewerSession {
|
||||
private pc: RTCPeerConnection | null = null;
|
||||
private retryTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private attempt = 0;
|
||||
private readonly key: DeviceKey | null;
|
||||
/** Final stop: unmount, refusal on principle, end of session. */
|
||||
private stopped = false;
|
||||
/**
|
||||
* Temporary give-up: attempts exhausted or transient host error. The
|
||||
* "Retry" button or a system wake-up starts a new series.
|
||||
*/
|
||||
private halted = false;
|
||||
private streaming = false;
|
||||
private started = false;
|
||||
private lastWakeAt = Number.NEGATIVE_INFINITY;
|
||||
private quality: StreamSettings | null;
|
||||
private unwatch: (() => void) | null = null;
|
||||
private readonly maxAttempts: number;
|
||||
|
||||
constructor(private readonly options: SessionOptions) {
|
||||
this.maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
|
||||
this.quality = options.quality ?? null;
|
||||
this.key = options.key === undefined ? deviceKey() : options.key;
|
||||
}
|
||||
|
||||
start(): void {
|
||||
if (this.stopped) return;
|
||||
if (this.stopped || this.started) return;
|
||||
this.started = true;
|
||||
if (typeof RTCPeerConnection === 'undefined') {
|
||||
this.options.onState({
|
||||
kind: 'failed',
|
||||
code: 'unsupported',
|
||||
message: strings.unsupported,
|
||||
});
|
||||
this.stopped = true;
|
||||
this.options.onState({ kind: 'failed', code: 'unsupported' });
|
||||
return;
|
||||
}
|
||||
if (this.options.watchLifecycle !== false) {
|
||||
this.unwatch = watchLifecycle((reason) => this.wake(reason));
|
||||
}
|
||||
this.connect();
|
||||
}
|
||||
|
||||
/** Idempotent: appelable depuis un nettoyage React, un unmount, un bouton. */
|
||||
/** Idempotent: callable from a React cleanup, an unmount, a button. */
|
||||
stop(): void {
|
||||
this.stopped = true;
|
||||
this.unwatch?.();
|
||||
this.unwatch = null;
|
||||
this.clearRetryTimer();
|
||||
this.teardown();
|
||||
this.options.onStream(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* "Retry" button: after a give-up, starts a full series of attempts again,
|
||||
* without reloading the page. Returns `false` if the session is stopped for
|
||||
* good (refusal on principle, end): a new one must then be created.
|
||||
*/
|
||||
retry(): boolean {
|
||||
if (this.stopped || !this.started) return false;
|
||||
if (this.halted) this.restartSeries();
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* The system signals that the network or the device is back. Restarts at
|
||||
* once if the session is waiting (retry timer), has given up, or holds an
|
||||
* already dead transport; leaves a working session alone.
|
||||
*
|
||||
* Guards against a loop: at most one restart per `WAKE_MIN_INTERVAL_MS`, a
|
||||
* restart while waiting counts as an attempt, and after a give-up a restart
|
||||
* opens ONE series, which ends again in the failed state if the host stays
|
||||
* away.
|
||||
*
|
||||
* Returns `true` if a connection was restarted.
|
||||
*/
|
||||
wake(_reason?: WakeReason): boolean {
|
||||
if (this.stopped || !this.started) return false;
|
||||
const now = Date.now();
|
||||
if (now - this.lastWakeAt < WAKE_MIN_INTERVAL_MS) return false;
|
||||
|
||||
if (this.halted) {
|
||||
this.lastWakeAt = now;
|
||||
this.restartSeries();
|
||||
return true;
|
||||
}
|
||||
if (this.retryTimer !== null) {
|
||||
this.lastWakeAt = now;
|
||||
this.clearRetryTimer();
|
||||
this.connect();
|
||||
return true;
|
||||
}
|
||||
if (this.transportDead()) {
|
||||
this.lastWakeAt = now;
|
||||
if (this.streaming) {
|
||||
this.streaming = false;
|
||||
this.attempt = 0;
|
||||
}
|
||||
this.connect();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the requested quality. It is sent at once if signalling is open,
|
||||
* and sent again at every resume.
|
||||
*/
|
||||
setQuality(settings: StreamSettings): void {
|
||||
this.quality = settings;
|
||||
this.send({ type: 'quality_request', settings } as ClientMessage);
|
||||
}
|
||||
|
||||
/** Quality the viewer requests, as they chose it. */
|
||||
get requestedQuality(): StreamSettings | null {
|
||||
return this.quality;
|
||||
}
|
||||
|
||||
private restartSeries(): void {
|
||||
this.halted = false;
|
||||
this.attempt = 0;
|
||||
this.clearRetryTimer();
|
||||
this.connect();
|
||||
}
|
||||
|
||||
private clearRetryTimer(): void {
|
||||
if (this.retryTimer !== null) {
|
||||
clearTimeout(this.retryTimer);
|
||||
this.retryTimer = null;
|
||||
}
|
||||
this.teardown();
|
||||
this.options.onStream(null);
|
||||
}
|
||||
|
||||
/** Closed signalling or a dropped WebRTC connection, with no resume planned. */
|
||||
private transportDead(): boolean {
|
||||
const ws = this.ws;
|
||||
if (!ws || ws.readyState === WebSocket.CLOSING || ws.readyState === WebSocket.CLOSED) {
|
||||
return true;
|
||||
}
|
||||
const state = this.pc?.connectionState;
|
||||
return state === 'failed' || state === 'disconnected';
|
||||
}
|
||||
|
||||
private connect(): void {
|
||||
@@ -110,26 +272,30 @@ export class ViewerSession {
|
||||
}
|
||||
this.ws = ws;
|
||||
|
||||
// Each listener checks it still talks to the current socket: the close
|
||||
// of an old socket arrives afterwards, and without this guard it would
|
||||
// cut the new connection that just replaced it.
|
||||
const current = () => !this.stopped && this.ws === ws;
|
||||
ws.addEventListener('open', () => {
|
||||
if (this.stopped) return;
|
||||
if (!current()) return;
|
||||
ws.send(JSON.stringify(this.hello()));
|
||||
});
|
||||
ws.addEventListener('message', (event) => {
|
||||
if (this.stopped) return;
|
||||
if (!current()) return;
|
||||
void this.onServerMessage(event.data);
|
||||
});
|
||||
ws.addEventListener('close', () => {
|
||||
if (this.stopped) return;
|
||||
if (!current()) return;
|
||||
this.onTransportLost();
|
||||
});
|
||||
ws.addEventListener('error', () => {
|
||||
// `close` suit toujours: on y traite la reconnexion.
|
||||
// `close` always follows: reconnection is handled there.
|
||||
});
|
||||
}
|
||||
|
||||
private hello(): ClientMessage {
|
||||
const device: DeviceInfo = {
|
||||
id: crypto.randomUUID(),
|
||||
id: deviceId(),
|
||||
name: this.options.deviceName ?? defaultDeviceName(),
|
||||
user_agent: navigator.userAgent,
|
||||
platform: navigator.platform ?? null,
|
||||
@@ -140,6 +306,7 @@ export class ViewerSession {
|
||||
room: this.options.room,
|
||||
token: this.options.token,
|
||||
device,
|
||||
key: this.key?.publicKey ?? null,
|
||||
} as ClientMessage;
|
||||
}
|
||||
|
||||
@@ -149,12 +316,31 @@ export class ViewerSession {
|
||||
try {
|
||||
message = JSON.parse(raw) as ServerMessage;
|
||||
} catch {
|
||||
this.fail('protocol_violation', messageFor('protocol_violation'));
|
||||
this.fail('protocol_violation');
|
||||
return;
|
||||
}
|
||||
|
||||
switch (message.type) {
|
||||
case 'challenge': {
|
||||
// The host trusts this key: prove it is here (#34).
|
||||
const signature = this.key?.sign(message.nonce);
|
||||
if (!signature) {
|
||||
this.fail('protocol_violation');
|
||||
return;
|
||||
}
|
||||
this.send({ type: 'proof', signature } as ClientMessage);
|
||||
break;
|
||||
}
|
||||
case 'trust':
|
||||
rememberTrust(message.trusted);
|
||||
break;
|
||||
case 'welcome':
|
||||
rememberTrust(message.trusted);
|
||||
// The chosen quality survives resumes: the host starts again from
|
||||
// its default setting at every session, so it is asked again.
|
||||
if (this.quality) {
|
||||
this.send({ type: 'quality_request', settings: this.quality } as ClientMessage);
|
||||
}
|
||||
await this.negotiate();
|
||||
break;
|
||||
case 'answer':
|
||||
@@ -162,25 +348,32 @@ export class ViewerSession {
|
||||
try {
|
||||
await this.pc.setRemoteDescription({ type: 'answer', sdp: message.sdp });
|
||||
} catch {
|
||||
this.fail('protocol_violation', messageFor('protocol_violation'));
|
||||
this.fail('protocol_violation');
|
||||
}
|
||||
break;
|
||||
case 'error':
|
||||
if (message.code === 'not_trusted') rememberTrust(false);
|
||||
if (isTerminal(message.code)) {
|
||||
this.fail(message.code as ViewerErrorCode, messageFor(message.code));
|
||||
this.fail(message.code as ViewerErrorCode);
|
||||
} else {
|
||||
this.fail('internal', messageFor(message.code));
|
||||
this.fail('internal');
|
||||
}
|
||||
break;
|
||||
case 'bye':
|
||||
this.stop();
|
||||
this.options.onState({ kind: 'ended', reason: message.reason });
|
||||
break;
|
||||
case 'source_changed':
|
||||
case 'settings_applied':
|
||||
// What the host applies does not replace what the viewer
|
||||
// requests: otherwise the default setting sent back after a
|
||||
// resume would overwrite the user's choice.
|
||||
break;
|
||||
case 'source_changed':
|
||||
// The frames switch on the host side, in the same track: no
|
||||
// renegotiation, the full screen and the stats go on (#26).
|
||||
this.options.onSourceChanged?.(message.source);
|
||||
break;
|
||||
case 'ice_candidate':
|
||||
// Le flux est remplacé côté hôte; rien à faire ici avant l'issue
|
||||
// du changement de source à chaud.
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
@@ -191,14 +384,17 @@ export class ViewerSession {
|
||||
this.emit({ kind: 'negotiating' });
|
||||
const pc = new RTCPeerConnection({ iceServers: [] });
|
||||
this.pc = pc;
|
||||
const current = () => !this.stopped && this.pc === pc;
|
||||
|
||||
pc.addTransceiver('video', { direction: 'recvonly' });
|
||||
pc.addEventListener('track', (event) => {
|
||||
if (!current()) return;
|
||||
minimizeJitterBuffer(event.receiver);
|
||||
const [stream] = event.streams;
|
||||
this.options.onStream(stream ?? new MediaStream([event.track]));
|
||||
});
|
||||
pc.addEventListener('connectionstatechange', () => {
|
||||
if (this.stopped) return;
|
||||
if (!current()) return;
|
||||
if (pc.connectionState === 'connected') {
|
||||
this.streaming = true;
|
||||
this.attempt = 0;
|
||||
@@ -212,17 +408,24 @@ export class ViewerSession {
|
||||
const offer = await pc.createOffer();
|
||||
await pc.setLocalDescription(offer);
|
||||
await waitForIceGathering(pc, 3000);
|
||||
if (!current()) return;
|
||||
const sdp = pc.localDescription?.sdp;
|
||||
if (!sdp) {
|
||||
this.fail('protocol_violation', messageFor('protocol_violation'));
|
||||
this.fail('protocol_violation');
|
||||
return;
|
||||
}
|
||||
this.send({ type: 'offer', sdp } as ClientMessage);
|
||||
} catch {
|
||||
this.onTransportLost();
|
||||
if (current()) this.onTransportLost();
|
||||
}
|
||||
}
|
||||
|
||||
/** Tells the host the new name of this device (#36), right away if connected. */
|
||||
rename(name: string): void {
|
||||
const clean = cleanName(name) || suggestedName(navigator.userAgent);
|
||||
this.send({ type: 'rename', name: clean } as ClientMessage);
|
||||
}
|
||||
|
||||
private send(message: ClientMessage): void {
|
||||
if (this.ws?.readyState === WebSocket.OPEN) {
|
||||
this.ws.send(JSON.stringify(message));
|
||||
@@ -230,7 +433,7 @@ export class ViewerSession {
|
||||
}
|
||||
|
||||
private onTransportLost(): void {
|
||||
if (this.stopped) return;
|
||||
if (this.stopped || this.halted) return;
|
||||
this.teardown();
|
||||
if (this.streaming) {
|
||||
this.streaming = false;
|
||||
@@ -242,7 +445,7 @@ export class ViewerSession {
|
||||
private scheduleRetry(): void {
|
||||
if (this.stopped) return;
|
||||
if (this.attempt >= this.maxAttempts) {
|
||||
this.fail('network', messageFor('network'));
|
||||
this.fail('network');
|
||||
return;
|
||||
}
|
||||
const delayMs = backoffDelay(this.attempt);
|
||||
@@ -253,27 +456,38 @@ export class ViewerSession {
|
||||
}, delayMs);
|
||||
}
|
||||
|
||||
private fail(code: ViewerErrorCode, message: string): void {
|
||||
private fail(code: ViewerErrorCode): void {
|
||||
if (isRetryable(code)) {
|
||||
// Temporary give-up: the wake listeners stay attached to start a
|
||||
// new series when the network or the device comes back.
|
||||
this.halted = true;
|
||||
this.streaming = false;
|
||||
this.clearRetryTimer();
|
||||
this.teardown();
|
||||
this.options.onStream(null);
|
||||
this.emit({ kind: 'failed', code });
|
||||
return;
|
||||
}
|
||||
this.stop();
|
||||
this.options.onState({ kind: 'failed', code, message });
|
||||
this.options.onState({ kind: 'failed', code });
|
||||
}
|
||||
|
||||
private teardown(): void {
|
||||
if (this.ws) {
|
||||
this.ws.onopen = null;
|
||||
this.ws.onmessage = null;
|
||||
this.ws.onclose = null;
|
||||
this.ws.onerror = null;
|
||||
try {
|
||||
this.ws.close();
|
||||
} catch {
|
||||
// Une socket déjà fermée n'est pas une erreur.
|
||||
}
|
||||
const ws = this.ws;
|
||||
// Reset before `close()`: the listeners then see a socket that is no
|
||||
// longer the current one and ignore its close.
|
||||
this.ws = null;
|
||||
try {
|
||||
ws.close();
|
||||
} catch {
|
||||
// An already closed socket is not an error.
|
||||
}
|
||||
}
|
||||
if (this.pc) {
|
||||
this.pc.close();
|
||||
const pc = this.pc;
|
||||
this.pc = null;
|
||||
pc.close();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -281,7 +495,7 @@ export class ViewerSession {
|
||||
if (!this.stopped) this.options.onState(state);
|
||||
}
|
||||
|
||||
/** Statistiques de la piste entrante, pour l'affichage. */
|
||||
/** Statistics of the incoming track, for display. */
|
||||
async stats(): Promise<VideoStats | null> {
|
||||
const pc = this.pc;
|
||||
if (!pc) return null;
|
||||
@@ -314,11 +528,12 @@ export type VideoStats = {
|
||||
height: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Name shown to the host for this device. The values are data sent in the
|
||||
* `hello` and displayed by the host, kept as they were.
|
||||
*/
|
||||
function defaultDeviceName(): string {
|
||||
const ua = navigator.userAgent;
|
||||
if (/iPad|Tablet/i.test(ua)) return 'Tablette';
|
||||
if (/Mobile|Android/i.test(ua)) return 'Téléphone';
|
||||
return 'Navigateur';
|
||||
return readName() ?? suggestedName(navigator.userAgent);
|
||||
}
|
||||
|
||||
async function waitForIceGathering(pc: RTCPeerConnection, timeoutMs: number): Promise<void> {
|
||||
@@ -336,3 +551,21 @@ async function waitForIceGathering(pc: RTCPeerConnection, timeoutMs: number): Pr
|
||||
pc.addEventListener('icegatheringstatechange', check);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks the browser to hold as few frames as possible before display (#86).
|
||||
* Its jitter buffer is sized for calls over the Internet; on a local network
|
||||
* a screen share wants the frame on screen as soon as it is decoded.
|
||||
* `jitterBufferTarget` is the standard (Chrome 114+, Firefox 125+),
|
||||
* `playoutDelayHint` the older Chrome spelling. Unknown to the browser: no
|
||||
* effect.
|
||||
*/
|
||||
export function minimizeJitterBuffer(receiver: RTCRtpReceiver): void {
|
||||
const tunable = receiver as unknown as Record<string, unknown>;
|
||||
try {
|
||||
if ('jitterBufferTarget' in tunable) tunable.jitterBufferTarget = 0;
|
||||
else if ('playoutDelayHint' in tunable) tunable.playoutDelayHint = 0;
|
||||
} catch {
|
||||
// A browser refusing the value keeps its default.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* Choices kept by the browser in `localStorage`.
|
||||
*
|
||||
* Storage may be denied (private browsing): every caller then falls back to
|
||||
* a value that lasts for the page only.
|
||||
*
|
||||
* Keys used to be French (`rustscreen.appareil`, `rustscreen.miroir`...).
|
||||
* They were renamed to English, and a device that visited before keeps its
|
||||
* choices: `readMigrated` reads the old key once, writes the new one and
|
||||
* removes the old one. This matters most for the device id, which the host
|
||||
* uses to recognise a device it already admitted or banned.
|
||||
*/
|
||||
|
||||
export type KeyValueStore = Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>;
|
||||
|
||||
/** `window.localStorage`, or `null` when the browser denies it. */
|
||||
export function browserStorage(): Storage | null {
|
||||
try {
|
||||
return window.localStorage;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The value under `key`, or else the one under `legacyKey`, moved to `key`.
|
||||
*
|
||||
* `translate` maps an old value to the new one, `null` dropping it. The old
|
||||
* key is removed only once the new one is written: a failed write keeps the
|
||||
* old value for the next visit. May throw if reading is denied.
|
||||
*/
|
||||
export function readMigrated(
|
||||
storage: KeyValueStore,
|
||||
key: string,
|
||||
legacyKey: string,
|
||||
translate: (legacy: string) => string | null = (legacy) => legacy,
|
||||
): string | null {
|
||||
const current = storage.getItem(key);
|
||||
if (current !== null) return current;
|
||||
const legacy = storage.getItem(legacyKey);
|
||||
if (legacy === null) return null;
|
||||
const value = translate(legacy);
|
||||
if (value === null) return null;
|
||||
try {
|
||||
storage.setItem(key, value);
|
||||
storage.removeItem(legacyKey);
|
||||
} catch {
|
||||
// Write denied: the value still holds for this page.
|
||||
}
|
||||
return value;
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import type { KeyValueStore } from './storage';
|
||||
import { readTheme, saveTheme } from './theme';
|
||||
|
||||
function memory(): KeyValueStore {
|
||||
const values = new Map<string, string>();
|
||||
return {
|
||||
getItem: (key) => values.get(key) ?? null,
|
||||
setItem: (key, value) => {
|
||||
values.set(key, value);
|
||||
},
|
||||
removeItem: (key) => {
|
||||
values.delete(key);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('theme (#28)', () => {
|
||||
it('follows the system on first visit', () => {
|
||||
expect(readTheme(memory())).toBe('system');
|
||||
expect(readTheme(null)).toBe('system');
|
||||
});
|
||||
|
||||
it('keeps the device choice', () => {
|
||||
const storage = memory();
|
||||
saveTheme('dark', storage);
|
||||
expect(readTheme(storage)).toBe('dark');
|
||||
});
|
||||
|
||||
it('ignores an unknown value or a denied storage', () => {
|
||||
const storage = memory();
|
||||
storage.setItem('rustscreen.theme', 'violet');
|
||||
expect(readTheme(storage)).toBe('system');
|
||||
const denied = {
|
||||
getItem: () => {
|
||||
throw new Error('denied');
|
||||
},
|
||||
setItem: () => {
|
||||
throw new Error('denied');
|
||||
},
|
||||
removeItem: () => {
|
||||
throw new Error('denied');
|
||||
},
|
||||
};
|
||||
expect(readTheme(denied)).toBe('system');
|
||||
expect(() => saveTheme('light', denied)).not.toThrow();
|
||||
});
|
||||
|
||||
it('translates and rewrites a value stored before #83', () => {
|
||||
for (const [legacy, theme] of [
|
||||
['systeme', 'system'],
|
||||
['clair', 'light'],
|
||||
['sombre', 'dark'],
|
||||
] as const) {
|
||||
const storage = memory();
|
||||
storage.setItem('rustscreen.theme', legacy);
|
||||
expect(readTheme(storage)).toBe(theme);
|
||||
expect(storage.getItem('rustscreen.theme')).toBe(theme);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* Viewer theme (#28): the device's by default, light or dark on request. The
|
||||
* choice is kept by the device, not by the host: two tablets may prefer
|
||||
* opposite themes.
|
||||
*
|
||||
* The value is also the `data-theme` attribute of the root element, which
|
||||
* the style sheet reads.
|
||||
*/
|
||||
import { browserStorage, type KeyValueStore } from './storage';
|
||||
|
||||
export type Theme = 'system' | 'light' | 'dark';
|
||||
|
||||
const KEY = 'rustscreen.theme';
|
||||
/** The three themes, in the order the settings offer them. */
|
||||
export const THEMES: readonly Theme[] = ['system', 'light', 'dark'];
|
||||
/** Values stored before #83, under the same key. */
|
||||
const LEGACY_VALUES: Readonly<Record<string, Theme>> = {
|
||||
systeme: 'system',
|
||||
clair: 'light',
|
||||
sombre: 'dark',
|
||||
};
|
||||
|
||||
export function readTheme(storage: KeyValueStore | null = browserStorage()): Theme {
|
||||
try {
|
||||
const raw = storage?.getItem(KEY);
|
||||
if (raw && (THEMES as readonly string[]).includes(raw)) return raw as Theme;
|
||||
const migrated = raw ? LEGACY_VALUES[raw] : undefined;
|
||||
if (migrated) {
|
||||
saveTheme(migrated, storage);
|
||||
return migrated;
|
||||
}
|
||||
} catch {
|
||||
// Storage denied (private browsing): the system theme.
|
||||
}
|
||||
return 'system';
|
||||
}
|
||||
|
||||
export function saveTheme(theme: Theme, storage: KeyValueStore | null = browserStorage()): void {
|
||||
try {
|
||||
storage?.setItem(KEY, theme);
|
||||
} catch {
|
||||
// Same: the choice holds for the page only.
|
||||
}
|
||||
}
|
||||
|
||||
/** Sets the theme on the root element: the style sheet does the rest. */
|
||||
export function applyTheme(theme: Theme, root: HTMLElement = document.documentElement): void {
|
||||
root.dataset.theme = theme;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { deviceKey, fromSecret, isTrusted, rememberTrust } from './trust';
|
||||
|
||||
/** `rs_proto::trust::TEST_VECTOR`: the host checks the same four values. */
|
||||
const VECTOR = {
|
||||
secret: '9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60',
|
||||
publicKey: 'd75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a',
|
||||
nonce: '000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f',
|
||||
signature:
|
||||
'76d5c3961e096b67f6932039110292bb727a9475552afe48961c0073c653001e8fba219441d9795a9aa721224353aa589049d2d1050e0f37ce32b7953ea86f0e',
|
||||
};
|
||||
|
||||
function memory(): Map<string, string> & Storage {
|
||||
const map = new Map<string, string>();
|
||||
return Object.assign(map, {
|
||||
getItem: (k: string) => map.get(k) ?? null,
|
||||
setItem: (k: string, v: string) => void map.set(k, v),
|
||||
removeItem: (k: string) => void map.delete(k),
|
||||
}) as unknown as Map<string, string> & Storage;
|
||||
}
|
||||
|
||||
describe('device key', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('signs exactly what the host checks', () => {
|
||||
const key = fromSecret(VECTOR.secret);
|
||||
expect(key.publicKey).toBe(VECTOR.publicKey);
|
||||
expect(key.sign(VECTOR.nonce)).toBe(VECTOR.signature);
|
||||
});
|
||||
|
||||
it('refuses to sign a malformed nonce', () => {
|
||||
expect(fromSecret(VECTOR.secret).sign('zz')).toBeNull();
|
||||
});
|
||||
|
||||
it('is drawn once and kept', () => {
|
||||
const storage = memory();
|
||||
const first = deviceKey(storage);
|
||||
const second = deviceKey(storage);
|
||||
expect(first?.publicKey).toMatch(/^[0-9a-f]{64}$/);
|
||||
expect(second?.publicKey).toBe(first?.publicKey);
|
||||
});
|
||||
|
||||
it('works without crypto.subtle, as on a page served over HTTP on the LAN', () => {
|
||||
const random = globalThis.crypto.getRandomValues.bind(globalThis.crypto);
|
||||
vi.stubGlobal('crypto', { getRandomValues: random });
|
||||
expect(globalThis.crypto.subtle).toBeUndefined();
|
||||
const key = deviceKey(memory());
|
||||
expect(key?.sign(VECTOR.nonce)).toMatch(/^[0-9a-f]{128}$/);
|
||||
});
|
||||
|
||||
it('is absent when the browser keeps nothing', () => {
|
||||
expect(deviceKey(null)).toBeNull();
|
||||
const forgetful = {
|
||||
getItem: () => null,
|
||||
setItem: () => undefined,
|
||||
removeItem: () => undefined,
|
||||
};
|
||||
expect(deviceKey(forgetful)).toBeNull();
|
||||
});
|
||||
|
||||
it('remembers what the host said', () => {
|
||||
const storage = memory();
|
||||
expect(isTrusted(storage)).toBe(false);
|
||||
rememberTrust(true, storage);
|
||||
expect(isTrusted(storage)).toBe(true);
|
||||
rememberTrust(false, storage);
|
||||
expect(isTrusted(storage)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* The key of this device, to come back without a link once the host trusts
|
||||
* it (#34).
|
||||
*
|
||||
* The page is served over HTTP on the LAN, which is not a secure context:
|
||||
* `crypto.subtle` does not exist there, `crypto.getRandomValues()` does. The
|
||||
* Ed25519 signature is therefore done in JavaScript (`@noble/ed25519`,
|
||||
* bundled, no network), and the private key lives in `localStorage` for this
|
||||
* origin. It is never sent, never logged: the host receives the public key
|
||||
* and signatures only.
|
||||
*
|
||||
* What is signed is fixed here, not chosen by the host: the context
|
||||
* `rustscreen-trust-v1`, a zero byte, then the nonce of the challenge. It
|
||||
* mirrors `rs_proto::trust`, and both test suites check the same vector.
|
||||
*/
|
||||
import * as ed from '@noble/ed25519';
|
||||
import { sha512 } from '@noble/hashes/sha2.js';
|
||||
|
||||
import { browserStorage, type KeyValueStore } from './storage';
|
||||
|
||||
ed.hashes.sha512 = sha512;
|
||||
|
||||
const SECRET_KEY = 'rustscreen.key';
|
||||
/** Set once the host said it trusts this device: the home page then connects. */
|
||||
const TRUSTED_KEY = 'rustscreen.trusted';
|
||||
const CONTEXT = new TextEncoder().encode('rustscreen-trust-v1');
|
||||
const HEX_32 = /^[0-9a-f]{64}$/;
|
||||
|
||||
export type DeviceKey = {
|
||||
/** Public key, 64 hex digits: what the host keeps. */
|
||||
publicKey: string;
|
||||
/** Signs the nonce of a challenge (64 hex digits), or `null` if malformed. */
|
||||
sign(nonce: string): string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The key of this device, drawn on first use. `null` when the browser cannot
|
||||
* keep it (storage denied, or a browser too old for the signature code): the
|
||||
* device then goes through the link every time, as before #34.
|
||||
*/
|
||||
export function deviceKey(storage: KeyValueStore | null = browserStorage()): DeviceKey | null {
|
||||
if (!storage) return null;
|
||||
try {
|
||||
let secret = storage.getItem(SECRET_KEY);
|
||||
if (!secret || !HEX_32.test(secret)) {
|
||||
secret = toHex(ed.utils.randomSecretKey());
|
||||
storage.setItem(SECRET_KEY, secret);
|
||||
// Read back: a storage that accepts and forgets would draw a new
|
||||
// key on each visit, which the host could never trust.
|
||||
if (storage.getItem(SECRET_KEY) !== secret) return null;
|
||||
}
|
||||
return fromSecret(secret);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The key for a known secret: exported for the shared test vector. */
|
||||
export function fromSecret(secretHex: string): DeviceKey {
|
||||
const secret = fromHex(secretHex);
|
||||
return {
|
||||
publicKey: toHex(ed.getPublicKey(secret)),
|
||||
sign(nonce: string) {
|
||||
if (!HEX_32.test(nonce)) return null;
|
||||
const message = new Uint8Array(CONTEXT.length + 1 + 32);
|
||||
message.set(CONTEXT, 0);
|
||||
message.set(fromHex(nonce), CONTEXT.length + 1);
|
||||
return toHex(ed.sign(message, secret));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Did the host say, last time, that it trusts this device? */
|
||||
export function isTrusted(storage: KeyValueStore | null = browserStorage()): boolean {
|
||||
try {
|
||||
return storage?.getItem(TRUSTED_KEY) === '1';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Remembers what the host said, from the `welcome` or a `not_trusted`. */
|
||||
export function rememberTrust(trusted: boolean, storage: KeyValueStore | null = browserStorage()) {
|
||||
try {
|
||||
if (trusted) storage?.setItem(TRUSTED_KEY, '1');
|
||||
else storage?.removeItem(TRUSTED_KEY);
|
||||
} catch {
|
||||
// Storage denied: the home page will offer the code, as before.
|
||||
}
|
||||
}
|
||||
|
||||
function toHex(bytes: Uint8Array): string {
|
||||
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
|
||||
function fromHex(hex: string): Uint8Array {
|
||||
const bytes = new Uint8Array(hex.length / 2);
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
bytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
/**
|
||||
* True for `delayMs` after the last mouse move, touch or key press. The timer
|
||||
* is restarted only when needed: a moving mouse does not cause one render per
|
||||
* pixel.
|
||||
*/
|
||||
export function useActivity(delayMs: number, activeInitially = true): boolean {
|
||||
const [active, setActive] = useState(activeInitially);
|
||||
useEffect(() => {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const wake = () => {
|
||||
setActive(true);
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => setActive(false), delayMs);
|
||||
};
|
||||
const events = ['pointermove', 'pointerdown', 'keydown', 'touchstart'] as const;
|
||||
for (const e of events) window.addEventListener(e, wake, { passive: true });
|
||||
timer = setTimeout(() => setActive(false), delayMs);
|
||||
return () => {
|
||||
clearTimeout(timer);
|
||||
for (const e of events) window.removeEventListener(e, wake);
|
||||
};
|
||||
}, [delayMs]);
|
||||
return active;
|
||||
}
|
||||
@@ -1,13 +1,35 @@
|
||||
import { StrictMode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { App } from './App';
|
||||
import { I18nProvider, initialLanguage, loadCatalogs, loadLanguages } from './i18n';
|
||||
import { applyTheme, readTheme } from './lib/theme';
|
||||
import './styles.css';
|
||||
|
||||
const root = document.getElementById('root');
|
||||
if (!root) throw new Error('élément racine absent');
|
||||
// Before the first render: no white flash on a device set to dark.
|
||||
applyTheme(readTheme());
|
||||
|
||||
createRoot(root).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
);
|
||||
const root = document.getElementById('root');
|
||||
if (!root) throw new Error('root element missing');
|
||||
|
||||
async function start(element: HTMLElement) {
|
||||
const languages = await loadLanguages();
|
||||
const language = initialLanguage(languages);
|
||||
const catalogs = await loadCatalogs(language);
|
||||
if (catalogs.length === 0) {
|
||||
// Without texts, the interface cannot say anything: this one message
|
||||
// stays hard-coded, in both complete languages, for lack of better.
|
||||
element.textContent =
|
||||
'rustscreen: textes de l’interface introuvables, rechargez la page. / Interface texts not found, reload the page.';
|
||||
return;
|
||||
}
|
||||
document.documentElement.lang = language;
|
||||
createRoot(element).render(
|
||||
<StrictMode>
|
||||
<I18nProvider initial={{ language, catalogs }} languages={languages}>
|
||||
<App />
|
||||
</I18nProvider>
|
||||
</StrictMode>,
|
||||
);
|
||||
}
|
||||
|
||||
void start(root);
|
||||
@@ -5,6 +5,10 @@ import type { SessionToken } from "./SessionToken";
|
||||
import type { StreamSettings } from "./StreamSettings";
|
||||
|
||||
/**
|
||||
* Ce que le spectateur envoie à l'hôte.
|
||||
* What the viewer sends to the host.
|
||||
*/
|
||||
export type ClientMessage = { "type": "hello", version: number, room: RoomId, token: SessionToken, device: DeviceInfo, } | { "type": "offer", sdp: string, } | { "type": "ice_candidate", candidate: string, sdp_mid: string | null, sdp_mline_index: number | null, } | { "type": "quality_request", settings: StreamSettings, } | { "type": "bye" };
|
||||
export type ClientMessage = { "type": "hello", version: number, room: RoomId | null, token: SessionToken | null, device: DeviceInfo,
|
||||
/**
|
||||
* Ed25519 public key of the device, 64 hex digits. Never the private key.
|
||||
*/
|
||||
key: string | null, } | { "type": "proof", signature: string, } | { "type": "offer", sdp: string, } | { "type": "ice_candidate", candidate: string, sdp_mid: string | null, sdp_mline_index: number | null, } | { "type": "quality_request", settings: StreamSettings, } | { "type": "rename", name: string, } | { "type": "bye" };
|
||||
Loaded 100 of 252 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user