1 Commits
Author SHA1 Message Date
renovate-bot 7f637dcfd4 fix(deps): update rust crate libloading to 0.9.0
CI / Formatage, tests et builds (pull_request) Successful in 1m9s
2026-10-26 17:35:33 +00:00
268 changed files with 11484 additions and 23941 deletions

No files matched your search

+65 -123
View File
@@ -1,19 +1,20 @@
# rustscreen continuous integration.
# Chaîne d'intégration continue de rustscreen.
#
# 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.
# 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.
#
# Two precautions that cost a lot when forgotten:
# Deux précautions qui coûtent cher quand on les oublie :
#
# - 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.
# - 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.
name: CI
@@ -26,17 +27,17 @@ permissions:
contents: read
jobs:
integrate:
name: Formatting, tests and builds
integrer:
name: Formatage, tests et builds
runs-on: rustscreen-ci
steps:
- uses: actions/checkout@v7
- name: Tools and caches
- name: Outils et caches
run: |
set -euo pipefail
# Caches live outside the repository, in a directory specific to this
# project: the CI machine is shared with others.
# 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.
cache="${RUSTSCREEN_CACHE_DIR:-$HOME/.cache/rustscreen-ci}"
mkdir -p "$cache"
{
@@ -44,21 +45,11 @@ jobs:
echo "VPX_PREFIX=$cache/libvpx"
echo "npm_config_cache=$cache/npm"
} >> "$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
# 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: Versions
@@ -69,15 +60,15 @@ jobs:
cargo fmt --version
node --version
npm --version
nasm -v || echo "nasm missing: libvpx will be built without an assembler, slower encoding"
nasm -v || echo "nasm absent: libvpx sera construit sans assembleur, encodage plus lent"
- name: libvpx library
- name: Bibliothèque libvpx
run: |
set -euo pipefail
# The version is pinned by the script: beyond 1.13, the pre-generated
# bindings of `env-libvpx-sys` are no longer enough.
# 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.
if [ -f "$VPX_PREFIX/lib/libvpx.a" ]; then
echo "libvpx already built in $VPX_PREFIX"
echo "libvpx déjà construite dans $VPX_PREFIX"
else
./scripts/build-libvpx.sh "$VPX_PREFIX"
fi
@@ -87,136 +78,87 @@ jobs:
echo "VPX_VERSION=1.13.0"
} >> "$GITHUB_ENV"
- name: Viewer dependencies
- name: Dépendances du viewer
run: |
set -euo pipefail
cd apps/viewer
# `npm ci` rather than `npm install`: the lock file is the reference,
# the pipeline negotiates no version.
# `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 --no-audit --no-fund
- name: Viewer lint and types
- name: Lint et types du viewer
run: |
set -euo pipefail
cd apps/viewer
npm run lint
npx tsc --noEmit
- name: Viewer tests
- name: Tests du viewer
run: |
set -euo pipefail
cd apps/viewer
npm test
- name: Viewer bundle
- name: Bundle du viewer
run: |
set -euo pipefail
cd apps/viewer
npm run build
- 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
- name: Formatage
run: cargo fmt --all --check
- name: Clippy
run: cargo clippy --workspace --all-targets -- -D warnings
- name: Tests
# 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).
# Les tests `export_bindings` écrivent les types TypeScript: ils
# tournent ici, avec le reste, et l'étape « types à jour » ne fait
# plus que comparer. Une seconde invocation de cargo, aux features
# différentes, recompilait la moitié du workspace (34 s, #78).
run: cargo test --workspace
- name: Wayland capture (PipeWire)
- name: Capture Wayland (PipeWire)
run: |
set -euo pipefail
# 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).
# La feature exige libpipewire-0.3 et libclang (bindgen). Le runner ne
# les a pas toujours: sans elles, l'étape le dit et passe, la release
# se chargera d'échouer (voir 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"
echo "libpipewire-0.3 absente du runner: capture Wayland non vérifiée"
fi
- name: Hardware encoding (VA-API)
- name: Le binaire démarre
run: |
set -euo pipefail
# 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
# La chaîne ne se contente pas de tester : elle vérifie que le binaire
# démarre, parce qu'un produit qui ne démarre pas passe tous les tests
# unitaires. Les tests d'intégration l'ont déjà compilé.
"$CARGO_TARGET_DIR/debug/rustscreen" --version
- 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).
- name: Binaire de publication
# Sur main seulement: toute la pile en release coûte plus d'une minute,
# et la release la refait de toute façon (#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
cargo build --release -p rs-session --bin rustscreen
"$CARGO_TARGET_DIR/release/rustscreen" --version
- name: The TypeScript protocol is up to date
- name: Le protocole TypeScript est à jour
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
# 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.
# Écrits par l'étape « Tests »: il ne reste qu'à comparer. `status`
# plutôt que `diff`: un type nouveau, jamais commité, compte aussi.
ecarts=$(git status --porcelain -- apps/viewer/src/proto apps/desktop/src/bindings)
if [ -n "$ecarts" ]; then
echo "$ecarts" >&2
echo "types TypeScript générés pas à jour : lancer make proto et commiter" >&2
exit 1
fi
+50 -86
View File
@@ -1,15 +1,14 @@
# Release: a `vX.Y.Z` tag produces a release with its artifacts.
# Publication : une étiquette `vX.Y.Z` produit une release avec ses artefacts.
#
# 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.
# 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.
#
# 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.
# 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.
name: Release
@@ -22,20 +21,20 @@ permissions:
jobs:
release:
name: Packages and release
name: Paquets et release
runs-on: rustscreen-ci
steps:
- uses: actions/checkout@v7
with:
# `git describe` and the history since the previous tag need the
# tags, which a shallow clone does not fetch.
# `git describe` et l'historique depuis l'étiquette précédente ont
# besoin des étiquettes, que le clone superficiel ne prend pas.
fetch-depth: 0
- name: Tools and caches
- name: Outils et caches
run: |
set -euo pipefail
# Caches live outside the repository, in a directory specific to this
# project: the CI machine is shared with others.
# 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.
cache="${RUSTSCREEN_CACHE_DIR:-$HOME/.cache/rustscreen-ci}"
mkdir -p "$cache"
{
@@ -43,36 +42,26 @@ jobs:
echo "VPX_PREFIX=$cache/libvpx"
echo "npm_config_cache=$cache/npm"
} >> "$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
# 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 and tag
- name: Version et étiquette
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
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
exit 1
fi
echo "VERSION=$tag" >> "$GITHUB_ENV"
echo "version $tag confirmed"
echo "VERSION=$etiquette" >> "$GITHUB_ENV"
echo "version $etiquette confirmée"
- name: libvpx library
- name: Bibliothèque libvpx
run: |
set -euo pipefail
if [ ! -f "$VPX_PREFIX/lib/libvpx.a" ]; then
@@ -91,68 +80,43 @@ jobs:
npm ci --no-audit --no-fund
npm run build
- name: Binary
- name: Binaire
run: |
set -euo pipefail
# 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.
# Un binaire publié sans PipeWire ne capture rien sous Wayland, la
# cible du produit (ADR 0009): la release échoue plutôt que de le
# livrer. Le runner a besoin de libpipewire-0.3-dev et 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
echo "libpipewire-0.3 introuvable: installer libpipewire-0.3-dev et libclang-dev sur le 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
cargo build --release -p rs-session --features pipewire --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
- name: AppImage
run: |
set -euo pipefail
./scripts/build-appimage.sh
- name: .deb and .rpm
run: |
set -euo pipefail
./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.
# 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
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/
# `RELEASE_NOTES` désigne un fichier versionné quand il existe; sinon
# le script écrit une note minimale plutôt que d'échouer.
notes="docs/releases/${GITHUB_REF_NAME}.md"
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
if [ ! -f "$notes" ]; then
echo "pas de notes pour ${GITHUB_REF_NAME}, note minimale" >&2
export RELEASE_NOTES="$notes.absent"
fi
./scripts/publish-release.py "$GITHUB_REF_NAME" \
"dist-appimage/rustscreen-${VERSION}-x86_64.AppImage" \
"$CARGO_TARGET_DIR/release/rustscreen"
-1
View File
@@ -30,7 +30,6 @@ diag-*.zip
# Empaquetage local
dist-appimage/
dist-packages/
.cache/
SHA256SUMS
-70
View File
@@ -1,70 +0,0 @@
# 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\\)"
+27 -91
View File
@@ -14,38 +14,20 @@ dépendent pas d'un service en ligne.
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
spectateur, serveur local avec jeton qui expire et code court, 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.
Ce qui manque: la capture Windows et macOS, l'encodeur matériel, et la traduction des messages
produits par l'hôte (erreurs, avertissements), encore en français.
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.
L'hôte tient dans `rs-session::Hote`: démarrer, arrêter, déconnecter un spectateur, régler, et
publier l'état complet à chaque changement. La ligne de commande (`rs-session/src/bin/rustscreen.rs`)
et la coque (`apps/desktop/src-tauri`) ne font que le piloter: aucune des deux 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
@@ -69,7 +51,7 @@ la capture ni le serveur.
- **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
`scripts/verifier-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.
@@ -93,7 +75,7 @@ la capture ni le serveur.
- **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),
Windows demande DXGI ou
macOS exige la permission d'enregistrement d'écran et ScreenCaptureKit, 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.
@@ -123,34 +105,19 @@ 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.
**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
Le banc d'essai actuel est le binaire `rustscreen` 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-session --bin rustscreen-cli -- --synthetic --port 8099
cargo run -p rs-session --bin rustscreen -- --synthetic --port 8099
# ou rejeu d'un fichier encodé, sans encodeur
cargo run -p rs-session --bin rustscreen-cli -- spikes/str0m-mire/mire.ivf --port 8099
cargo run -p rs-session --bin rustscreen -- spikes/str0m-mire/mire.ivf --port 8099
```
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:
sinon des réglages (`~/.config/rustscreen/reglages.json`, partagés avec la coque). 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
@@ -159,50 +126,27 @@ 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
cargo run --release -p rs-session --features pipewire --bin rustscreen
# 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
cargo run --release -p rs-session --features pipewire --bin rustscreen -- --virtuel --size 1280x800
# archive de diagnostics, sans rien démarrer
cargo run -p rs-session --bin rustscreen-cli -- --diagnostics
cargo run -p rs-session --bin rustscreen -- --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
cargo run --release -p rs-session --features pipewire --bin rustscreen -- --codec vp9 --une-fenetre
```
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 # pnpm install, interface, puis binaire (target/release/rustscreen-desktop)
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
Le chemin se force avec `RUSTSCREEN_CAPTURE=portail|x11|synthetique`. 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).
@@ -213,16 +157,13 @@ Pour essayer la coque ou un navigateur sans rien ouvrir sur le bureau, préfére
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 journal JSON (`~/.local/state/rustscreen/logs`) nomme les étapes d'une session: `portail_accorde`,
`format_capture`, `session_ouverte`, `candidat_ice_retenu`, `premiere_image`, `changement_qualite`,
`deconnexion` (avec `cause`), `capture_revoquee`, et côté hôte `partage_demarre`, `partage_termine`,
`partage_interrompu`, `spectateur_deconnecte`, `changement_resolution`, `veille_inhibee`,
`veille_relachee`, `reveil_detecte`, `capture_relancee`, `adresse_changee`, `reglages_modifies`,
`acces_regenere`, `code_accepte`, `code_refuse`. 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:
@@ -267,10 +208,5 @@ session a révélés. Le détail est dans `docs/capture-wayland.md`; l'essentiel
- **`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`).
inodes de `/proc/self/fd` (voir le test `aucune_connexion_sortante`).
Generated
+14 -551
View File
@@ -125,12 +125,6 @@ version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
[[package]]
name = "atomic_refcell"
version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "21e4227379beff4205943696e6c3e0cd809bacdf3f0edd6e3dd153e2269571a4"
[[package]]
name = "autocfg"
version = "1.5.1"
@@ -272,7 +266,7 @@ dependencies = [
"bitflags",
"cexpr",
"clang-sys",
"itertools 0.13.0",
"itertools",
"proc-macro2",
"quote",
"regex",
@@ -547,32 +541,6 @@ dependencies = [
"cipher",
]
[[package]]
name = "curve25519-dalek"
version = "5.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23"
dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
"curve25519-dalek-derive",
"digest 0.11.3",
"fiat-crypto",
"rustc_version",
"subtle",
]
[[package]]
name = "curve25519-dalek-derive"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "data-encoding"
version = "2.11.1"
@@ -662,7 +630,7 @@ dependencies = [
"rand 0.9.5",
"rcgen",
"sec1",
"signature 2.2.0",
"signature",
"spki",
"subtle",
"time",
@@ -686,27 +654,6 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
[[package]]
name = "ed25519"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a"
dependencies = [
"signature 3.0.0",
]
[[package]]
name = "ed25519-dalek"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de"
dependencies = [
"curve25519-dalek",
"ed25519",
"sha2",
"subtle",
]
[[package]]
name = "either"
version = "1.19.0"
@@ -759,12 +706,6 @@ dependencies = [
"simd-adler32",
]
[[package]]
name = "fiat-crypto"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24"
[[package]]
name = "find-msvc-tools"
version = "0.1.15"
@@ -788,15 +729,6 @@ dependencies = [
"zlib-rs",
]
[[package]]
name = "flume"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e139bc46ca777eb5efaf62df0ab8cc5fd400866427e56c68b22e414e53bd3be"
dependencies = [
"spin",
]
[[package]]
name = "fnv"
version = "1.0.7"
@@ -849,34 +781,12 @@ version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
[[package]]
name = "futures-executor"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432"
dependencies = [
"futures-core",
"futures-task",
"futures-util",
]
[[package]]
name = "futures-io"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed"
[[package]]
name = "futures-macro"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "futures-sink"
version = "0.3.34"
@@ -896,7 +806,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
dependencies = [
"futures-core",
"futures-macro",
"futures-sink",
"futures-task",
"pin-project-lite",
@@ -988,202 +897,12 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "gio-sys"
version = "0.22.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c28739f914c15b87a9856000bed9cbd5b3a8afbca5e982d9a299e1601422cb5"
dependencies = [
"glib-sys",
"gobject-sys",
"libc",
"system-deps 9.0.1",
"windows-sys 0.61.2",
]
[[package]]
name = "glib"
version = "0.22.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4cf9e5bd8713f1990a92c422998826e0fb34824277b46bc59757373483c6694"
dependencies = [
"bitflags",
"futures-channel",
"futures-core",
"futures-executor",
"futures-task",
"futures-util",
"gio-sys",
"glib-macros",
"glib-sys",
"gobject-sys",
"libc",
"memchr",
"smallvec",
]
[[package]]
name = "glib-macros"
version = "0.22.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c9597c68fa7bdf4154a3079642cd21c4dccac0b0bdd2897d82861523bf91e7b9"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "glib-sys"
version = "0.22.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "99b38907e67e40dec9b60f858bcada952598719cb512a13eb13d6cdcd16f8295"
dependencies = [
"libc",
"system-deps 9.0.1",
]
[[package]]
name = "glob"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
[[package]]
name = "gobject-sys"
version = "0.22.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07595c9ba696bd9819cb6a8df39f08078f3dd679508fe052dd558492c2053834"
dependencies = [
"glib-sys",
"libc",
"system-deps 9.0.1",
]
[[package]]
name = "gstreamer"
version = "0.25.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4237e2066a25ecb7e54be6c066409e30615920265b9799b8d560ef8ac9857c6"
dependencies = [
"cfg-if",
"futures-channel",
"futures-core",
"futures-util",
"glib",
"gstreamer-sys",
"itertools 0.15.0",
"kstring",
"libc",
"muldiv",
"num-integer",
"num-rational",
"option-operations",
"pastey",
"pin-project-lite",
"smallvec",
"thiserror",
]
[[package]]
name = "gstreamer-app"
version = "0.25.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "97f8ae9238c2352398dcc084de28df3f7099af216ac6c160b52318d23f25c010"
dependencies = [
"futures-core",
"futures-sink",
"glib",
"gstreamer",
"gstreamer-app-sys",
"gstreamer-base",
"libc",
]
[[package]]
name = "gstreamer-app-sys"
version = "0.25.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0798b8aef6694341d40bb81edc759f8979b896b59f9f0f45d8cfa3bb7bf2e743"
dependencies = [
"glib-sys",
"gstreamer-base-sys",
"gstreamer-sys",
"libc",
"system-deps 9.0.1",
]
[[package]]
name = "gstreamer-base"
version = "0.25.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "17cbd8f59586a369c40d4b0d2f3a61cf9e9287b3cf5503cdcd8e7c5faa99265e"
dependencies = [
"atomic_refcell",
"cfg-if",
"glib",
"gstreamer",
"gstreamer-base-sys",
"libc",
]
[[package]]
name = "gstreamer-base-sys"
version = "0.25.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b05f77bfd76b5afee6b29c27dae19eaf5018b5cf8d0d17520f3de44c6385c32"
dependencies = [
"glib-sys",
"gobject-sys",
"gstreamer-sys",
"libc",
"system-deps 9.0.1",
]
[[package]]
name = "gstreamer-sys"
version = "0.25.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "436d9532847489a8285d57b8c3670762c12a18f777fdc2ab159b52e0e6f521b9"
dependencies = [
"cfg-if",
"glib-sys",
"gobject-sys",
"libc",
"system-deps 9.0.1",
]
[[package]]
name = "gstreamer-video"
version = "0.25.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ffe4d77b2a5e679973d9c6b6c052da8cda86b83f5c268872f8691fde693fde84"
dependencies = [
"cfg-if",
"futures-channel",
"glib",
"gstreamer",
"gstreamer-base",
"gstreamer-video-sys",
"libc",
"thiserror",
]
[[package]]
name = "gstreamer-video-sys"
version = "0.25.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef455da22edca97ac9299d682b868227f3d9217b303748ce0161b31ae82dc106"
dependencies = [
"glib-sys",
"gobject-sys",
"gstreamer-base-sys",
"gstreamer-sys",
"libc",
"system-deps 9.0.1",
]
[[package]]
name = "h2"
version = "0.4.20"
@@ -1383,15 +1102,6 @@ dependencies = [
"either",
]
[[package]]
name = "itertools"
version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc"
dependencies = [
"either",
]
[[package]]
name = "itoa"
version = "1.0.18"
@@ -1419,15 +1129,6 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "kstring"
version = "2.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "558bf9508a558512042d3095138b1f7b8fe90c5467d94f9f1da28b3731c5dbd1"
dependencies = [
"static_assertions",
]
[[package]]
name = "lazy_static"
version = "1.5.1"
@@ -1463,7 +1164,7 @@ dependencies = [
"libspa-sys",
"nom 8.0.0",
"rustix",
"system-deps 7.0.8",
"system-deps",
]
[[package]]
@@ -1474,7 +1175,7 @@ checksum = "3b6e17bdaf63ed0d5e4144022624032b41fd9733112e8c74ac26fc9bf1291924"
dependencies = [
"bindgen",
"cc",
"system-deps 7.0.8",
"system-deps",
]
[[package]]
@@ -1483,15 +1184,6 @@ version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "lock_api"
version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
dependencies = [
"scopeguard",
]
[[package]]
name = "log"
version = "0.4.34"
@@ -1522,20 +1214,6 @@ version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
[[package]]
name = "mdns-sd"
version = "0.21.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8562654710f72a9cbce4b0d5b7c366a2f94330ba1ce3740f15e932ea2d37b161"
dependencies = [
"fastrand",
"flume",
"if-addrs",
"mio",
"socket-pktinfo",
"socket2",
]
[[package]]
name = "memchr"
version = "2.8.3"
@@ -1600,7 +1278,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee"
dependencies = [
"libc",
"log",
"wasi",
"windows-sys 0.61.2",
]
@@ -1615,12 +1292,6 @@ dependencies = [
"pxfm",
]
[[package]]
name = "muldiv"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "956787520e75e9bd233246045d19f42fb73242759cc57fba9611d940ae96d4b0"
[[package]]
name = "nix"
version = "0.31.3"
@@ -1686,16 +1357,6 @@ dependencies = [
"num-traits",
]
[[package]]
name = "num-rational"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
dependencies = [
"num-integer",
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -1720,15 +1381,6 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "option-operations"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aca39cf52b03268400c16eeb9b56382ea3c3353409309b63f5c8f0b1faf42754"
dependencies = [
"pastey",
]
[[package]]
name = "ordered-stream"
version = "0.2.0"
@@ -1739,12 +1391,6 @@ dependencies = [
"pin-project-lite",
]
[[package]]
name = "pastey"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"
[[package]]
name = "pem"
version = "4.0.0"
@@ -1798,7 +1444,7 @@ checksum = "9ce653f53e63e5b93853218092ee9a8906a5d082c92f3f1db26316955dd63ce0"
dependencies = [
"bindgen",
"libspa-sys",
"system-deps 7.0.8",
"system-deps",
]
[[package]]
@@ -2004,36 +1650,30 @@ dependencies = [
[[package]]
name = "rs-capture"
version = "0.5.0"
version = "0.4.0"
dependencies = [
"pipewire",
"rs-proto",
"rustix",
"thiserror",
"tracing",
"windows-sys 0.61.2",
"x11rb",
]
[[package]]
name = "rs-codec"
version = "0.5.0"
version = "0.4.0"
dependencies = [
"env-libvpx-sys",
"gstreamer",
"gstreamer-app",
"gstreamer-video",
"rs-capture",
"rs-proto",
"thiserror",
"tokio",
"tracing",
"windows",
]
[[package]]
name = "rs-diag"
version = "0.5.0"
version = "0.4.0"
dependencies = [
"if-addrs",
"serde",
@@ -2047,7 +1687,7 @@ dependencies = [
[[package]]
name = "rs-platform"
version = "0.5.0"
version = "0.4.0"
dependencies = [
"futures-util",
"if-addrs",
@@ -2055,13 +1695,12 @@ dependencies = [
"thiserror",
"tokio",
"tracing",
"windows-sys 0.61.2",
"zbus",
]
[[package]]
name = "rs-proto"
version = "0.5.0"
version = "0.4.0"
dependencies = [
"serde",
"serde_json",
@@ -2071,9 +1710,8 @@ dependencies = [
[[package]]
name = "rs-rtc"
version = "0.5.0"
version = "0.4.0"
dependencies = [
"if-addrs",
"rs-codec",
"str0m",
"thiserror",
@@ -2083,12 +1721,10 @@ dependencies = [
[[package]]
name = "rs-session"
version = "0.5.0"
version = "0.4.0"
dependencies = [
"base64 0.23.1",
"ed25519-dalek",
"futures-util",
"hex",
"png",
"rs-capture",
"rs-codec",
@@ -2109,14 +1745,12 @@ dependencies = [
[[package]]
name = "rs-signaling"
version = "0.5.0"
version = "0.4.0"
dependencies = [
"axum",
"axum-server",
"ed25519-dalek",
"hex",
"image",
"mdns-sd",
"qrcode",
"rand 0.10.3",
"rcgen",
@@ -2131,12 +1765,11 @@ dependencies = [
"tokio",
"tower-http",
"tracing",
"ts-rs",
]
[[package]]
name = "rs-store"
version = "0.5.0"
version = "0.4.0"
dependencies = [
"rs-proto",
"serde",
@@ -2152,15 +1785,6 @@ version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
[[package]]
name = "rustc_version"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
dependencies = [
"semver",
]
[[package]]
name = "rusticata-macros"
version = "4.1.0"
@@ -2230,12 +1854,6 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
[[package]]
name = "scopeguard"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "sctp-proto"
version = "0.10.7"
@@ -2263,12 +1881,6 @@ dependencies = [
"zeroize",
]
[[package]]
name = "semver"
version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
[[package]]
name = "serde"
version = "1.0.229"
@@ -2425,12 +2037,6 @@ version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
[[package]]
name = "signature"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5"
[[package]]
name = "simd-adler32"
version = "0.3.10"
@@ -2449,17 +2055,6 @@ version = "1.16.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8"
[[package]]
name = "socket-pktinfo"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "612942246d0cc239cfd83af1dfd39be47f649208a3524e5e9da651910128e0ac"
dependencies = [
"libc",
"socket2",
"windows-sys 0.61.2",
]
[[package]]
name = "socket2"
version = "0.6.5"
@@ -2470,15 +2065,6 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "spin"
version = "0.9.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"
dependencies = [
"lock_api",
]
[[package]]
name = "spki"
version = "0.7.3"
@@ -2489,12 +2075,6 @@ dependencies = [
"der",
]
[[package]]
name = "static_assertions"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
[[package]]
name = "str0m"
version = "0.24.1"
@@ -2619,19 +2199,6 @@ dependencies = [
"version-compare",
]
[[package]]
name = "system-deps"
version = "9.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db551ad38aac61d5e0343e0eeeb0163be3115c4e23b6a025959570ee0c03c67d"
dependencies = [
"cfg-expr",
"heck",
"pkg-config",
"toml",
"version-compare",
]
[[package]]
name = "target-lexicon"
version = "0.13.5"
@@ -3179,107 +2746,12 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "windows"
version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
dependencies = [
"windows-collections",
"windows-core",
"windows-future",
"windows-numerics",
]
[[package]]
name = "windows-collections"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
dependencies = [
"windows-core",
]
[[package]]
name = "windows-core"
version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
dependencies = [
"windows-implement",
"windows-interface",
"windows-link",
"windows-result",
"windows-strings",
]
[[package]]
name = "windows-future"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
dependencies = [
"windows-core",
"windows-link",
"windows-threading",
]
[[package]]
name = "windows-implement"
version = "0.60.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "windows-interface"
version = "0.59.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-numerics"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
dependencies = [
"windows-core",
"windows-link",
]
[[package]]
name = "windows-result"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
dependencies = [
"windows-link",
]
[[package]]
name = "windows-strings"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
dependencies = [
"windows-link",
]
[[package]]
name = "windows-sys"
version = "0.52.0"
@@ -3314,15 +2786,6 @@ dependencies = [
"windows_x86_64_msvc",
]
[[package]]
name = "windows-threading"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
dependencies = [
"windows-link",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
+1 -1
View File
@@ -16,7 +16,7 @@ members = [
exclude = ["apps/desktop/src-tauri"]
[workspace.package]
version = "0.5.0"
version = "0.4.0"
edition = "2024"
rust-version = "1.90"
license = "Apache-2.0"
+13 -14
View File
@@ -1,4 +1,4 @@
# Project gates. Plain `make` runs everything that must pass before a commit.
# Portes du projet. `make` seul lance tout ce qui doit être vert avant un commit.
.PHONY: all fmt lint test build proto bench clean desktop desktop-lint
@@ -13,36 +13,35 @@ lint:
cargo clippy --workspace --all-targets -- -D warnings
npm --prefix apps/viewer run lint
# `--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.
# `--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.
test:
cargo test --workspace -- --skip export_bindings
# 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.
# 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.
proto:
cargo test -p rs-proto -p rs-store -p rs-session -p rs-signaling export_bindings
cargo test -p rs-proto -p rs-store -p rs-session export_bindings
build:
cargo build --workspace
npm --prefix apps/viewer run build
# Test bench: always in release, a debug binary skews the measurements.
# Banc d'essai: toujours en release, un binaire debug fausse les mesures.
bench:
cargo run --release -p rs-session --bin rustscreen-cli -- --synthetic
cargo run --release -p rs-session --bin rustscreen -- --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.
# La coque Tauri: WebKitGTK au build, donc dans `nix develop .#desktop`. Son
# crate a son propre workspace; il partage le dossier target pour ne pas tout
# recompiler. pnpm pour l'interface de la coque, npm pour le 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
+25 -27
View File
@@ -8,30 +8,34 @@
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 : **jalon 0.6 « Parité Pro »**, Linux seulement. Pour s'en servir, lire le
[guide de l'utilisateur](docs/guide/README.md). Ce qui tourne:
État : **jalon 0.3 « Voir l'écran »**. Ce qui tourne aujourd'hui, vérifié le 26 octobre 2026:
- 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.
- workspace Rust de neuf crates, protocole partagé avec types TypeScript générés
- `rs-capture`: capture Linux réelle, portail et PipeWire sous Wayland, X11 (XShm) en repli, plus
une mire synthétique
- **écran virtuel** par le portail du bureau (`--virtuel`): la tablette devient un second écran,
vérifié sur GNOME 46
- `rs-diag`: journal JSON local en rotation, archive de diagnostics expurgée (`--diagnostics`)
- `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é
- `rs-session`: l'hôte (partage, spectateurs, réglages, veille, réseau) et le binaire `rustscreen`
- `rs-store`: réglages persistants, écriture atomique, fichier corrompu mis de côté
- `apps/desktop`: coque Tauri, choix de la source avec vignettes, QR, spectateurs, réglages
- `apps/viewer`: viewer React avec machine à états, reprise après coupure ou veille, 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)
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.
Restent à écrire: la capture Windows (#8, après la 1.0), l'icône de barre système (#22), et
l'encodeur matériel (#57). 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 (PipeWire, DXGI), d'encoder en VP8/H.264 matériel, et de servir un client
système (DXGI, ScreenCaptureKit, PipeWire), 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 :
@@ -79,14 +83,14 @@ docs architecture, ADR, matrice de fonctionnalités, backlog
- Rust stable (édition 2024), `cargo`
- Node 22+, npm pour `apps/viewer`, pnpm pour `apps/desktop` (`nix develop .#desktop`)
- Linux : PipeWire et `xdg-desktop-portal` (Wayland), X11 accepté en repli
- Windows : 10 1809+ pour la duplication de bureau DXGI (en cours, pas encore utilisable)
- macOS : 12.3+ pour ScreenCaptureKit
- Windows : 10 1809+ pour la duplications de bureau DXGI
## Installer
```sh
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
nix run . # Nix: reproductible, tout est inclus
./scripts/build-appimage.sh # AppImage: un fichier, rien à installer
```
Détails, prérequis et limites dans [docs/PACKAGING.md](docs/PACKAGING.md). Les deux paquets
@@ -97,12 +101,6 @@ capturent l'écran sous Wayland (portail) et X11; `--synthetic` reste là pour e
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
+3 -3
View File
@@ -1,14 +1,14 @@
{
"name": "@rustscreen/desktop",
"private": true,
"version": "0.5.0",
"version": "0.4.0",
"type": "module",
"packageManager": "pnpm@12.15.0",
"description": "rustscreen desktop shell: pick the source, see the viewers, stop.",
"description": "Coque desktop de rustscreen: choisir la source, voir les spectateurs, couper.",
"scripts": {
"dev": "vite",
"build": "tsc --noEmit && vite build",
"lint": "biome lint src && node ../../scripts/check-i18n.mjs apps/desktop/src desktop",
"lint": "biome lint src && node ../../scripts/verifier-i18n.mjs apps/desktop/src desktop",
"format": "biome format --write src",
"test": "vitest run"
},
+61 -439
View File
@@ -156,7 +156,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "241b621213072e993be4f6f3a9e4b45f65b7e6faad43001be957184b7bb1824b"
dependencies = [
"atk-sys",
"glib 0.18.5",
"glib",
"libc",
]
@@ -166,8 +166,8 @@ version = "0.18.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c5e48b684b0ca77d2bbadeef17424c2ea3c897d44d566a1617e7e8f30614d086"
dependencies = [
"glib-sys 0.18.1",
"gobject-sys 0.18.0",
"glib-sys",
"gobject-sys",
"libc",
"system-deps 6.2.2",
]
@@ -178,12 +178,6 @@ version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
[[package]]
name = "atomic_refcell"
version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "21e4227379beff4205943696e6c3e0cd809bacdf3f0edd6e3dd153e2269571a4"
[[package]]
name = "autocfg"
version = "1.5.1"
@@ -331,7 +325,7 @@ dependencies = [
"bitflags 2.13.2",
"cexpr",
"clang-sys",
"itertools 0.13.0",
"itertools",
"proc-macro2",
"quote",
"regex",
@@ -477,7 +471,7 @@ checksum = "8ca26ef0159422fb77631dc9d17b102f253b876fe1586b03b803e63a309b4ee2"
dependencies = [
"bitflags 2.13.2",
"cairo-sys-rs",
"glib 0.18.5",
"glib",
"libc",
"once_cell",
"thiserror 1.0.69",
@@ -489,7 +483,7 @@ version = "0.18.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "685c9fa8e590b8b3d678873528d83411db17242a73fccaed827770ea0fedda51"
dependencies = [
"glib-sys 0.18.1",
"glib-sys",
"libc",
"system-deps 6.2.2",
]
@@ -864,32 +858,6 @@ dependencies = [
"cipher",
]
[[package]]
name = "curve25519-dalek"
version = "5.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23"
dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
"curve25519-dalek-derive",
"digest 0.11.3",
"fiat-crypto",
"rustc_version",
"subtle",
]
[[package]]
name = "curve25519-dalek-derive"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "darling"
version = "0.24.1"
@@ -1079,7 +1047,7 @@ dependencies = [
"rand 0.9.5",
"rcgen",
"sec1",
"signature 2.2.0",
"signature",
"spki",
"subtle",
"time",
@@ -1204,27 +1172,6 @@ version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
[[package]]
name = "ed25519"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a"
dependencies = [
"signature 3.0.0",
]
[[package]]
name = "ed25519-dalek"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de"
dependencies = [
"curve25519-dalek",
"ed25519",
"sha2 0.11.1",
"subtle",
]
[[package]]
name = "either"
version = "1.19.0"
@@ -1308,12 +1255,6 @@ dependencies = [
"simd-adler32",
]
[[package]]
name = "fiat-crypto"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24"
[[package]]
name = "field-offset"
version = "0.3.6"
@@ -1347,15 +1288,6 @@ dependencies = [
"zlib-rs",
]
[[package]]
name = "flume"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e139bc46ca777eb5efaf62df0ab8cc5fd400866427e56c68b22e414e53bd3be"
dependencies = [
"spin",
]
[[package]]
name = "fnv"
version = "1.0.7"
@@ -1501,7 +1433,7 @@ dependencies = [
"gdk-pixbuf",
"gdk-sys",
"gio",
"glib 0.18.5",
"glib",
"libc",
"pango",
]
@@ -1514,7 +1446,7 @@ checksum = "50e1f5f1b0bfb830d6ccc8066d18db35c487b1b2b1e8589b5dfe9f07e8defaec"
dependencies = [
"gdk-pixbuf-sys",
"gio",
"glib 0.18.5",
"glib",
"libc",
"once_cell",
]
@@ -1525,9 +1457,9 @@ version = "0.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9839ea644ed9c97a34d129ad56d38a25e6756f99f3a88e15cd39c20629caf7"
dependencies = [
"gio-sys 0.18.1",
"glib-sys 0.18.1",
"gobject-sys 0.18.0",
"gio-sys",
"glib-sys",
"gobject-sys",
"libc",
"system-deps 6.2.2",
]
@@ -1540,9 +1472,9 @@ checksum = "5c2d13f38594ac1e66619e188c6d5a1adb98d11b2fcf7894fc416ad76aa2f3f7"
dependencies = [
"cairo-sys-rs",
"gdk-pixbuf-sys",
"gio-sys 0.18.1",
"glib-sys 0.18.1",
"gobject-sys 0.18.0",
"gio-sys",
"glib-sys",
"gobject-sys",
"libc",
"pango-sys",
"pkg-config",
@@ -1556,8 +1488,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "140071d506d223f7572b9f09b5e155afbd77428cd5cc7af8f2694c41d98dfe69"
dependencies = [
"gdk-sys",
"glib-sys 0.18.1",
"gobject-sys 0.18.0",
"glib-sys",
"gobject-sys",
"libc",
"pkg-config",
"system-deps 6.2.2",
@@ -1572,7 +1504,7 @@ dependencies = [
"gdk",
"gdkx11-sys",
"gio",
"glib 0.18.5",
"glib",
"libc",
"x11",
]
@@ -1584,7 +1516,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2e7445fe01ac26f11601db260dd8608fe172514eb63b3b5e261ea6b0f4428d"
dependencies = [
"gdk-sys",
"glib-sys 0.18.1",
"glib-sys",
"libc",
"system-deps 6.2.2",
"x11",
@@ -1657,8 +1589,8 @@ dependencies = [
"futures-core",
"futures-io",
"futures-util",
"gio-sys 0.18.1",
"glib 0.18.5",
"gio-sys",
"glib",
"libc",
"once_cell",
"pin-project-lite",
@@ -1672,26 +1604,13 @@ version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37566df850baf5e4cb0dfb78af2e4b9898d817ed9263d1090a2df958c64737d2"
dependencies = [
"glib-sys 0.18.1",
"gobject-sys 0.18.0",
"glib-sys",
"gobject-sys",
"libc",
"system-deps 6.2.2",
"winapi",
]
[[package]]
name = "gio-sys"
version = "0.22.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c28739f914c15b87a9856000bed9cbd5b3a8afbca5e982d9a299e1601422cb5"
dependencies = [
"glib-sys 0.22.9",
"gobject-sys 0.22.9",
"libc",
"system-deps 9.0.1",
"windows-sys 0.61.2",
]
[[package]]
name = "glib"
version = "0.18.5"
@@ -1704,10 +1623,10 @@ dependencies = [
"futures-executor",
"futures-task",
"futures-util",
"gio-sys 0.18.1",
"glib-macros 0.18.5",
"glib-sys 0.18.1",
"gobject-sys 0.18.0",
"gio-sys",
"glib-macros",
"glib-sys",
"gobject-sys",
"libc",
"memchr",
"once_cell",
@@ -1715,27 +1634,6 @@ dependencies = [
"thiserror 1.0.69",
]
[[package]]
name = "glib"
version = "0.22.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4cf9e5bd8713f1990a92c422998826e0fb34824277b46bc59757373483c6694"
dependencies = [
"bitflags 2.13.2",
"futures-channel",
"futures-core",
"futures-executor",
"futures-task",
"futures-util",
"gio-sys 0.22.9",
"glib-macros 0.22.9",
"glib-sys 0.22.9",
"gobject-sys 0.22.9",
"libc",
"memchr",
"smallvec",
]
[[package]]
name = "glib-macros"
version = "0.18.5"
@@ -1750,18 +1648,6 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "glib-macros"
version = "0.22.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c9597c68fa7bdf4154a3079642cd21c4dccac0b0bdd2897d82861523bf91e7b9"
dependencies = [
"heck 0.5.0",
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "glib-sys"
version = "0.18.1"
@@ -1772,16 +1658,6 @@ dependencies = [
"system-deps 6.2.2",
]
[[package]]
name = "glib-sys"
version = "0.22.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "99b38907e67e40dec9b60f858bcada952598719cb512a13eb13d6cdcd16f8295"
dependencies = [
"libc",
"system-deps 9.0.1",
]
[[package]]
name = "glob"
version = "0.3.4"
@@ -1794,145 +1670,11 @@ version = "0.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0850127b514d1c4a4654ead6dedadb18198999985908e6ffe4436f53c785ce44"
dependencies = [
"glib-sys 0.18.1",
"glib-sys",
"libc",
"system-deps 6.2.2",
]
[[package]]
name = "gobject-sys"
version = "0.22.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07595c9ba696bd9819cb6a8df39f08078f3dd679508fe052dd558492c2053834"
dependencies = [
"glib-sys 0.22.9",
"libc",
"system-deps 9.0.1",
]
[[package]]
name = "gstreamer"
version = "0.25.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4237e2066a25ecb7e54be6c066409e30615920265b9799b8d560ef8ac9857c6"
dependencies = [
"cfg-if",
"futures-channel",
"futures-core",
"futures-util",
"glib 0.22.10",
"gstreamer-sys",
"itertools 0.15.0",
"kstring",
"libc",
"muldiv",
"num-integer",
"num-rational",
"option-operations",
"pastey",
"pin-project-lite",
"smallvec",
"thiserror 2.0.21",
]
[[package]]
name = "gstreamer-app"
version = "0.25.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "97f8ae9238c2352398dcc084de28df3f7099af216ac6c160b52318d23f25c010"
dependencies = [
"futures-core",
"futures-sink",
"glib 0.22.10",
"gstreamer",
"gstreamer-app-sys",
"gstreamer-base",
"libc",
]
[[package]]
name = "gstreamer-app-sys"
version = "0.25.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0798b8aef6694341d40bb81edc759f8979b896b59f9f0f45d8cfa3bb7bf2e743"
dependencies = [
"glib-sys 0.22.9",
"gstreamer-base-sys",
"gstreamer-sys",
"libc",
"system-deps 9.0.1",
]
[[package]]
name = "gstreamer-base"
version = "0.25.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "17cbd8f59586a369c40d4b0d2f3a61cf9e9287b3cf5503cdcd8e7c5faa99265e"
dependencies = [
"atomic_refcell",
"cfg-if",
"glib 0.22.10",
"gstreamer",
"gstreamer-base-sys",
"libc",
]
[[package]]
name = "gstreamer-base-sys"
version = "0.25.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b05f77bfd76b5afee6b29c27dae19eaf5018b5cf8d0d17520f3de44c6385c32"
dependencies = [
"glib-sys 0.22.9",
"gobject-sys 0.22.9",
"gstreamer-sys",
"libc",
"system-deps 9.0.1",
]
[[package]]
name = "gstreamer-sys"
version = "0.25.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "436d9532847489a8285d57b8c3670762c12a18f777fdc2ab159b52e0e6f521b9"
dependencies = [
"cfg-if",
"glib-sys 0.22.9",
"gobject-sys 0.22.9",
"libc",
"system-deps 9.0.1",
]
[[package]]
name = "gstreamer-video"
version = "0.25.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ffe4d77b2a5e679973d9c6b6c052da8cda86b83f5c268872f8691fde693fde84"
dependencies = [
"cfg-if",
"futures-channel",
"glib 0.22.10",
"gstreamer",
"gstreamer-base",
"gstreamer-video-sys",
"libc",
"thiserror 2.0.21",
]
[[package]]
name = "gstreamer-video-sys"
version = "0.25.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef455da22edca97ac9299d682b868227f3d9217b303748ce0161b31ae82dc106"
dependencies = [
"glib-sys 0.22.9",
"gobject-sys 0.22.9",
"gstreamer-base-sys",
"gstreamer-sys",
"libc",
"system-deps 9.0.1",
]
[[package]]
name = "gtk"
version = "0.18.2"
@@ -1946,7 +1688,7 @@ dependencies = [
"gdk",
"gdk-pixbuf",
"gio",
"glib 0.18.5",
"glib",
"gtk-sys",
"gtk3-macros",
"libc",
@@ -1964,9 +1706,9 @@ dependencies = [
"cairo-sys-rs",
"gdk-pixbuf-sys",
"gdk-sys",
"gio-sys 0.18.1",
"glib-sys 0.18.1",
"gobject-sys 0.18.0",
"gio-sys",
"glib-sys",
"gobject-sys",
"libc",
"pango-sys",
"system-deps 6.2.2",
@@ -2386,15 +2128,6 @@ dependencies = [
"either",
]
[[package]]
name = "itertools"
version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc"
dependencies = [
"either",
]
[[package]]
name = "itoa"
version = "1.0.18"
@@ -2408,7 +2141,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca5671e9ffce8ffba57afc24070e906da7fc4b1ba66f2cabebf61bf2ea257fcc"
dependencies = [
"bitflags 1.3.2",
"glib 0.18.5",
"glib",
"javascriptcore-rs-sys",
]
@@ -2418,8 +2151,8 @@ version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af1be78d14ffa4b75b66df31840478fef72b51f8c2465d4ca7c194da9f7a5124"
dependencies = [
"glib-sys 0.18.1",
"gobject-sys 0.18.0",
"glib-sys",
"gobject-sys",
"libc",
"system-deps 6.2.2",
]
@@ -2575,15 +2308,6 @@ dependencies = [
"serde",
]
[[package]]
name = "kstring"
version = "2.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "558bf9508a558512042d3095138b1f7b8fe90c5467d94f9f1da28b3731c5dbd1"
dependencies = [
"static_assertions",
]
[[package]]
name = "lazy_static"
version = "1.5.1"
@@ -2596,7 +2320,7 @@ version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "03589b9607c868cc7ae54c0b2a22c8dc03dd41692d48f2d7df73615c6a95dc0a"
dependencies = [
"glib 0.18.5",
"glib",
"gtk",
"gtk-sys",
"libappindicator-sys",
@@ -2738,20 +2462,6 @@ version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
[[package]]
name = "mdns-sd"
version = "0.21.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8562654710f72a9cbce4b0d5b7c366a2f94330ba1ce3740f15e932ea2d37b161"
dependencies = [
"fastrand",
"flume",
"if-addrs",
"mio",
"socket-pktinfo",
"socket2",
]
[[package]]
name = "memchr"
version = "2.8.3"
@@ -2816,7 +2526,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee"
dependencies = [
"libc",
"log",
"wasi",
"windows-sys 0.61.2",
]
@@ -2852,12 +2561,6 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "muldiv"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "956787520e75e9bd233246045d19f42fb73242759cc57fba9611d940ae96d4b0"
[[package]]
name = "ndk"
version = "0.9.0"
@@ -2959,16 +2662,6 @@ dependencies = [
"num-traits",
]
[[package]]
name = "num-rational"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
dependencies = [
"num-integer",
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -3217,15 +2910,6 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
[[package]]
name = "option-operations"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aca39cf52b03268400c16eeb9b56382ea3c3353409309b63f5c8f0b1faf42754"
dependencies = [
"pastey",
]
[[package]]
name = "ordered-stream"
version = "0.2.0"
@@ -3243,7 +2927,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ca27ec1eb0457ab26f3036ea52229edbdb74dee1edd29063f5b9b010e7ebee4"
dependencies = [
"gio",
"glib 0.18.5",
"glib",
"libc",
"once_cell",
"pango-sys",
@@ -3255,8 +2939,8 @@ version = "0.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "436737e391a843e5933d6d9aa102cb126d501e815b83601365a948a518555dc5"
dependencies = [
"glib-sys 0.18.1",
"gobject-sys 0.18.0",
"glib-sys",
"gobject-sys",
"libc",
"system-deps 6.2.2",
]
@@ -3284,12 +2968,6 @@ dependencies = [
"windows-link",
]
[[package]]
name = "pastey"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"
[[package]]
name = "pem"
version = "4.0.0"
@@ -3775,34 +3453,29 @@ dependencies = [
[[package]]
name = "rs-capture"
version = "0.5.0"
version = "0.4.0"
dependencies = [
"pipewire",
"rs-proto",
"rustix",
"thiserror 2.0.21",
"tracing",
"windows-sys 0.61.2",
"x11rb",
]
[[package]]
name = "rs-codec"
version = "0.5.0"
version = "0.4.0"
dependencies = [
"env-libvpx-sys",
"gstreamer",
"gstreamer-app",
"gstreamer-video",
"rs-capture",
"thiserror 2.0.21",
"tokio",
"tracing",
]
[[package]]
name = "rs-diag"
version = "0.5.0"
version = "0.4.0"
dependencies = [
"if-addrs",
"serde",
@@ -3816,7 +3489,7 @@ dependencies = [
[[package]]
name = "rs-platform"
version = "0.5.0"
version = "0.4.0"
dependencies = [
"futures-util",
"if-addrs",
@@ -3824,13 +3497,12 @@ dependencies = [
"thiserror 2.0.21",
"tokio",
"tracing",
"windows-sys 0.61.2",
"zbus",
]
[[package]]
name = "rs-proto"
version = "0.5.0"
version = "0.4.0"
dependencies = [
"serde",
"serde_json",
@@ -3840,9 +3512,8 @@ dependencies = [
[[package]]
name = "rs-rtc"
version = "0.5.0"
version = "0.4.0"
dependencies = [
"if-addrs",
"rs-codec",
"str0m",
"thiserror 2.0.21",
@@ -3852,7 +3523,7 @@ dependencies = [
[[package]]
name = "rs-session"
version = "0.5.0"
version = "0.4.0"
dependencies = [
"base64 0.23.1",
"png",
@@ -3874,13 +3545,11 @@ dependencies = [
[[package]]
name = "rs-signaling"
version = "0.5.0"
version = "0.4.0"
dependencies = [
"axum",
"axum-server",
"ed25519-dalek",
"hex",
"mdns-sd",
"qrcode",
"rand 0.10.3",
"rcgen",
@@ -3894,12 +3563,11 @@ dependencies = [
"tokio",
"tower-http 0.7.1",
"tracing",
"ts-rs",
]
[[package]]
name = "rs-store"
version = "0.5.0"
version = "0.4.0"
dependencies = [
"rs-proto",
"serde",
@@ -3983,11 +3651,10 @@ dependencies = [
[[package]]
name = "rustscreen-desktop"
version = "0.5.0"
version = "0.4.0"
dependencies = [
"libloading 0.8.9",
"rs-diag",
"rs-platform",
"rs-session",
"rs-store",
"serde",
@@ -4382,12 +4049,6 @@ version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
[[package]]
name = "signature"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5"
[[package]]
name = "simd-adler32"
version = "0.3.10"
@@ -4412,17 +4073,6 @@ version = "1.16.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8"
[[package]]
name = "socket-pktinfo"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "612942246d0cc239cfd83af1dfd39be47f649208a3524e5e9da651910128e0ac"
dependencies = [
"libc",
"socket2",
"windows-sys 0.61.2",
]
[[package]]
name = "socket2"
version = "0.6.5"
@@ -4463,7 +4113,7 @@ checksum = "471f924a40f31251afc77450e781cb26d55c0b650842efafc9c6cbd2f7cc4f9f"
dependencies = [
"futures-channel",
"gio",
"glib 0.18.5",
"glib",
"libc",
"soup3-sys",
]
@@ -4474,22 +4124,13 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ebe8950a680a12f24f15ebe1bf70db7af98ad242d9db43596ad3108aab86c27"
dependencies = [
"gio-sys 0.18.1",
"glib-sys 0.18.1",
"gobject-sys 0.18.0",
"gio-sys",
"glib-sys",
"gobject-sys",
"libc",
"system-deps 6.2.2",
]
[[package]]
name = "spin"
version = "0.9.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"
dependencies = [
"lock_api",
]
[[package]]
name = "spki"
version = "0.7.3"
@@ -4506,12 +4147,6 @@ version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
[[package]]
name = "static_assertions"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
[[package]]
name = "static_vcruntime"
version = "3.0.0"
@@ -4707,19 +4342,6 @@ dependencies = [
"version-compare",
]
[[package]]
name = "system-deps"
version = "9.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db551ad38aac61d5e0343e0eeeb0163be3115c4e23b6a025959570ee0c03c67d"
dependencies = [
"cfg-expr 0.20.10",
"heck 0.5.0",
"pkg-config",
"toml 1.1.8+spec-1.1.0",
"version-compare",
]
[[package]]
name = "tao"
version = "0.37.2"
@@ -5005,7 +4627,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.3.4",
"getrandom 0.4.3",
"once_cell",
"rustix",
"windows-sys 0.61.2",
@@ -5800,10 +5422,10 @@ dependencies = [
"gdk",
"gdk-sys",
"gio",
"gio-sys 0.18.1",
"glib 0.18.5",
"glib-sys 0.18.1",
"gobject-sys 0.18.0",
"gio-sys",
"glib",
"glib-sys",
"gobject-sys",
"gtk",
"gtk-sys",
"javascriptcore-rs",
@@ -5822,9 +5444,9 @@ dependencies = [
"bitflags 1.3.2",
"cairo-sys-rs",
"gdk-sys",
"gio-sys 0.18.1",
"glib-sys 0.18.1",
"gobject-sys 0.18.0",
"gio-sys",
"glib-sys",
"gobject-sys",
"gtk-sys",
"javascriptcore-rs-sys",
"libc",
+12 -21
View File
@@ -1,47 +1,38 @@
[package]
name = "rustscreen-desktop"
description = "rustscreen desktop shell: choose what to share, see who is watching, stop."
version = "0.5.0"
description = "Coque desktop de rustscreen: choisir ce qu'on partage, voir qui regarde, couper."
version = "0.4.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"
# Hors du workspace principal: WebKitGTK et GTK sont nécessaires au build, et la
# CI de l'hôte ne les a pas. `nix develop .#desktop` les fournit.
[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.
# L'interface compilée (`dist`) est embarquée dans le binaire. Sans cette
# feature, Tauri charge `devUrl` (le serveur Vite, `pnpm dev`): c'est le mode
# de développement, `--no-default-features`. La CLI Tauri fait ce choix toute
# seule; on s'en passe, d'où le choix explicite.
default = ["custom-protocol"]
custom-protocol = ["tauri/custom-protocol"]
# Real Wayland capture (ADR 0009), like the command-line binary.
# Capture Wayland réelle (ADR 0009), comme le binaire en ligne de commande.
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.
# `tray-icon`: icône de barre système (#22); `image-png`: ses icônes.
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"
# Essai de chargement de libayatana-appindicator avant de créer l'icône (#22).
libloading = "0.9.0"
[build-dependencies]
tauri-build = { version = "2.7.4", features = [] }
@@ -1,7 +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.",
"description": "La fenêtre principale: écouter l'état de l'hôte. Les commandes de l'application sont autorisées par défaut.",
"windows": ["main"],
"permissions": ["core:default"]
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 361 KiB

+308
View File
@@ -0,0 +1,308 @@
//! Icône de barre système et menu de session (#22).
//!
//! L'icône dit l'état réel: elle suit le même `etat` que la fenêtre, au même
//! moment, donc en bien moins d'une seconde. Le menu permet de démarrer (la
//! dernière source choisie), d'arrêter, d'ouvrir la fenêtre et de quitter, sans
//! que la fenêtre soit ouverte.
//!
//! Sous Linux, l'icône passe par StatusNotifierItem (libayatana-appindicator,
//! chargée à l'exécution). GNOME sans l'extension AppIndicator n'affiche rien:
//! [`disponible`] le détecte, et la fermeture de la fenêtre se replie alors sur
//! une simple réduction, pour ne jamais cacher un partage sans moyen de le
//! retrouver.
//!
//! Les textes viennent de l'interface (`traduire_barre`), dans sa langue
//! (#21): les traductions vivent dans `locales/`, pas ici. Le français
//! ci-dessous ne sert qu'avant le premier envoi.
use std::sync::Mutex;
use rs_session::{Etat, 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 ICONE: &[u8] = include_bytes!("../icons/icon.png");
/// Ce que le menu propose; l'identifiant revient dans l'événement de clic.
pub const OUVRIR: &str = "ouvrir";
pub const DEMARRER: &str = "demarrer";
pub const ARRETER: &str = "arreter";
pub const QUITTER: &str = "quitter";
/// Les formes du statut en direct: Rust ne connaît pas les règles de pluriel
/// de chaque langue, l'interface lui donne celles de 0, de 1 et du reste.
#[derive(Debug, Clone, Deserialize)]
pub struct Formes {
pub zero: String,
pub one: String,
/// Avec `{count}` à remplacer.
pub other: String,
}
/// Les textes du menu, traduits par l'interface.
#[derive(Debug, Clone, Deserialize)]
pub struct TextesBarre {
pub aucun: String,
pub demarrage: String,
pub direct: Formes,
pub ouvrir: String,
pub demarrer: String,
pub reprendre: String,
pub arreter: String,
pub quitter: String,
}
impl Default for TextesBarre {
fn default() -> Self {
Self {
aucun: "Aucun partage".into(),
demarrage: "Démarrage du partage…".into(),
direct: Formes {
zero: "En direct, personne ne regarde".into(),
one: "En direct, 1 spectateur".into(),
other: "En direct, {count} spectateurs".into(),
},
ouvrir: "Ouvrir rustscreen".into(),
demarrer: "Démarrer le partage…".into(),
reprendre: "Reprendre le dernier partage".into(),
arreter: "Arrêter le partage".into(),
quitter: "Quitter".into(),
}
}
}
impl TextesBarre {
fn statut(&self, etat: &Etat) -> String {
match etat.phase {
Phase::Arrete => self.aucun.clone(),
Phase::Demarrage => self.demarrage.clone(),
Phase::EnCours => match etat.partage.as_ref().map_or(0, |p| p.appareils.len()) {
0 => self.direct.zero.clone(),
1 => self.direct.one.clone(),
n => self.direct.other.replace("{count}", &n.to_string()),
},
}
}
}
pub struct Barre<R: Runtime> {
icone: TrayIcon<R>,
statut: MenuItem<R>,
ouvrir: MenuItem<R>,
demarrer: MenuItem<R>,
arreter: MenuItem<R>,
quitter: MenuItem<R>,
repos: Image<'static>,
direct: Image<'static>,
textes: Mutex<TextesBarre>,
}
impl<R: Runtime> Barre<R> {
/// Crée l'icône et son menu. `None` quand ce bureau n'a pas de barre
/// système: l'application vit alors dans sa fenêtre seulement.
pub fn creer(
app: &AppHandle<R>,
au_clic: impl Fn(&AppHandle<R>, &str) + Send + Sync + 'static,
) -> Option<Self> {
if !disponible() {
tracing::info!("pas de barre système sur ce bureau: fenêtre seule");
return None;
}
let construire = || -> tauri::Result<Self> {
let repos = Image::from_bytes(ICONE)?.to_owned();
let direct = avec_pastille(&repos);
let textes = TextesBarre::default();
let statut = MenuItem::with_id(app, "statut", &textes.aucun, false, None::<&str>)?;
let ouvrir = MenuItem::with_id(app, OUVRIR, &textes.ouvrir, true, None::<&str>)?;
let demarrer = MenuItem::with_id(app, DEMARRER, &textes.demarrer, true, None::<&str>)?;
let arreter = MenuItem::with_id(app, ARRETER, &textes.arreter, false, None::<&str>)?;
let quitter = MenuItem::with_id(app, QUITTER, &textes.quitter, true, None::<&str>)?;
let menu = Menu::with_items(
app,
&[
&statut,
&PredefinedMenuItem::separator(app)?,
&ouvrir,
&demarrer,
&arreter,
&PredefinedMenuItem::separator(app)?,
&quitter,
],
)?;
let icone = TrayIconBuilder::with_id("rustscreen")
.icon(repos.clone())
.tooltip(format!("rustscreen: {}", textes.aucun))
.menu(&menu)
.show_menu_on_left_click(false)
.on_menu_event(move |app, evenement| au_clic(app, evenement.id().as_ref()))
.on_tray_icon_event(|icone, evenement| {
// Windows et macOS: un clic gauche rouvre la fenêtre. Sous
// Linux, StatusNotifierItem n'envoie que le menu.
if let TrayIconEvent::Click {
button: MouseButton::Left,
button_state: MouseButtonState::Up,
..
} = evenement
{
montrer(icone.app_handle());
}
})
.build(app)?;
Ok(Self {
icone,
statut,
ouvrir,
demarrer,
arreter,
quitter,
repos,
direct,
textes: Mutex::new(textes),
})
};
match construire() {
Ok(barre) => Some(barre),
Err(erreur) => {
tracing::warn!(%erreur, "icône de barre système impossible");
None
}
}
}
/// Change la langue du menu; l'appelant redessine avec [`Barre::suivre`].
pub fn traduire(&self, textes: TextesBarre) {
let resultat = (|| -> tauri::Result<()> {
self.ouvrir.set_text(&textes.ouvrir)?;
self.arreter.set_text(&textes.arreter)?;
self.quitter.set_text(&textes.quitter)?;
Ok(())
})();
if let Err(erreur) = resultat {
tracing::warn!(%erreur, "menu de la barre système non traduit");
}
*self.textes.lock().unwrap_or_else(|e| e.into_inner()) = textes;
}
/// Met l'icône, l'infobulle et le menu à l'image de l'état.
pub fn suivre(&self, etat: &Etat, derniere_source: bool) {
let textes = self
.textes
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone();
let texte = textes.statut(etat);
let icone = if etat.phase == Phase::EnCours {
&self.direct
} else {
&self.repos
};
let resultat = (|| -> tauri::Result<()> {
self.icone.set_icon(Some(icone.clone()))?;
self.icone
.set_tooltip(Some(format!("rustscreen: {texte}")))?;
self.statut.set_text(&texte)?;
// Démarrer depuis le menu relance la dernière source; sans elle,
// le menu ouvre la fenêtre pour en choisir une.
self.demarrer.set_text(if derniere_source {
&textes.reprendre
} else {
&textes.demarrer
})?;
self.demarrer.set_enabled(etat.phase == Phase::Arrete)?;
self.arreter.set_enabled(etat.phase != Phase::Arrete)?;
Ok(())
})();
if let Err(erreur) = resultat {
tracing::warn!(%erreur, "barre système non mise à jour");
}
}
}
/// Rouvre la fenêtre principale, cachée ou réduite.
pub fn montrer<R: Runtime>(app: &AppHandle<R>) {
if let Some(fenetre) = app.get_webview_window("main") {
let _ = fenetre.unminimize();
let _ = fenetre.show();
let _ = fenetre.set_focus();
}
}
/// Une barre système existe-t-elle? Sous Linux, il faut un hôte
/// StatusNotifierItem sur le bus de session et la bibliothèque qui y parle.
#[cfg(target_os = "linux")]
fn disponible() -> bool {
let bibliotheque = ["libayatana-appindicator3.so.1", "libappindicator3.so.1"]
.iter()
.any(|nom| bibliotheque_presente(nom));
bibliotheque && hote_status_notifier()
}
#[cfg(not(target_os = "linux"))]
fn disponible() -> bool {
true
}
/// Le chargeur dynamique sait-il ouvrir cette bibliothèque? tray-icon panique
/// sinon, au lieu de rendre une erreur. Chercher le fichier ne suffit pas: un
/// binaire construit par Nix ne lit pas le cache du système, il faut essayer
/// le même chargement que lui.
#[cfg(target_os = "linux")]
fn bibliotheque_presente(nom: &str) -> bool {
// SAFETY: c'est la bibliothèque que tray-icon chargera de toute façon
// juste après, par le même chemin de recherche; ses constructeurs
// (enregistrement de types GObject) sont faits pour être exécutés une
// fois chargée, et la garder chargée évite un second passage.
match unsafe { libloading::Library::new(nom) } {
Ok(bibliotheque) => {
std::mem::forget(bibliotheque);
true
}
Err(_) => false,
}
}
/// `org.kde.StatusNotifierWatcher` a-t-il un propriétaire sur le bus de
/// session? C'est lui qui affiche les icônes (KDE, Ubuntu, GNOME avec
/// l'extension AppIndicator).
#[cfg(target_os = "linux")]
fn hote_status_notifier() -> 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(|sortie| String::from_utf8_lossy(&sortie.stdout).trim() == "b true")
}
/// L'icône « en direct »: la même, avec une pastille rouge en bas à droite,
/// lisible même à 16 pixels.
fn avec_pastille(base: &Image<'_>) -> Image<'static> {
let (w, h) = (base.width(), base.height());
let mut rgba = base.rgba().to_vec();
let rayon = w.min(h) as f32 * 0.22;
let (cx, cy) = (w as f32 - rayon - 1.0, h as f32 - rayon - 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 <= rayon {
rgba[i..i + 4].copy_from_slice(&[0xdc, 0x26, 0x26, 0xff]);
} else if d <= rayon + w as f32 * 0.03 {
// Liseré blanc: la pastille se détache sur une barre sombre
// comme sur une claire.
rgba[i..i + 4].copy_from_slice(&[0xff, 0xff, 0xff, 0xff]);
}
}
}
Image::new_owned(rgba, w, h)
}
+143 -244
View File
@@ -1,370 +1,269 @@
//! rustscreen desktop shell (#15): the screen the host sees.
//! Coque desktop de rustscreen (#15): l'écran que voit l'hôte.
//!
//! 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.
//! Elle ne fait rien d'autre que relayer: chaque commande appelle
//! [`rs_session::Hote`], et chaque changement d'état part vers l'interface par
//! l'événement `etat`, l'état complet à chaque fois. L'interface ne garde donc
//! aucun état du partage à elle, et ne peut pas afficher un bouton qui ment.
mod tray;
mod barre;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use rs_session::{
Config, Host, HostState, InterfaceOption, Overrides, Phase, SettingsOutcome, SourceChoice,
SourceOption,
Application, Config, Etat, Hote, InterfaceProposee, Phase, SourceChoisie, SourceProposee,
Surcharges,
};
use rs_store::{CloseAction, Notice, Rejection, Settings};
use rs_store::{Fermeture, Refus, Reglages};
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.
/// La dernière source démarrée, pour que le menu de la barre système puisse
/// relancer un partage sans ouvrir la fenêtre.
#[derive(Default)]
struct LastSource(Mutex<Option<SourceChoice>>);
struct Derniere(Mutex<Option<SourceChoisie>>);
/// 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>>>);
/// L'icône de barre système, si ce bureau en a une: sans elle, cacher la
/// fenêtre rendrait l'application introuvable.
struct AvecBarre(Option<Arc<barre::Barre<tauri::Wry>>>);
impl MaybeTray {
fn present(&self) -> bool {
impl AvecBarre {
fn presente(&self) -> bool {
self.0.is_some()
}
}
fn last_source_known(app: &tauri::AppHandle) -> bool {
app.state::<LastSource>()
fn derniere_connue(app: &tauri::AppHandle) -> bool {
app.state::<Derniere>()
.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,\
const FILTRE: &str = "rustscreen_desktop=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()
fn etat(hote: State<'_, Hote>) -> Etat {
hote.etat()
}
#[tauri::command]
async fn sources(host: State<'_, Host>) -> Result<Vec<SourceOption>, ()> {
Ok(host.sources().await)
async fn sources(hote: State<'_, Hote>) -> Result<Vec<SourceProposee>, ()> {
Ok(hote.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
async fn demarrer(
hote: State<'_, Hote>,
derniere: State<'_, Derniere>,
choix: SourceChoisie,
) -> Result<(), String> {
*derniere.0.lock().unwrap_or_else(|e| e.into_inner()) = Some(choix.clone());
hote.demarrer(choix).await
}
#[tauri::command]
async fn stop(host: State<'_, Host>) -> Result<(), ()> {
host.stop().await;
async fn arreter(hote: State<'_, Hote>) -> Result<(), ()> {
hote.arreter().await;
Ok(())
}
#[tauri::command]
fn disconnect(host: State<'_, Host>, connection: u64) -> bool {
host.disconnect(connection)
fn deconnecter(hote: State<'_, Hote>, connexion: u64) -> bool {
hote.deconnecter(connexion)
}
#[tauri::command]
fn regenerate_access(host: State<'_, Host>) -> bool {
host.regenerate_access()
fn regenerer_acces(hote: State<'_, Hote>) -> bool {
hote.regenerer_acces()
}
/// Les textes du menu de la barre système, dans la langue de l'interface.
#[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(
fn traduire_barre(
app: tauri::AppHandle,
host: State<'_, Host>,
tray: State<'_, MaybeTray>,
texts: tray::TrayTexts,
hote: State<'_, Hote>,
barre: State<'_, AvecBarre>,
textes: barre::TextesBarre,
) {
if let Some(tray) = &tray.0 {
tray.translate(texts);
tray.follow(&host.state(), last_source_known(&app));
if let Some(barre) = &barre.0 {
barre.traduire(textes);
barre.suivre(&hote.etat(), derniere_connue(&app));
}
}
#[tauri::command]
fn settings(host: State<'_, Host>) -> Settings {
host.settings()
fn reglages(hote: State<'_, Hote>) -> Reglages {
hote.reglages()
}
#[tauri::command]
async fn update_settings(
host: State<'_, Host>,
settings: Settings,
) -> Result<SettingsOutcome, Vec<Rejection>> {
host.update_settings(settings).await
async fn modifier_reglages(
hote: State<'_, Hote>,
reglages: Reglages,
) -> Result<Application, Vec<Refus>> {
hote.modifier_reglages(reglages).await
}
#[tauri::command]
fn interfaces(host: State<'_, Host>) -> Vec<InterfaceOption> {
host.interfaces()
fn interfaces(hote: State<'_, Hote>) -> Vec<InterfaceProposee> {
hote.interfaces()
}
/// Writes the diagnostics archive to the download folder and returns its
/// path: the user sends it themselves (ADR 0008).
/// Écrit l'archive de diagnostics dans le dossier de téléchargement et rend
/// son chemin: l'utilisateur la transmet lui-même (ADR 0008).
#[tauri::command]
async fn export_diagnostics(host: State<'_, Host>) -> Result<String, String> {
let host = host.inner().clone();
async fn exporter_diagnostics(hote: State<'_, Hote>) -> Result<String, String> {
let hote = hote.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())
let (nom, octets) = hote.diagnostics()?;
let dossier = dossier_telechargements();
std::fs::create_dir_all(&dossier).map_err(|e| e.to_string())?;
let chemin = dossier.join(nom);
std::fs::write(&chemin, octets).map_err(|e| e.to_string())?;
tracing::info!(evenement = "diagnostics_exportes", "archive écrite");
Ok(chemin.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")
/// `XDG_DOWNLOAD_DIR` de `user-dirs.dirs` quand il existe, sinon le dossier
/// personnel.
fn dossier_telechargements() -> PathBuf {
let maison = 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"));
.unwrap_or_else(|| maison.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('"');
.and_then(|texte| {
texte.lines().find_map(|ligne| {
let valeur = ligne.strip_prefix("XDG_DOWNLOAD_DIR=")?.trim_matches('"');
Some(PathBuf::from(
value.replace("$HOME", &home.display().to_string()),
valeur.replace("$HOME", &maison.display().to_string()),
))
})
})
.unwrap_or(home)
.unwrap_or(maison)
}
/// A click in the system tray menu.
fn on_tray_click(app: &tauri::AppHandle, id: &str) {
let host = app.state::<Host>().inner().clone();
/// Un clic dans le menu de la barre système.
fn au_clic_barre(app: &tauri::AppHandle, id: &str) {
let hote = app.state::<Hote>().inner().clone();
match id {
tray::OPEN => tray::show(app),
tray::START => {
let last = app
.state::<LastSource>()
barre::OUVRIR => barre::montrer(app),
barre::DEMARRER => {
let derniere = app
.state::<Derniere>()
.0
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone();
match last {
Some(choice) => {
match derniere {
Some(choix) => {
tauri::async_runtime::spawn(async move {
// The failure shows in the window, through the state.
let _ = host.start(choice).await;
// L'échec s'affiche dans la fenêtre, par l'état.
let _ = hote.demarrer(choix).await;
});
}
None => tray::show(app),
None => barre::montrer(app),
}
}
tray::STOP => {
tauri::async_runtime::spawn(async move { host.stop().await });
barre::ARRETER => {
tauri::async_runtime::spawn(async move { hote.arreter().await });
}
tray::QUIT => request_quit(app),
barre::QUITTER => app.exit(0),
_ => {}
}
}
/// 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 journal = rs_diag::initialiser(rs_diag::dossier_journaux().as_deref(), FILTRE);
let executable = std::env::current_exe().ok();
let host = tauri::async_runtime::block_on(Host::new(Config {
let hote = tauri::async_runtime::block_on(Hote::nouveau(Config {
version: env!("CARGO_PKG_VERSION").into(),
viewer_dir: std::env::var_os("RUSTSCREEN_VIEWER")
.map(PathBuf::from)
.or_else(rs_session::installed_viewer),
viewer_dir: std::env::var_os("RUSTSCREEN_VIEWER").map(PathBuf::from),
tls: false,
store: rs_store::Store::user_default(),
overrides: Overrides::default(),
log_dir: log.dir.clone(),
autostart: executable.map(|exe| (exe, AUTOSTARTED.to_string())),
magasin: rs_store::Magasin::par_defaut(),
surcharges: Surcharges::default(),
journaux: journal.dossier.clone(),
demarrage_auto: executable.map(|exe| (exe, String::new())),
}));
let application = tauri::Builder::default()
.manage(host.clone())
.manage(LastSource::default())
.manage(hote.clone())
.manage(Derniere::default())
.invoke_handler(tauri::generate_handler![
state,
etat,
sources,
start,
stop,
disconnect,
regenerate_access,
trust_device,
revoke_device,
rename_device,
switch_source,
translate_tray,
quit,
settings,
update_settings,
demarrer,
arreter,
deconnecter,
regenerer_acces,
traduire_barre,
reglages,
modifier_reglages,
interfaces,
export_diagnostics,
exporter_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);
let barre = barre::Barre::creer(app.handle(), au_clic_barre).map(Arc::new);
app.manage(AvecBarre(barre.clone()));
// L'état part vers l'interface et vers l'icône à chaque changement,
// complet: l'icône suit l'état réel au même instant que la fenêtre.
let poignee = app.handle().clone();
let mut abonne = hote.abonner();
if let Some(barre) = &barre {
barre.suivre(&abonne.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));
while abonne.changed().await.is_ok() {
let etat = abonne.borrow_and_update().clone();
if let Some(barre) = &barre {
barre.suivre(&etat, derniere_connue(&poignee));
}
if let Err(error) = handle.emit("state", state) {
tracing::warn!(%error, "state not sent to the interface");
if let Err(erreur) = poignee.emit("etat", etat) {
tracing::warn!(%erreur, "état non transmis à l'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);
.on_window_event(|fenetre, evenement| {
if let WindowEvent::CloseRequested { api, .. } = evenement {
let app = fenetre.app_handle();
let hote = app.state::<Hote>();
if hote.reglages().fermeture == Fermeture::Quitter {
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() {
// Fermer ne coupe pas un partage (#22): la fenêtre se cache
// dans la barre système. Sans barre, elle se réduit pendant un
// partage, et ferme l'application sinon.
if app.state::<AvecBarre>().presente() {
api.prevent_close();
let _ = window.hide();
} else if host.state().phase != Phase::Stopped {
let _ = fenetre.hide();
} else if hote.etat().phase != Phase::Arrete {
api.prevent_close();
let _ = window.minimize();
let _ = fenetre.minimize();
}
}
})
.build(tauri::generate_context!())
.expect("Tauri application");
.expect("application Tauri");
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());
application.run(move |app, evenement| {
// Quitter arrête le partage proprement: session portail fermée, veille
// relâchée, spectateurs prévenus.
if let RunEvent::Exit = evenement {
let hote = app.state::<Hote>().inner().clone();
tauri::async_runtime::block_on(hote.arreter());
}
});
drop(log);
drop(journal);
}
-302
View File
@@ -1,302 +0,0 @@
//! 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)
}
+3 -4
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "rustscreen",
"version": "0.5.0",
"version": "0.4.0",
"identifier": "local.rustscreen.desktop",
"build": {
"frontendDist": "../dist",
@@ -15,8 +15,7 @@
"width": 1100,
"height": 760,
"minWidth": 800,
"minHeight": 560,
"visible": false
"minHeight": 560
}
],
"security": {
@@ -25,6 +24,6 @@
},
"bundle": {
"active": false,
"icon": ["icons/icon.png", "icons/icon.ico"]
"icon": ["icons/icon.png"]
}
}
+127 -226
View File
@@ -1,286 +1,190 @@
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 { Etat } from './bindings/Etat';
import type { SourceChoisie } from './bindings/SourceChoisie';
import type { SourceProposee } from './bindings/SourceProposee';
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';
import { ChoixSource } from './components/ChoixSource';
import { PanneauPartage } from './components/PanneauPartage';
import { Reglages } from './components/Reglages';
import { I18nProvider, langueEffective, useI18n } from './i18n';
import type { Hote } from './lib/hote';
import { actions, cle, statut, textesBarre } from './lib/vue';
/**
* 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).
* La langue vient des réglages de l'hôte, ou du bureau. La changer retraduit
* l'interface et le menu de la barre système au rendu suivant (#21).
*/
export function App({ host }: { host: Host }) {
const [setting, setSetting] = useState<string | null>(null);
export function App({ hote }: { hote: Hote }) {
const [reglage, setReglage] = useState<string | null>(null);
useEffect(() => {
host.settings().then((s) => setSetting(s.language));
}, [host]);
const language = effectiveLanguage(setting, navigator.languages ?? [navigator.language]);
hote.reglages().then((r) => setReglage(r.langue));
}, [hote]);
const langue = langueEffective(reglage, navigator.languages ?? [navigator.language]);
return (
<I18nProvider language={language}>
<Shell host={host} onLanguage={setSetting} />
<I18nProvider langue={langue}>
<Interface hote={hote} onLangue={setReglage} />
</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');
function Interface({ hote, onLangue }: { hote: Hote; onLangue: (code: string | null) => void }) {
const { t, langue } = useI18n();
const [etat, setEtat] = useState<Etat | null>(null);
const [sources, setSources] = useState<SourceProposee[] | null>(null);
const [selection, setSelection] = useState<SourceChoisie | null>(null);
const [envoi, setEnvoi] = useState(false);
const [reglagesOuverts, setReglagesOuverts] = useState(false);
const [theme, setTheme] = useState<Theme>('systeme');
// The state comes from the host, always complete: subscribe before reading,
// so as not to miss a change in between.
// L'état vient de l'hôte, toujours complet: on s'abonne avant de lire, pour
// ne pas manquer un changement entre les deux.
useEffect(() => {
let unlisten: (() => void) | undefined;
let done = false;
host.listen(setState).then((stop) => {
if (done) stop();
else unlisten = stop;
let arreter: (() => void) | undefined;
let fini = false;
hote.ecouter(setEtat).then((stop) => {
if (fini) stop();
else arreter = 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));
hote.etat().then(setEtat);
hote.reglages().then((r) => setTheme(r.theme));
return () => {
done = true;
unlisten?.();
unlistenQuit?.();
fini = true;
arreter?.();
};
}, [host]);
}, [hote]);
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.
// Le menu de la barre système est dessiné par Rust: il reçoit ses textes
// dans la langue de l'interface.
useEffect(() => {
document.documentElement.lang = language;
host.translateTray(trayTexts(t)).catch(() => undefined);
}, [host, t, language]);
document.documentElement.lang = langue;
hote.traduireBarre(textesBarre(t)).catch(() => undefined);
}, [hote, t, langue]);
const refresh = useCallback(() => {
const actualiser = 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),
hote.sources().then((liste) => {
setSources(liste);
// La sélection disparue (fenêtre fermée) n'est pas gardée en silence.
setSelection((choix) =>
choix && liste.some((s) => cle(s.choix) === cle(choix)) ? choix : (liste[0]?.choix ?? null),
);
});
}, [host]);
}, [hote]);
// 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;
const phase = etat?.phase;
useEffect(() => {
if (phase === 'stopped') {
refresh();
if (phase === 'arrete') {
actualiser();
}
}, [phase, refresh]);
}, [phase, actualiser]);
if (!state) {
return <div className='loading'>{t('title')}</div>;
if (!etat) {
return <div className='chargement'>{t('titre')}</div>;
}
const buttons = actions(state, selection, sending);
const badge = status(state, t);
const send = async (command: () => Promise<unknown>) => {
setSending(true);
const boutons = actions(etat, selection, envoi);
const etiquette = statut(etat, t);
const envoyer = async (commande: () => Promise<unknown>) => {
setEnvoi(true);
try {
await command();
await commande();
} catch {
// The error also arrives in the state (`error`), which shows it.
// L'erreur arrive aussi dans l'état (`erreur`), qui l'affiche.
} finally {
setSending(false);
setEnvoi(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);
});
const portail = selection?.type === 'portail';
return (
<div className='app'>
<header className='header'>
<h1>{t('title')}</h1>
<span className={`badge ${badge.tone}`} role='status'>
{badge.text}
<header className='entete'>
<h1>{t('titre')}</h1>
<span className={`pastille ${etiquette.ton}`} role='status'>
{etiquette.texte}
</span>
{state.phase === 'live' && (
<span className='sleep' title={state.sleep_inhibited.join(', ')}>
{state.sleep_inhibited.length > 0 ? t('sleepInhibited') : t('sleepNotInhibited')}
{etat.phase === 'en_cours' && (
<span className='veille' title={etat.veille_inhibee.join(', ')}>
{etat.veille_inhibee.length > 0 ? t('veille') : t('veilleAbsente')}
</span>
)}
<span className='spacer' />
<button type='button' className='button muted' onClick={() => setSettingsOpen(true)}>
{t('settings')}
<span className='espace' />
<button type='button' className='bouton discret' onClick={() => setReglagesOuverts(true)}>
{t('reglages')}
</button>
</header>
<main className='content'>
<Banners state={state} />
<main className='contenu'>
<Bandeaux etat={etat} />
{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))}
{etat.phase === 'en_cours' && etat.partage ? (
<PanneauPartage
partage={etat.partage}
onDeconnecter={(connexion) => envoyer(() => hote.deconnecter(connexion))}
onNouveauCode={() => envoyer(() => hote.regenererAcces())}
/>
) : (
<SourcePicker
<ChoixSource
sources={sources}
selection={selection}
enabled={buttons.pick || picking}
onPick={setSelection}
onRefresh={refresh}
onVirtualSize={changeVirtualSize}
actif={boutons.choisir}
onChoisir={setSelection}
onActualiser={actualiser}
/>
)}
</main>
<footer className='action-bar'>
{(state.phase === 'starting' || (picking && sending)) && (
<p className='waiting' role='status'>
{portal ? t('waitingDesktop') : t('waiting')}
<footer className='barre'>
{etat.phase === 'demarrage' && (
<p className='attente' role='status'>
{portail ? t('attenteBureau') : t('attente')}
</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 && (
<span className='espace' />
{boutons.demarrer.visible && (
<button
type='button'
className='button'
title={t('switchHelp')}
disabled={sending}
onClick={() => {
setSelection(null);
refresh();
setSwitching(true);
}}
className='bouton principal'
disabled={!boutons.demarrer.actif}
onClick={() => selection && envoyer(() => hote.demarrer(selection))}
>
{t('switchSource')}
{t('demarrer')}
</button>
)}
{buttons.start.visible && (
{boutons.annuler.visible && (
<button
type='button'
className='button primary'
disabled={!buttons.start.enabled}
onClick={() => selection && send(() => host.start(selection))}
className='bouton'
disabled={!boutons.annuler.actif}
onClick={() => hote.arreter()}
>
{t('start')}
{t('annuler')}
</button>
)}
{buttons.cancel.visible && (
{boutons.arreter.visible && (
<button
type='button'
className='button'
disabled={!buttons.cancel.enabled}
onClick={() => host.stop()}
className='bouton danger'
disabled={!boutons.arreter.actif}
onClick={() => envoyer(() => hote.arreter())}
>
{t('cancel')}
</button>
)}
{buttons.stop.visible && (
<button
type='button'
className='button danger'
disabled={!buttons.stop.enabled}
onClick={() => send(() => host.stop())}
>
{t('stop')}
{t('arreter')}
</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();
{reglagesOuverts && (
<Reglages
hote={hote}
demarrageAuto={etat.capacites.demarrage_auto}
onFermer={() => setReglagesOuverts(false)}
onEnregistre={(r) => {
setTheme(r.theme);
onLangue(r.langue);
}}
/>
)}
@@ -288,32 +192,29 @@ function Shell({ host, onLanguage }: { host: Host; onLanguage: (code: string | n
);
}
function Banners({ state }: { state: HostState }) {
function Bandeaux({ etat }: { etat: Etat }) {
const { t } = useI18n();
return (
<>
{state.error && state.phase === 'stopped' && (
<div className='banner error' role='alert'>
<strong>{t('startFailed')}</strong> {say(state.error, t)}
{etat.erreur && etat.phase === 'arrete' && (
<div className='bandeau erreur' role='alert'>
<strong>{t('erreurDemarrage')}</strong> {etat.erreur}
</div>
)}
{state.stop && state.phase === 'stopped' && (
<div className='banner error' role='alert'>
<strong>{t('stoppedByDesktop')}</strong> {say(state.stop.reason, t)}
{etat.arret && etat.phase === 'arrete' && (
<div className='bandeau erreur' role='alert'>
<strong>{t('arretBureau')}</strong> {etat.arret.raison}
</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)}
{etat.reglages_recuperes && <div className='bandeau alerte'>{etat.reglages_recuperes}</div>}
{etat.avertissements.map((a) => (
<div key={a} className='bandeau alerte' role='alert'>
{a}
</div>
))}
{state.pending_settings.length > 0 && (
<div className='banner info'>
<strong>{t('pendingSettings')}</strong>{' '}
{state.pending_settings.map((n) => say(n, t)).join('; ')}
{etat.reglages_en_attente.length > 0 && (
<div className='bandeau info'>
<strong>{t('enAttente')}</strong> {etat.reglages_en_attente.join('; ')}
</div>
)}
</>
@@ -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 { DeviceId } from "../../../viewer/src/proto/DeviceId";
/**
* Un appareil autorisé à revenir sans rescanner (#34). Le stockage existe dès
* maintenant pour que le format n'ait pas à changer de version ce jour-là.
*/
export type AppareilConfiance = { id: DeviceId, nom: string, };
+14
View File
@@ -0,0 +1,14 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* Un spectateur connecté.
*/
export type AppareilVu = {
/**
* Numéro à renvoyer pour le déconnecter.
*/
connexion: number, nom: string, plateforme: string | null, adresse: string,
/**
* Arrivée, en millisecondes Unix.
*/
depuis_ms: number, };
+14
View File
@@ -0,0 +1,14 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* Ce que produit une modification de réglages.
*/
export type Application = {
/**
* Champs appliqués tout de suite.
*/
immediats: Array<string>,
/**
* Champs qui attendent le prochain partage, avec la raison.
*/
au_prochain_partage: Array<string>, };
+11
View File
@@ -0,0 +1,11 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* Pourquoi le dernier partage s'est arrêté, quand ce n'est pas l'utilisateur.
*/
export type Arret = { raison: string,
/**
* Arrêté depuis le bureau (bouton « arrêter le partage », écran
* débranché): la ligne de commande sort alors avec le code 3.
*/
par_le_bureau: boolean, };
-15
View File
@@ -1,15 +0,0 @@
// 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, };
+15
View File
@@ -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 Capacites = {
/**
* `wayland`, `x11` ou `aucune`.
*/
session: string, bureau: string, portail: boolean, ecran_virtuel: boolean,
/**
* Le binaire sait consommer un flux PipeWire (feature `pipewire`).
*/
pipewire: boolean,
/**
* Le démarrage automatique est réglable depuis cette application.
*/
demarrage_auto: boolean, };
-6
View File
@@ -1,6 +0,0 @@
// 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";
+3 -3
View File
@@ -1,7 +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`).
* Codec vidéo des partages (#67). VP9 garde la même qualité pour moins de
* débit, mais coûte 1,6x le calcul de VP8 (`docs/perf.md`).
*/
export type Codec = "vp8" | "vp9" | "h264";
export type Codec = "vp8" | "vp9";
-7
View File
@@ -1,7 +0,0 @@
// 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, };
+36
View File
@@ -0,0 +1,36 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { Arret } from "./Arret";
import type { Capacites } from "./Capacites";
import type { Partage } from "./Partage";
import type { Phase } from "./Phase";
/**
* Tout l'état de l'hôte.
*/
export type Etat = { phase: Phase, partage: Partage | null,
/**
* Échec du dernier démarrage, à afficher tel quel.
*/
erreur: string | null, arret: Arret | null,
/**
* Ce qui marche encore mais mérite d'être su (interface coupée, adresse
* changée).
*/
avertissements: Array<string>,
/**
* Mécanismes d'inhibition de veille tenus (`login1`, `screensaver`):
* vide hors partage, ou si aucun n'a pu être pris.
*/
veille_inhibee: Array<string>,
/**
* Réglages modifiés pendant le partage, appliqués au prochain.
*/
reglages_en_attente: Array<string>,
/**
* Le fichier de réglages était inutilisable au démarrage: ce qui a été fait.
*/
reglages_recuperes: string | null,
/**
* Capacités de cette machine, pour ne proposer que ce qui marche.
*/
capacites: Capacites, };
+6
View File
@@ -0,0 +1,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* Ce que fait la fermeture de la fenêtre de l'application de bureau (#22).
*/
export type Fermeture = "barre_systeme" | "quitter";
-37
View File
@@ -1,37 +0,0 @@
// 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, };
@@ -1,6 +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.
* Une interface réseau proposée dans les réglages.
*/
export type InterfaceOption = { name: string, addresses: Array<string>, active: boolean, };
export type InterfaceProposee = { nom: string, adresses: Array<string>, active: boolean, };
-7
View File
@@ -1,7 +0,0 @@
// 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" };
+7
View File
@@ -0,0 +1,7 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* Ce que l'interface affiche comme nom d'une source, dans sa langue (#21).
* Seul un titre de fenêtre ou un nom de sortie vient tel quel du système.
*/
export type Libelle = { "type": "titre", texte: string, } | { "type": "moniteur", sortie: string, principal: boolean, } | { "type": "ecran" } | { "type": "fenetre" } | { "type": "ecran_virtuel" } | { "type": "mire" } | { "type": "mire_enregistree" } | { "type": "tous_les_ecrans" } | { "type": "ecran_entier" } | { "type": "ecran_choisi" } | { "type": "fenetre_choisie" };
@@ -1,19 +0,0 @@
// 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, };
+7
View File
@@ -0,0 +1,7 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* Ce qu'il faut savoir d'une source avant de la choisir, traduit par
* l'interface.
*/
export type NoteSource = "portail_ecran" | "portail_fenetre" | "portail_sans_fenetre" | "ecran_virtuel" | "mire" | "sans_pipewire" | "reduite";
-16
View File
@@ -1,16 +0,0 @@
// 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, };
+42
View File
@@ -0,0 +1,42 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { AppareilVu } from "./AppareilVu";
import type { SourcePartagee } from "./SourcePartagee";
/**
* Un partage en cours.
*/
export type Partage = { source: SourcePartagee, room: string,
/**
* L'URL à donner, jeton compris, sur l'adresse du LAN.
*/
url: string,
/**
* Le QR code de `url`, en SVG.
*/
qr_svg: string,
/**
* Code court à taper sans caméra, en minuscules: l'interface le groupe.
*/
code: string,
/**
* Échéance du jeton et du code, en millisecondes Unix. `None`: sans
* limite.
*/
expire_ms: number | null,
/**
* L'échéance est passée: plus aucun nouvel appareil n'entre tant que
* l'hôte n'a pas tiré un nouveau code.
*/
acces_expire: boolean,
/**
* Empreinte SHA-256 du certificat, en HTTPS seulement.
*/
empreinte: string | null,
/**
* Adresse et port d'écoute réels (`0.0.0.0:8099`, `192.168.1.20:9000`).
*/
ecoute: string,
/**
* Interface choisie, `None` si l'hôte écoute partout.
*/
interface: string | null, appareils: Array<AppareilVu>, limite: number, demarre_ms: number, };
+2 -2
View File
@@ -1,6 +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.
* Où en est le partage.
*/
export type Phase = "stopped" | "starting" | "live";
export type Phase = "arrete" | "demarrage" | "en_cours";
+7
View File
@@ -0,0 +1,7 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* Une valeur refusée, nommée par son champ: l'interface la place à côté du
* champ fautif, et le message se lit tel quel.
*/
export type Refus = { champ: string, message: string, };
-17
View File
@@ -1,17 +0,0 @@
// 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, };
@@ -1,6 +0,0 @@
// 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";
+47
View File
@@ -0,0 +1,47 @@
// 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 { AppareilConfiance } from "./AppareilConfiance";
import type { Codec } from "./Codec";
import type { Fermeture } from "./Fermeture";
import type { Theme } from "./Theme";
/**
* Tout ce qui est réglable, en un seul endroit.
*
* `#[serde(default)]`: un fichier écrit par une version qui ignorait un champ
* se lit quand même, le champ prend sa valeur par défaut.
*/
export type Reglages = { version: number,
/**
* Port d'écoute du serveur (viewer et signalement).
*/
port: number,
/**
* Nom de l'interface réseau sur laquelle écouter (`wlp2s0`, `enp3s0`).
* `None`: toutes les interfaces.
*/
interface: string | null, theme: Theme,
/**
* Code de langue de l'interface (`fr`, `en`, `pt-BR`), parmi les
* fichiers de `locales/` (#21). `None`: celle du bureau. Un code, pas une
* liste fermée: ajouter une langue ne change pas ce format.
*/
langue: string | null,
/**
* Spectateurs simultanés.
*/
limite: number,
/**
* Qualité proposée au démarrage d'un partage.
*/
qualite: QualityPreset, codec: Codec,
/**
* Minutes pendant lesquelles le QR code et le code court font entrer un
* nouvel appareil (#19). `0`: sans limite. Les appareils déjà admis
* reviennent après l'échéance.
*/
validite_code_min: number,
/**
* Lancer l'hôte à l'ouverture de session (#32).
*/
demarrage_auto: boolean, fermeture: Fermeture, appareils_confiance: Array<AppareilConfiance>, };
-8
View File
@@ -1,8 +0,0 @@
// 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, };
-78
View File
@@ -1,78 +0,0 @@
// 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, };
@@ -1,16 +0,0 @@
// 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>, };
-54
View File
@@ -1,54 +0,0 @@
// 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, };
-16
View File
@@ -1,16 +0,0 @@
// 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, };
-15
View File
@@ -1,15 +0,0 @@
// 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,15 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* Ce que l'utilisateur choisit de partager. L'interface renvoie tel quel le
* `choix` d'une [`SourceProposee`].
*/
export type SourceChoisie = { "type": "synthetique", largeur: number, hauteur: number, } | { "type": "x11", id: string, } | { "type": "portail", virtuel: boolean,
/**
* Une fenêtre plutôt qu'un écran (#17), si le portail le permet.
*/
fenetre: boolean,
/**
* Taille d'un écran virtuel. Ignorée pour un écran existant.
*/
taille: [number, number] | null, } | { "type": "mire", chemin: string, };
-7
View File
@@ -1,7 +0,0 @@
// 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";
-35
View File
@@ -1,35 +0,0 @@
// 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,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 { Libelle } from "./Libelle";
/**
* La source en cours de partage.
*/
export type SourcePartagee = { genre: SourceKind, nom: string, libelle: Libelle,
/**
* `portail`, `x11`, `synthetique` ou `ivf`.
*/
chemin: string,
/**
* Taille encodée courante: elle suit un changement de résolution.
*/
largeur: number, hauteur: number, };
@@ -0,0 +1,36 @@
// 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 { Libelle } from "./Libelle";
import type { NoteSource } from "./NoteSource";
import type { SourceChoisie } from "./SourceChoisie";
/**
* Une source proposée dans la liste.
*/
export type SourceProposee = { choix: SourceChoisie, genre: SourceKind,
/**
* Nom en français, pour la ligne de commande. Un titre de fenêtre peut
* s'y trouver: il reste dans l'interface locale, jamais dans le journal
* (ADR 0008).
*/
nom: string,
/**
* Le nom à afficher, que l'interface traduit.
*/
libelle: Libelle, largeur: number, hauteur: number,
/**
* Vignette en `data:image/png`, quand la plateforme permet d'en prendre
* une sans consentement (X11). Jamais sous Wayland: le portail ne montre
* rien avant l'accord de l'utilisateur.
*/
vignette: string | null,
/**
* Ce qu'il faut savoir avant de choisir (« le bureau demandera lequel »).
*/
note: NoteSource | null,
/**
* Faux pour une source listée mais pas partageable maintenant (fenêtre
* réduite, bureau qui ne sait pas partager une fenêtre): la note dit
* pourquoi, avant le démarrage et pas après (#17).
*/
disponible: boolean, };
-12
View File
@@ -1,12 +0,0 @@
// 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, };
+2 -2
View File
@@ -1,6 +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.
* Thème de l'interface de l'hôte.
*/
export type Theme = "system" | "light" | "dark";
export type Theme = "systeme" | "clair" | "sombre";
@@ -1,19 +0,0 @@
// 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, };
-38
View File
@@ -1,38 +0,0 @@
// 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,83 @@
import { useMemo, useState } from 'react';
import type { SourceChoisie } from '../bindings/SourceChoisie';
import type { SourceProposee } from '../bindings/SourceProposee';
import { useI18n } from '../i18n';
import { cle, filtrer, nomAffiche } from '../lib/vue';
type Props = {
sources: SourceProposee[] | null;
selection: SourceChoisie | null;
actif: boolean;
onChoisir: (choix: SourceChoisie) => void;
onActualiser: () => void;
};
/** Au-delà, la liste devient longue à parcourir: la recherche apparaît. */
const SEUIL_RECHERCHE = 6;
export function ChoixSource({ sources, selection, actif, onChoisir, onActualiser }: Props) {
const { t } = useI18n();
const [recherche, setRecherche] = useState('');
const visibles = useMemo(() => filtrer(sources ?? [], recherche, t), [sources, recherche, t]);
const choisie = selection ? cle(selection) : null;
return (
<section className='choix' aria-labelledby='choix-titre'>
<div className='choix-entete'>
<h2 id='choix-titre'>{t('choisirTitre')}</h2>
{sources && sources.length > SEUIL_RECHERCHE && (
<input
type='search'
className='recherche'
placeholder={t('recherche')}
aria-label={t('recherche')}
value={recherche}
onChange={(e) => setRecherche(e.target.value)}
/>
)}
<button type='button' className='bouton discret' onClick={onActualiser} disabled={!actif}>
{t('actualiser')}
</button>
</div>
{sources === null && <p className='aide'>{t('chargementSources')}</p>}
{sources !== null && visibles.length === 0 && <p className='aide'>{t('aucuneSource')}</p>}
<ul className='sources'>
{visibles.map((source) => {
const id = cle(source.choix);
const nom = nomAffiche(source.libelle, t);
const selectionnee = id === choisie;
return (
<li key={id}>
<button
type='button'
className={`source${selectionnee ? ' selectionnee' : ''}${source.disponible ? '' : ' indisponible'}`}
aria-pressed={selectionnee}
disabled={!actif || !source.disponible}
onClick={() => onChoisir(source.choix)}
>
<span className='vignette'>
{source.vignette ? (
<img src={source.vignette} alt='' />
) : (
<span className='vignette-vide' aria-hidden='true'>
{source.genre === 'window' ? '▭' : '▣'}
</span>
)}
</span>
<span className='source-nom' title={nom}>
{nom}
</span>
{source.largeur > 0 && (
<span className='source-taille'>
{source.largeur} × {source.hauteur}
</span>
)}
{source.note && <span className='source-note'>{t(`notes.${source.note}`)}</span>}
</button>
</li>
);
})}
</ul>
</section>
);
}
@@ -1,52 +0,0 @@
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,142 @@
import { useEffect, useState } from 'react';
import type { Partage } from '../bindings/Partage';
import { useI18n } from '../i18n';
import { codeAffiche, duree, echeance, nomAffiche } from '../lib/vue';
type Props = {
partage: Partage;
onDeconnecter: (connexion: number) => void;
onNouveauCode: () => void;
};
export function PanneauPartage({ partage, onDeconnecter, onNouveauCode }: Props) {
const { t } = useI18n();
const maintenant = useMaintenant();
const [copie, setCopie] = useState(false);
const copier = async () => {
try {
await navigator.clipboard.writeText(partage.url);
setCopie(true);
setTimeout(() => setCopie(false), 1500);
} catch {
setCopie(false);
}
};
const [hote] = partage.ecoute.split(':');
const accueil = partage.url.split('/r/')[0] ?? partage.url;
const reste = echeance(partage.expire_ms, maintenant, t);
return (
<section className='partage'>
<div className='carte qr-carte'>
<h2>{t('scanner')}</h2>
{/* SVG produit par l'hôte (rs-signaling::qr), jamais par une entrée extérieure. */}
<div
className='qr'
role='img'
aria-label={partage.url}
// biome-ignore lint/security/noDangerouslySetInnerHtml: SVG généré par l'hôte local
dangerouslySetInnerHTML={{ __html: partage.qr_svg }}
/>
<label className='lien'>
<span>{t('lien')}</span>
<span className='lien-ligne'>
<input readOnly value={partage.url} onFocus={(e) => e.target.select()} />
<button type='button' className='bouton' onClick={copier}>
{copie ? t('copie') : t('copier')}
</button>
</span>
</label>
<div className={`code-court ${partage.acces_expire ? 'code-expire' : ''}`}>
<span className='discret'>
{t('code')} {t('codeAide', { accueil })}
</span>
<strong className='code-valeur' aria-live='polite'>
{codeAffiche(partage.code)}
</strong>
{reste && (
<span className={partage.acces_expire ? 'alerte-texte' : 'discret'}>{reste}</span>
)}
<button
type='button'
className='bouton discret code-nouveau'
title={t('nouveauCodeAide')}
onClick={onNouveauCode}
>
{t('nouveauCode')}
</button>
</div>
{partage.empreinte && (
<p className='empreinte'>
{t('empreinte')}: <code>{partage.empreinte}</code>
</p>
)}
</div>
<div className='carte'>
<dl className='faits'>
<dt>{t('source')}</dt>
<dd>
{nomAffiche(partage.source.libelle, t)}
<span className='discret'>
{' '}
{partage.source.largeur} × {partage.source.hauteur}
</span>
</dd>
<dt>{t('ecoute')}</dt>
<dd>
{partage.interface ? `${partage.interface} (${hote})` : t('toutesInterfaces')}
<span className='discret'>
{' '}
{t('port', { port: partage.ecoute.split(':').pop() ?? '' })}
</span>
</dd>
<dt>{t('depuis')}</dt>
<dd>{duree(partage.demarre_ms, maintenant)}</dd>
</dl>
<h2 className='spectateurs-titre'>
{t('spectateurs')}
<span className='compteur'>
{t('places', { n: partage.appareils.length, limite: partage.limite })}
</span>
</h2>
{partage.appareils.length === 0 ? (
<p className='aide'>{t('personne')}</p>
) : (
<ul className='appareils'>
{partage.appareils.map((appareil) => (
<li key={appareil.connexion}>
<span className='appareil-nom'>{appareil.nom}</span>
<span className='discret'>
{[appareil.plateforme, appareil.adresse].filter(Boolean).join(' · ')}
{' · '}
{duree(appareil.depuis_ms, maintenant)}
</span>
<button
type='button'
className='bouton discret danger'
title={t('deconnecterAide')}
onClick={() => onDeconnecter(appareil.connexion)}
>
{t('deconnecter')}
</button>
</li>
))}
</ul>
)}
</div>
</section>
);
}
/** L'heure courante, rafraîchie chaque seconde pour les durées affichées. */
function useMaintenant(): number {
const [maintenant, setMaintenant] = useState(() => Date.now());
useEffect(() => {
const minuterie = setInterval(() => setMaintenant(Date.now()), 1000);
return () => clearInterval(minuterie);
}, []);
return maintenant;
}
+304
View File
@@ -0,0 +1,304 @@
import { useEffect, useId, useState } from 'react';
import type { QualityPreset } from '../../../viewer/src/proto/QualityPreset';
import type { Application } from '../bindings/Application';
import type { Codec } from '../bindings/Codec';
import type { Fermeture } from '../bindings/Fermeture';
import type { InterfaceProposee } from '../bindings/InterfaceProposee';
import type { Refus } from '../bindings/Refus';
import type { Reglages as ReglagesHote } from '../bindings/Reglages';
import type { Theme } from '../bindings/Theme';
import { LANGUES, useI18n } from '../i18n';
import { type Hote, refusDe } from '../lib/hote';
import { resumeApplication } from '../lib/vue';
const QUALITES: QualityPreset[] = ['saver', 'balanced', 'sharp'];
const CODECS: Codec[] = ['vp8', 'vp9'];
const THEMES: Theme[] = ['systeme', 'clair', 'sombre'];
const FERMETURES: Fermeture[] = ['barre_systeme', 'quitter'];
type Props = {
hote: Hote;
demarrageAuto: boolean;
onFermer: () => void;
onEnregistre: (reglages: ReglagesHote) => void;
};
export function Reglages({ hote, demarrageAuto, onFermer, onEnregistre }: Props) {
const { t } = useI18n();
const [reglages, setReglages] = useState<ReglagesHote | null>(null);
const [interfaces, setInterfaces] = useState<InterfaceProposee[]>([]);
const [refus, setRefus] = useState<Refus[]>([]);
// Ce qu'on garde est le fait, pas sa phrase: changer de langue en
// enregistrant retraduit aussi la confirmation.
const [message, setMessage] = useState<
| { type: 'application'; application: Application }
| { type: 'diagnostics'; chemin: string }
| null
>(null);
const [envoi, setEnvoi] = useState(false);
const id = useId();
useEffect(() => {
hote.reglages().then(setReglages);
hote.interfaces().then(setInterfaces);
}, [hote]);
if (!reglages) {
return null;
}
const changer = <K extends keyof ReglagesHote>(champ: K, valeur: ReglagesHote[K]) => {
setReglages({ ...reglages, [champ]: valeur });
setRefus((r) => r.filter((x) => x.champ !== champ));
setMessage(null);
};
const erreur = (champ: string) => refus.find((r) => r.champ === champ)?.message;
const enregistrer = async () => {
setEnvoi(true);
try {
const application = await hote.modifierReglages(reglages);
setRefus([]);
setMessage({ type: 'application', application });
onEnregistre(reglages);
} catch (e) {
setRefus(refusDe(e));
setMessage(null);
} finally {
setEnvoi(false);
}
};
const exporter = async () => {
try {
setMessage({ type: 'diagnostics', chemin: await hote.exporterDiagnostics() });
} catch (e) {
setRefus([{ champ: 'diagnostics', message: String(e) }]);
}
};
// Une interface choisie mais absente de la liste (débranchée) reste
// affichée, pour que le réglage enregistré ne disparaisse pas en silence.
const absente =
reglages.interface !== null && !interfaces.some((i) => i.nom === reglages.interface);
return (
<div className='voile'>
<div
className='dialogue'
role='dialog'
aria-modal='true'
aria-labelledby={`${id}-titre`}
onKeyDown={(e) => e.key === 'Escape' && onFermer()}
>
<h2 id={`${id}-titre`}>{t('reglages')}</h2>
<form
className='formulaire'
onSubmit={(e) => {
e.preventDefault();
enregistrer();
}}
>
<Champ
id={`${id}-port`}
libelle={t('portChamp')}
aide={t('portAide')}
erreur={erreur('port')}
>
<input
id={`${id}-port`}
type='number'
min={1024}
max={65535}
value={reglages.port}
onChange={(e) => changer('port', Number(e.target.value))}
/>
</Champ>
<Champ
id={`${id}-interface`}
libelle={t('interface')}
aide={t('interfaceAide')}
erreur={erreur('interface')}
>
<select
id={`${id}-interface`}
value={reglages.interface ?? ''}
onChange={(e) => changer('interface', e.target.value === '' ? null : e.target.value)}
>
<option value=''>{t('toutesInterfaces')}</option>
{interfaces.map((i) => (
<option key={i.nom} value={i.nom}>
{i.nom} ({i.adresses.join(', ')}){i.active ? '' : `, ${t('interfaceInactive')}`}
</option>
))}
{absente && reglages.interface && (
<option value={reglages.interface}>
{reglages.interface}, {t('interfaceInactive')}
</option>
)}
</select>
</Champ>
<Champ id={`${id}-limite`} libelle={t('limite')} erreur={erreur('limite')}>
<input
id={`${id}-limite`}
type='number'
min={1}
max={20}
value={reglages.limite}
onChange={(e) => changer('limite', Number(e.target.value))}
/>
</Champ>
<Champ
id={`${id}-validite`}
libelle={t('validite')}
aide={t('validiteAide')}
erreur={erreur('validite_code_min')}
>
<input
id={`${id}-validite`}
type='number'
min={0}
max={1440}
value={reglages.validite_code_min}
onChange={(e) => changer('validite_code_min', Number(e.target.value))}
/>
</Champ>
<Champ id={`${id}-qualite`} libelle={t('qualite')} erreur={erreur('qualite')}>
<select
id={`${id}-qualite`}
value={reglages.qualite}
onChange={(e) => changer('qualite', e.target.value as QualityPreset)}
>
{QUALITES.map((q) => (
<option key={q} value={q}>
{t(`qualites.${q}`)}
</option>
))}
</select>
</Champ>
<Champ
id={`${id}-codec`}
libelle={t('codec')}
aide={t('codecAide')}
erreur={erreur('codec')}
>
<select
id={`${id}-codec`}
value={reglages.codec}
onChange={(e) => changer('codec', e.target.value as Codec)}
>
{CODECS.map((c) => (
<option key={c} value={c}>
{t(`codecs.${c}`)}
</option>
))}
</select>
</Champ>
<Champ id={`${id}-theme`} libelle={t('theme')}>
<select
id={`${id}-theme`}
value={reglages.theme}
onChange={(e) => changer('theme', e.target.value as Theme)}
>
{THEMES.map((theme) => (
<option key={theme} value={theme}>
{t(`themes.${theme}`)}
</option>
))}
</select>
</Champ>
<Champ id={`${id}-langue`} libelle={t('langue')}>
<select
id={`${id}-langue`}
value={reglages.langue ?? ''}
onChange={(e) => changer('langue', e.target.value === '' ? null : e.target.value)}
>
<option value=''>{t('langueSysteme')}</option>
{LANGUES.map((l) => (
<option key={l.code} value={l.code} lang={l.code}>
{l.nom}
</option>
))}
</select>
</Champ>
<Champ id={`${id}-fermeture`} libelle={t('fermeture')} aide={t('fermetureAide')}>
<select
id={`${id}-fermeture`}
value={reglages.fermeture}
onChange={(e) => changer('fermeture', e.target.value as Fermeture)}
>
{FERMETURES.map((f) => (
<option key={f} value={f}>
{t(`fermetures.${f}`)}
</option>
))}
</select>
</Champ>
{demarrageAuto && (
<label className='case'>
<input
type='checkbox'
checked={reglages.demarrage_auto}
onChange={(e) => changer('demarrage_auto', e.target.checked)}
/>
{t('demarrageAuto')}
{erreur('demarrage_auto') && (
<span className='erreur-champ'>{erreur('demarrage_auto')}</span>
)}
</label>
)}
{erreur('fichier') && <p className='erreur-champ'>{erreur('fichier')}</p>}
{message && (
<p className='confirmation' role='status'>
{message.type === 'application'
? resumeApplication(message.application, t)
: t('diagnosticsEcrits', { chemin: message.chemin })}
</p>
)}
<div className='pied'>
<button type='button' className='bouton discret' onClick={exporter}>
{t('diagnostics')}
</button>
<span className='espace' />
<button type='button' className='bouton discret' onClick={onFermer}>
{t('fermer')}
</button>
<button type='submit' className='bouton principal' disabled={envoi}>
{t('enregistrer')}
</button>
</div>
<p className='aide'>{t('diagnosticsAide')}</p>
{erreur('diagnostics') && <p className='erreur-champ'>{erreur('diagnostics')}</p>}
</form>
</div>
</div>
);
}
function Champ({
id,
libelle,
aide,
erreur,
children,
}: {
id: string;
libelle: string;
aide?: string;
erreur?: string | undefined;
children: React.ReactNode;
}) {
return (
<div className={`champ${erreur ? ' en-erreur' : ''}`}>
<label htmlFor={id}>{libelle}</label>
{children}
{erreur ? (
<span className='erreur-champ' role='alert'>
{erreur}
</span>
) : (
aide && <span className='aide'>{aide}</span>
)}
</div>
);
}
@@ -1,397 +0,0 @@
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>
);
}
-255
View File
@@ -1,255 +0,0 @@
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;
}
@@ -1,205 +0,0 @@
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>
);
}
+39 -39
View File
@@ -1,66 +1,66 @@
import { createContext, type ReactNode, useContext, useMemo } from 'react';
import {
type AvailableLanguage,
type Catalog,
createTranslator,
FALLBACK_LANGUAGE,
pickLanguage,
type Translate,
type Catalogue,
choisirLangue,
LANGUE_DE_REPLI,
type LangueDisponible,
type Traduire,
traduction,
} 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.
* Textes de la coque (#21). Les mêmes fichiers que le viewer
* (`locales/*.json`), embarqués à la compilation: la coque n'a pas de serveur
* à interroger quand aucun partage ne tourne. Un fichier ajouté au dossier est
* une langue de plus, sans code à changer.
*/
type LocaleFile = Catalog & { _language: AvailableLanguage };
type Fichier = Catalogue & { _langue: LangueDisponible };
const FILES = Object.values(
import.meta.glob<LocaleFile>('../../../locales/*.json', { eager: true, import: 'default' }),
const FICHIERS = Object.values(
import.meta.glob<Fichier>('../../../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),
/** Les langues embarquées, par code. */
export const LANGUES: LangueDisponible[] = FICHIERS.map((f) => f._langue).sort((a, b) =>
a.nom.localeCompare(b.nom),
);
function catalog(code: string): Catalog | undefined {
return FILES.find((f) => f._language.code === code);
function catalogue(code: string): Catalogue | undefined {
return FICHIERS.find((f) => f._langue.code === code);
}
/**
* The language to display: the setting if it names an embedded language,
* otherwise the desktop's (`navigator.languages` reflects the session locale).
* La langue à afficher: le réglage s'il désigne une langue embarquée, sinon
* celle du bureau (`navigator.languages` reflète la locale de la session).
*/
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);
export function langueEffective(reglage: string | null, preferences: readonly string[]): string {
const codes = LANGUES.map((l) => l.code);
if (reglage && codes.includes(reglage)) return reglage;
return choisirLangue(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,
/** La traduction de la coque dans `code`, l'anglais en repli. */
export function traductionPour(code: string): Traduire {
const catalogues = [catalogue(code), catalogue(LANGUE_DE_REPLI)].filter(
(c): c is Catalogue => c !== undefined,
);
return createTranslator(code, 'desktop', catalogs);
return traduction(code, 'desktop', catalogues);
}
type Context = { t: Translate; language: string };
type Contexte = { t: Traduire; langue: string };
const I18n = createContext<Context | null>(null);
const I18n = createContext<Contexte | null>(null);
export function useI18n(): Context {
const context = useContext(I18n);
if (!context) throw new Error('useI18n outside of I18nProvider');
return context;
export function useI18n(): Contexte {
const contexte = useContext(I18n);
if (!contexte) throw new Error('useI18n hors de I18nProvider');
return contexte;
}
/** 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>;
/** Changer `langue` retraduit tout au rendu suivant, sans redémarrer. */
export function I18nProvider({ langue, children }: { langue: string; children: ReactNode }) {
const valeur = useMemo(() => ({ t: traductionPour(langue), langue }), [langue]);
return <I18n.Provider value={valeur}>{children}</I18n.Provider>;
}
-74
View File
@@ -1,74 +0,0 @@
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) }];
}
+57
View File
@@ -0,0 +1,57 @@
import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
import type { Application } from '../bindings/Application';
import type { Etat } from '../bindings/Etat';
import type { InterfaceProposee } from '../bindings/InterfaceProposee';
import type { Refus } from '../bindings/Refus';
import type { Reglages } from '../bindings/Reglages';
import type { SourceChoisie } from '../bindings/SourceChoisie';
import type { SourceProposee } from '../bindings/SourceProposee';
import type { TextesBarre } from './vue';
/**
* Ce que l'interface peut demander à l'hôte. Une seule implémentation réelle,
* par les commandes Tauri; les tests en fournissent une fausse.
*/
export type Hote = {
etat(): Promise<Etat>;
/** Rend la fonction qui arrête l'écoute. */
ecouter(rappel: (etat: Etat) => void): Promise<() => void>;
sources(): Promise<SourceProposee[]>;
demarrer(choix: SourceChoisie): Promise<void>;
arreter(): Promise<void>;
deconnecter(connexion: number): Promise<boolean>;
/** Nouveau QR code et nouveau code court (#19). */
regenererAcces(): Promise<boolean>;
reglages(): Promise<Reglages>;
/** Rejette avec la liste des valeurs refusées. */
modifierReglages(reglages: Reglages): Promise<Application>;
interfaces(): Promise<InterfaceProposee[]>;
/** Rend le chemin de l'archive écrite. */
exporterDiagnostics(): Promise<string>;
/** Les textes du menu de la barre système, dans la langue de l'interface. */
traduireBarre(textes: TextesBarre): Promise<void>;
};
export const hoteTauri: Hote = {
etat: () => invoke<Etat>('etat'),
ecouter: (rappel) => listen<Etat>('etat', (evenement) => rappel(evenement.payload)),
sources: () => invoke<SourceProposee[]>('sources'),
demarrer: (choix) => invoke<void>('demarrer', { choix }),
arreter: () => invoke<void>('arreter'),
deconnecter: (connexion) => invoke<boolean>('deconnecter', { connexion }),
regenererAcces: () => invoke<boolean>('regenerer_acces'),
reglages: () => invoke<Reglages>('reglages'),
modifierReglages: (reglages) => invoke<Application>('modifier_reglages', { reglages }),
interfaces: () => invoke<InterfaceProposee[]>('interfaces'),
exporterDiagnostics: () => invoke<string>('exporter_diagnostics'),
traduireBarre: (textes) => invoke<void>('traduire_barre', { textes }),
};
/** Les refus du Rust arrivent tels quels; tout autre rejet devient un refus global. */
export function refusDe(erreur: unknown): Refus[] {
if (Array.isArray(erreur)) {
return erreur as Refus[];
}
return [{ champ: 'fichier', message: String(erreur) }];
}
-253
View File
@@ -1,253 +0,0 @@
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));
});
});
-269
View File
@@ -1,269 +0,0 @@
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'),
};
}
+176
View File
@@ -0,0 +1,176 @@
import { describe, expect, it } from 'vitest';
import type { Etat } from '../bindings/Etat';
import type { Partage } from '../bindings/Partage';
import type { SourceProposee } from '../bindings/SourceProposee';
import { LANGUES, langueEffective, traductionPour } from '../i18n';
import {
actions,
cle,
codeAffiche,
duree,
echeance,
filtrer,
resumeApplication,
nomAffiche,
statut,
textesBarre,
} from './vue';
const t = traductionPour('fr');
function etat(phase: Etat['phase'], partage: Partage | null = null): Etat {
return {
phase,
partage,
erreur: null,
arret: null,
avertissements: [],
veille_inhibee: [],
reglages_en_attente: [],
reglages_recuperes: null,
capacites: {
session: 'wayland',
bureau: 'Gnome',
portail: true,
ecran_virtuel: true,
pipewire: true,
demarrage_auto: true,
},
};
}
const mire = { type: 'synthetique', largeur: 1280, hauteur: 720 } as const;
describe('les boutons suivent l’état de l’hôte (#15, pas de bouton qui ment)', () => {
it('arrêté: démarrer seulement avec une source choisie', () => {
expect(actions(etat('arrete'), null, false).demarrer).toEqual({ visible: true, actif: false });
expect(actions(etat('arrete'), mire, false).demarrer).toEqual({ visible: true, actif: true });
expect(actions(etat('arrete'), mire, false).arreter.visible).toBe(false);
});
it('une commande en vol ne s’envoie pas deux fois', () => {
const a = actions(etat('arrete'), mire, true);
expect(a.demarrer.actif).toBe(false);
expect(a.choisir).toBe(false);
});
it('pendant le démarrage: ni démarrer ni changer de source, annuler possible', () => {
const a = actions(etat('demarrage'), mire, true);
expect(a.demarrer.visible).toBe(false);
expect(a.choisir).toBe(false);
expect(a.annuler).toEqual({ visible: true, actif: true });
});
it('en cours: arrêter seulement', () => {
const a = actions(etat('en_cours'), mire, false);
expect(a.arreter).toEqual({ visible: true, actif: true });
expect(a.demarrer.visible).toBe(false);
expect(a.annuler.visible).toBe(false);
});
});
describe('statut', () => {
it('compte les spectateurs', () => {
const partage = { appareils: [{}, {}] } as unknown as Partage;
expect(statut(etat('en_cours', partage), t).texte).toBe('En direct, 2 spectateurs');
const personne = statut(etat('en_cours', { appareils: [] } as unknown as Partage), t);
expect(personne).toEqual({ texte: 'En direct, personne ne regarde', ton: 'direct' });
expect(statut(etat('demarrage'), t).ton).toBe('attente');
const en = traductionPour('en');
expect(statut(etat('en_cours', partage), en).texte).toBe('Live, 2 viewers');
});
});
describe('sources', () => {
const source = (nom: string, id: string): SourceProposee => ({
choix: { type: 'x11', id },
genre: 'window',
nom,
libelle: { type: 'titre', texte: nom },
largeur: 800,
hauteur: 600,
vignette: null,
note: null,
disponible: true,
});
it('la recherche ignore accents et casse', () => {
const liste = [source('Présentation.odp', 'a'), source('Terminal', 'b')];
expect(filtrer(liste, 'presen', t).map((s) => s.nom)).toEqual(['Présentation.odp']);
expect(filtrer(liste, ' ', t)).toHaveLength(2);
});
it('on cherche le nom affiché, dans la langue de l’interface (#21)', () => {
const mire: SourceProposee = {
...source('Mire de test', 'm'),
choix: { type: 'synthetique', largeur: 64, hauteur: 64 },
libelle: { type: 'mire' },
};
expect(filtrer([mire], 'test pattern', traductionPour('en'))).toHaveLength(1);
expect(nomAffiche({ type: 'moniteur', sortie: 'HDMI-1', principal: true }, t)).toBe(
'HDMI-1 (principal)',
);
});
it('la clé distingue écran existant et virtuel', () => {
expect(cle({ type: 'portail', virtuel: false, fenetre: true, taille: null })).not.toBe(
cle({ type: 'portail', virtuel: false, fenetre: false, taille: null }),
);
expect(cle({ type: 'portail', virtuel: true, fenetre: false, taille: null })).not.toBe(
cle({ type: 'portail', virtuel: false, fenetre: false, taille: null }),
);
});
});
describe('textes', () => {
it('les durées restent courtes', () => {
expect(duree(0, 42_000)).toBe('42 s');
expect(duree(0, 5 * 60_000)).toBe('5 min');
expect(duree(0, 65 * 60_000)).toBe('1 h 05');
expect(duree(10_000, 0)).toBe('0 s');
});
it('un réglage en attente est dit', () => {
expect(resumeApplication({ immediats: ['limite'], au_prochain_partage: [] }, t)).toContain(
'appliqués',
);
expect(
resumeApplication({ immediats: [], au_prochain_partage: ['port: couperait'] }, t),
).toContain('prochain partage');
});
});
describe('code court (#19)', () => {
it('s’affiche en deux groupes de trois', () => {
expect(codeAffiche('k7m4pq')).toBe('K7M 4PQ');
});
it('dit ce qu’il reste, en secondes sur la dernière minute', () => {
expect(echeance(null, 0, t)).toBeNull();
expect(echeance(10 * 60_000, 0, t)).toContain('10 min');
expect(echeance(30_000, 0, t)).toContain('30 s');
expect(echeance(0, 1, t)).toBe(t('codeExpire'));
});
});
describe('langue (#21)', () => {
it('le français et l’anglais sont embarqués', () => {
const codes = LANGUES.map((l) => l.code);
expect(codes).toContain('fr');
expect(codes).toContain('en');
});
it('le réglage prime, sinon la langue du bureau, sinon l’anglais', () => {
expect(langueEffective('fr', ['en-US'])).toBe('fr');
expect(langueEffective(null, ['fr-FR'])).toBe('fr');
expect(langueEffective(null, ['de-DE'])).toBe('en');
expect(langueEffective('xx', ['fr-BE'])).toBe('fr');
});
it('la barre système reçoit les trois formes, {count} à remplacer', () => {
const barre = textesBarre(t);
expect(barre.direct.zero).toBe('En direct, personne ne regarde');
expect(barre.direct.one).toBe('En direct, 1 spectateur');
expect(barre.direct.other).toBe('En direct, {count} spectateurs');
});
});
+209
View File
@@ -0,0 +1,209 @@
import type { Application } from '../bindings/Application';
import type { Etat } from '../bindings/Etat';
import type { SourceChoisie } from '../bindings/SourceChoisie';
import type { SourceProposee } from '../bindings/SourceProposee';
import type { Libelle } from '../bindings/Libelle';
import type { Traduire } from '../../../viewer/src/lib/i18n';
/**
* Ce que montrent les boutons, déduit de l'état de l'hôte et de rien d'autre.
*
* C'est le critère de #15, « pas de bouton qui ment »: un bouton n'a pas
* d'état à lui. `envoi` dit seulement qu'une commande est partie et que sa
* réponse n'est pas revenue, pour ne pas l'envoyer deux fois.
*/
export type Actions = {
/** La liste des sources est cliquable. */
choisir: boolean;
demarrer: { visible: boolean; actif: boolean };
annuler: { visible: boolean; actif: boolean };
arreter: { visible: boolean; actif: boolean };
};
export function actions(etat: Etat, selection: SourceChoisie | null, envoi: boolean): Actions {
switch (etat.phase) {
case 'arrete':
return {
choisir: !envoi,
demarrer: { visible: true, actif: selection !== null && !envoi },
annuler: { visible: false, actif: false },
arreter: { visible: false, actif: false },
};
case 'demarrage':
return {
choisir: false,
demarrer: { visible: false, actif: false },
annuler: { visible: true, actif: true },
arreter: { visible: false, actif: false },
};
case 'en_cours':
return {
choisir: false,
demarrer: { visible: false, actif: false },
annuler: { visible: false, actif: false },
arreter: { visible: true, actif: !envoi },
};
}
}
export type Statut = { texte: string; ton: 'repos' | 'attente' | 'direct' };
export function statut(etat: Etat, t: Traduire): Statut {
switch (etat.phase) {
case 'arrete':
return { texte: t('statutArrete'), ton: 'repos' };
case 'demarrage':
return { texte: t('statutDemarrage'), ton: 'attente' };
case 'en_cours': {
const n = etat.partage?.appareils.length ?? 0;
return { texte: t('statutEnCours', { count: n }), ton: 'direct' };
}
}
}
/** Identité stable d'un choix, pour la sélection et les clés React. */
export function cle(choix: SourceChoisie): string {
switch (choix.type) {
case 'x11':
return `x11:${choix.id}`;
case 'portail':
if (choix.virtuel) return 'portail:virtuel';
return choix.fenetre ? 'portail:fenetre' : 'portail:ecran';
case 'synthetique':
return 'synthetique';
case 'mire':
return `mire:${choix.chemin}`;
}
}
function normaliser(texte: string): string {
return texte
.normalize('NFD')
.replace(/\p{Diacritic}/gu, '')
.toLowerCase();
}
/**
* Recherche par nom affiché, sans tenir compte des accents ni de la casse:
* on cherche ce qu'on lit, dans la langue de l'interface.
*/
export function filtrer(
sources: SourceProposee[],
recherche: string,
t: Traduire,
): SourceProposee[] {
const cherche = normaliser(recherche.trim());
if (cherche === '') {
return sources;
}
return sources.filter((s) => normaliser(nomAffiche(s.libelle, t)).includes(cherche));
}
/** Le nom d'une source dans la langue de l'interface (#21). */
export function nomAffiche(libelle: Libelle, t: Traduire): string {
switch (libelle.type) {
case 'titre':
return libelle.texte;
case 'moniteur':
return libelle.principal
? t('sources.principal', { sortie: libelle.sortie })
: libelle.sortie;
case 'ecran':
return t('sources.ecran');
case 'fenetre':
return t('sources.fenetre');
case 'ecran_virtuel':
return t('sources.ecranVirtuel');
case 'mire':
return t('sources.mire');
case 'mire_enregistree':
return t('sources.mireEnregistree');
case 'tous_les_ecrans':
return t('sources.tousLesEcrans');
case 'ecran_entier':
return t('sources.ecranX11');
case 'ecran_choisi':
return t('sources.ecranChoisi');
case 'fenetre_choisie':
return t('sources.fenetreChoisie');
}
}
/** Durée lisible depuis une date Unix en millisecondes. */
export function duree(depuisMs: number, maintenantMs: number): string {
const secondes = Math.max(0, Math.floor((maintenantMs - depuisMs) / 1000));
if (secondes < 60) {
return `${secondes} s`;
}
const minutes = Math.floor(secondes / 60);
if (minutes < 60) {
return `${minutes} min`;
}
const heures = Math.floor(minutes / 60);
return `${heures} h ${String(minutes % 60).padStart(2, '0')}`;
}
/** Ce qu'on dit après un enregistrement de réglages. */
export function resumeApplication(application: Application, t: Traduire): string {
if (application.au_prochain_partage.length > 0) {
return t('reglagesEnAttente', { champs: application.au_prochain_partage.join('; ') });
}
if (application.immediats.length > 0) {
return t('reglagesAppliques');
}
return t('reglagesInchanges');
}
/** Le code court tel qu'on le lit et le dicte: `K7M 4PQ`. */
export function codeAffiche(code: string): string {
const haut = code.toUpperCase();
return haut.length === 6 ? `${haut.slice(0, 3)} ${haut.slice(3)}` : haut;
}
/**
* Ce qu'il reste au code d'accès, en clair, ou `null` s'il n'expire pas.
* Au-dessous d'une minute, on compte en secondes: c'est le moment où l'hôte
* doit savoir qu'un nouveau venu va être refusé.
*/
export function echeance(expireMs: number | null, maintenant: number, t: Traduire): string | null {
if (expireMs === null) return null;
const restant = expireMs - maintenant;
if (restant <= 0) return t('codeExpire');
if (restant < 60_000) return t('codeExpireDans', { duree: `${Math.ceil(restant / 1000)} s` });
return t('codeExpireDans', { duree: `${Math.ceil(restant / 60_000)} min` });
}
/** Ce que le menu de la barre système affiche, traduit (#21, #22). */
export type TextesBarre = {
aucun: string;
demarrage: string;
/** Formes du statut en direct, par nombre exact puis catégorie. */
direct: { zero: string; one: string; other: string };
ouvrir: string;
demarrer: string;
reprendre: string;
arreter: string;
quitter: string;
};
/**
* Les textes de la barre système. Rust ne connaît pas les règles de pluriel
* de chaque langue: on lui donne les formes de 0, 1 et du reste, avec
* `{count}` à remplacer.
*/
export function textesBarre(t: Traduire): TextesBarre {
return {
aucun: t('barre.aucun'),
demarrage: t('barre.demarrage'),
direct: {
zero: t('barre.direct', { count: 0 }),
one: t('barre.direct', { count: 1 }),
other: t('barre.direct', { count: '{count}' }),
},
ouvrir: t('barre.ouvrir'),
demarrer: t('barre.demarrer'),
reprendre: t('barre.reprendre'),
arreter: t('barre.arreter'),
quitter: t('barre.quitter'),
};
}
+3 -3
View File
@@ -1,14 +1,14 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { App } from './App';
import { tauriHost } from './lib/host';
import { hoteTauri } from './lib/hote';
import './styles.css';
const root = document.getElementById('root');
if (!root) throw new Error('root element missing');
if (!root) throw new Error('élément racine absent');
createRoot(root).render(
<StrictMode>
<App host={tauriHost} />
<App hote={hoteTauri} />
</StrictMode>,
);
+155 -225
View File
@@ -1,60 +1,60 @@
/* Desktop shell. System fonts, no remote resource. Sizes in rem: the
interface follows the desktop scale factor (HiDPI) without images to double. */
/* Coque desktop. Polices du système, aucune ressource distante. Tailles en rem:
l'interface suit le facteur d'échelle du bureau (HiDPI) sans image à doubler. */
:root {
--bg: #f5f6f8;
--fond: #f5f6f8;
--surface: #ffffff;
--border: #d9dee5;
--text: #18202a;
--muted: #5d6b7c;
--bord: #d9dee5;
--texte: #18202a;
--discret: #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;
--accent-texte: #ffffff;
/* Assez sombres pour un texte sur fond clair: contraste AA (4,5:1) vérifié
pour chaque paire texte et fond (#28). */
--direct: #15803d;
--attente: #b45309;
--danger: #b91c1c;
--warning-bg: #fff7e6;
--error-bg: #fdecec;
--info-bg: #eaf1ff;
--radius: 10px;
--alerte-fond: #fff7e6;
--erreur-fond: #fdecec;
--info-fond: #eaf1ff;
--rayon: 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;
:root[data-theme="sombre"] {
--fond: #0d1116;
--surface: #151b23;
--border: #2a3441;
--text: #e9eef5;
--muted: #97a5b6;
--bord: #2a3441;
--texte: #e9eef5;
--discret: #97a5b6;
--accent: #4c9aff;
--accent-text: #0d1116;
--live: #3ddc84;
--waiting: #f5a524;
--accent-texte: #0d1116;
--direct: #3ddc84;
--attente: #f5a524;
--danger: #ff6b6b;
--warning-bg: #2b2210;
--error-bg: #2e1517;
--info-bg: #13213a;
--alerte-fond: #2b2210;
--erreur-fond: #2e1517;
--info-fond: #13213a;
color-scheme: dark;
}
@media (prefers-color-scheme: dark) {
:root[data-theme="system"] {
--bg: #0d1116;
:root[data-theme="systeme"] {
--fond: #0d1116;
--surface: #151b23;
--border: #2a3441;
--text: #e9eef5;
--muted: #97a5b6;
--bord: #2a3441;
--texte: #e9eef5;
--discret: #97a5b6;
--accent: #4c9aff;
--accent-text: #0d1116;
--live: #3ddc84;
--waiting: #f5a524;
--accent-texte: #0d1116;
--direct: #3ddc84;
--attente: #f5a524;
--danger: #ff6b6b;
--warning-bg: #2b2210;
--error-bg: #2e1517;
--info-bg: #13213a;
--alerte-fond: #2b2210;
--erreur-fond: #2e1517;
--info-fond: #13213a;
color-scheme: dark;
}
}
@@ -71,8 +71,8 @@ body,
}
body {
background: var(--bg);
color: var(--text);
background: var(--fond);
color: var(--texte);
-webkit-font-smoothing: antialiased;
}
@@ -90,11 +90,11 @@ h2 {
font-size: 1rem;
}
.loading {
.chargement {
display: grid;
height: 100%;
place-items: center;
color: var(--muted);
color: var(--discret);
}
.app {
@@ -103,8 +103,8 @@ h2 {
flex-direction: column;
}
.header,
.action-bar {
.entete,
.barre {
display: flex;
align-items: center;
gap: 0.75rem;
@@ -112,37 +112,37 @@ h2 {
background: var(--surface);
}
.header {
border-bottom: 1px solid var(--border);
.entete {
border-bottom: 1px solid var(--bord);
}
.action-bar {
border-top: 1px solid var(--border);
.barre {
border-top: 1px solid var(--bord);
min-height: 3.75rem;
}
.spacer {
.espace {
flex: 1;
}
.content {
.contenu {
flex: 1;
overflow: auto;
padding: 1.25rem;
}
.badge {
.pastille {
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);
border: 1px solid var(--bord);
color: var(--discret);
font-size: 0.85rem;
}
.badge::before {
.pastille::before {
content: "";
width: 0.5rem;
height: 0.5rem;
@@ -150,108 +150,108 @@ h2 {
background: currentColor;
}
.badge.live {
color: var(--live);
.pastille.direct {
color: var(--direct);
border-color: currentColor;
}
.badge.waiting {
color: var(--waiting);
.pastille.attente {
color: var(--attente);
border-color: currentColor;
}
.sleep {
color: var(--muted);
.veille {
color: var(--discret);
font-size: 0.85rem;
}
.button {
.bouton {
padding: 0.5rem 1rem;
border: 1px solid var(--border);
border: 1px solid var(--bord);
border-radius: 8px;
background: var(--surface);
color: var(--text);
color: var(--texte);
font: inherit;
cursor: pointer;
}
.button:hover:not(:disabled) {
.bouton:hover:not(:disabled) {
border-color: var(--accent);
}
.button:disabled {
.bouton:disabled {
opacity: 0.5;
cursor: default;
}
.button.primary {
.bouton.principal {
background: var(--accent);
border-color: var(--accent);
color: var(--accent-text);
color: var(--accent-texte);
font-weight: 600;
}
.button.danger {
.bouton.danger {
color: var(--danger);
border-color: var(--danger);
}
.button.muted {
.bouton.discret {
padding: 0.35rem 0.75rem;
}
.help,
.muted {
color: var(--muted);
.aide,
.discret {
color: var(--discret);
font-size: 0.85rem;
}
.banner {
.bandeau {
margin-bottom: 1rem;
padding: 0.65rem 0.9rem;
border-radius: var(--radius);
border: 1px solid var(--border);
border-radius: var(--rayon);
border: 1px solid var(--bord);
}
.banner.error {
background: var(--error-bg);
.bandeau.erreur {
background: var(--erreur-fond);
border-color: var(--danger);
}
.banner.warning {
background: var(--warning-bg);
border-color: var(--waiting);
.bandeau.alerte {
background: var(--alerte-fond);
border-color: var(--attente);
}
.banner.info {
background: var(--info-bg);
.bandeau.info {
background: var(--info-fond);
border-color: var(--accent);
}
.picker-header {
.choix-entete {
display: flex;
align-items: center;
gap: 0.75rem;
margin-bottom: 1rem;
}
.picker-header h2 {
.choix-entete h2 {
flex: 1;
}
.search,
.form input:not([type="checkbox"]),
.form select,
.link input {
.recherche,
.formulaire input:not([type="checkbox"]),
.formulaire select,
.lien input {
padding: 0.45rem 0.6rem;
border: 1px solid var(--border);
border: 1px solid var(--bord);
border-radius: 8px;
background: var(--bg);
color: var(--text);
background: var(--fond);
color: var(--texte);
font: inherit;
}
.search {
.recherche {
width: 16rem;
}
@@ -271,10 +271,10 @@ h2 {
flex-direction: column;
gap: 0.3rem;
padding: 0.6rem;
border: 2px solid var(--border);
border-radius: var(--radius);
border: 2px solid var(--bord);
border-radius: var(--rayon);
background: var(--surface);
color: var(--text);
color: var(--texte);
font: inherit;
text-align: left;
cursor: pointer;
@@ -284,7 +284,7 @@ h2 {
border-color: var(--accent);
}
.source.selected {
.source.selectionnee {
border-color: var(--accent);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 25%, transparent);
}
@@ -293,55 +293,55 @@ h2 {
cursor: default;
}
.source.unavailable {
.source.indisponible {
border-style: dashed;
}
.thumbnail {
.vignette {
display: grid;
aspect-ratio: 16 / 9;
place-items: center;
overflow: hidden;
border-radius: 6px;
background: var(--bg);
background: var(--fond);
}
/* The text keeps its contrast: only the picture fades. The note says why the
source cannot be shared (#17). */
.source:disabled .thumbnail {
/* Le texte garde son contraste: seule l'image s'efface. La note dit pourquoi
la source n'est pas partageable (#17). */
.source:disabled .vignette {
opacity: 0.45;
}
.thumbnail img {
.vignette img {
width: 100%;
height: 100%;
object-fit: contain;
}
.thumbnail-empty {
color: var(--muted);
.vignette-vide {
color: var(--discret);
font-size: 2.5rem;
}
.source-name {
.source-nom {
overflow: hidden;
font-weight: 600;
text-overflow: ellipsis;
white-space: nowrap;
}
.source-size,
.source-taille,
.source-note {
color: var(--muted);
color: var(--discret);
font-size: 0.8rem;
}
.waiting {
.attente {
margin: 0;
color: var(--waiting);
color: var(--attente);
}
.share {
.partage {
display: grid;
grid-template-columns: minmax(18rem, 22rem) 1fr;
gap: 1.25rem;
@@ -349,19 +349,19 @@ h2 {
}
@media (max-width: 860px) {
.share {
.partage {
grid-template-columns: 1fr;
}
}
.card {
.carte {
padding: 1.1rem;
border: 1px solid var(--border);
border-radius: var(--radius);
border: 1px solid var(--bord);
border-radius: var(--rayon);
background: var(--surface);
}
.qr-card {
.qr-carte {
display: flex;
flex-direction: column;
gap: 0.9rem;
@@ -379,124 +379,87 @@ h2 {
height: auto;
}
.link {
.lien {
display: flex;
flex-direction: column;
gap: 0.35rem;
font-size: 0.85rem;
color: var(--muted);
color: var(--discret);
}
.link-row {
.lien-ligne {
display: flex;
gap: 0.5rem;
}
.link input {
.lien input {
flex: 1;
min-width: 0;
font-family: ui-monospace, monospace;
font-size: 0.8rem;
}
.fingerprint code {
.empreinte code {
word-break: break-all;
}
.facts {
.faits {
display: grid;
grid-template-columns: auto 1fr;
gap: 0.4rem 1rem;
margin: 0 0 1.25rem;
}
.facts dt {
color: var(--muted);
.faits dt {
color: var(--discret);
}
.facts dd {
.faits dd {
margin: 0;
}
.viewers-title {
.spectateurs-titre {
display: flex;
align-items: baseline;
gap: 0.6rem;
margin-bottom: 0.6rem;
}
.counter {
color: var(--muted);
.compteur {
color: var(--discret);
font-size: 0.85rem;
font-weight: 400;
}
.devices {
.appareils {
margin: 0;
padding: 0;
list-style: none;
}
.devices li {
.appareils 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);
border-top: 1px solid var(--bord);
}
.devices li .muted {
.appareils li .discret {
grid-column: 1;
}
.devices li .button {
.appareils li .bouton {
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 {
.appareil-nom {
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 {
.voile {
position: fixed;
inset: 0;
display: grid;
@@ -505,89 +468,61 @@ h2 {
background: rgb(0 0 0 / 45%);
}
.dialog {
.dialogue {
width: min(34rem, 100%);
max-height: 100%;
overflow: auto;
padding: 1.25rem;
border-radius: var(--radius);
border-radius: var(--rayon);
background: var(--surface);
}
.form {
.formulaire {
display: flex;
flex-direction: column;
gap: 0.9rem;
margin-top: 1rem;
}
.field {
.champ {
display: flex;
flex-direction: column;
gap: 0.3rem;
}
.field label {
.champ label {
font-weight: 600;
}
.field.has-error input,
.field.has-error select {
.champ.en-erreur input,
.champ.en-erreur select {
border-color: var(--danger);
}
.checkbox {
.case {
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 {
.erreur-champ {
color: var(--danger);
font-size: 0.85rem;
}
.confirmation {
margin: 0;
color: var(--live);
color: var(--direct);
}
.dialog-actions {
.pied {
display: flex;
align-items: center;
gap: 0.6rem;
}
/* Short code (#19): readable from afar, easy to dictate. */
.short-code {
/* Code court (#19): lisible de loin, dictable. */
.code-court {
display: flex;
flex-wrap: wrap;
gap: 0.35rem 0.75rem;
@@ -595,35 +530,30 @@ h2 {
font-size: 0.85rem;
}
.short-code > .muted:first-child {
.code-court > .discret:first-child {
flex-basis: 100%;
}
.short-code > .local-name {
flex-basis: 100%;
order: 1;
}
.code-value {
.code-valeur {
font:
700 1.6rem / 1.1 ui-monospace,
"SF Mono",
Menlo,
monospace;
letter-spacing: 0.12em;
color: var(--text);
color: var(--texte);
}
.code-expired .code-value {
color: var(--muted);
.code-expire .code-valeur {
color: var(--discret);
text-decoration: line-through;
}
.code-new {
.code-nouveau {
margin-left: auto;
}
.warning-text {
color: var(--waiting);
.alerte-texte {
color: var(--attente);
font-weight: 600;
}
+1 -1
View File
@@ -1,7 +1,7 @@
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';
// Served by Tauri from `dist`: no server, no remote resource.
// Servi par Tauri depuis `dist`: pas de serveur, pas de ressource distante.
export default defineConfig({
plugins: [react()],
clearScreen: false,
+44 -23
View File
@@ -1,15 +1,13 @@
{
"name": "@rustscreen/viewer",
"version": "0.5.0",
"version": "0.4.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@rustscreen/viewer",
"version": "0.5.0",
"version": "0.4.0",
"dependencies": {
"@noble/ed25519": "^3.2.0",
"@noble/hashes": "^2.4.0",
"react": "^19.2.0",
"react-dom": "^19.2.0"
},
@@ -128,6 +126,9 @@
"arm64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
@@ -145,6 +146,9 @@
"arm64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
@@ -162,6 +166,9 @@
"x64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
@@ -179,6 +186,9 @@
"x64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
@@ -250,25 +260,6 @@
"@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",
@@ -389,6 +380,9 @@
"arm64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -406,6 +400,9 @@
"arm64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -423,6 +420,9 @@
"ppc64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -440,6 +440,9 @@
"s390x"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -457,6 +460,9 @@
"x64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -474,6 +480,9 @@
"x64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -1234,6 +1243,9 @@
"arm64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MPL-2.0",
"optional": true,
"os": [
@@ -1255,6 +1267,9 @@
"arm64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MPL-2.0",
"optional": true,
"os": [
@@ -1276,6 +1291,9 @@
"x64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MPL-2.0",
"optional": true,
"os": [
@@ -1297,6 +1315,9 @@
"x64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MPL-2.0",
"optional": true,
"os": [
+3 -5
View File
@@ -1,20 +1,18 @@
{
"name": "@rustscreen/viewer",
"private": true,
"version": "0.5.0",
"version": "0.4.0",
"type": "module",
"description": "rustscreen browser client: receives the WebRTC stream from the host.",
"description": "Client navigateur de rustscreen: reçoit le flux WebRTC de l'hôte.",
"scripts": {
"dev": "vite",
"build": "tsc --noEmit && vite build",
"preview": "vite preview",
"lint": "biome lint src && node ../../scripts/check-i18n.mjs apps/viewer/src viewer",
"lint": "biome lint src && node ../../scripts/verifier-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"
},
+61 -176
View File
@@ -1,36 +1,16 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { ErrorPanel } from './components/ErrorPanel';
import { ChoixLangue } from './components/ChoixLangue';
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 { isTrusted } from './lib/trust';
import { useActivity } from './lib/useActivity';
import type { SourceInfo } from './proto';
const SWITCH_NOTICE_MS = 2500;
import { garderRotation, lireRotation, type Rotation, rotationSuivante } from './lib/rotation';
import { appliquerTheme, garderTheme, lireTheme, type Theme, themeSuivant } from './lib/theme';
import { useI18n } from './i18n';
export function App() {
const { t } = useI18n();
@@ -38,40 +18,27 @@ export function App() {
() => 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 [theme, setTheme] = useState<Theme>(() => lireTheme());
const [rotation, setRotation] = useState<Rotation>(() => lireRotation());
const sessionRef = useRef<ViewerSession | null>(null);
const containerRef = useRef<HTMLDivElement | null>(null);
// 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.
// 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.
useEffect(() => {
if (!location.ok && !byKey) return;
if (!location.ok) return;
const session = new ViewerSession({
room: location.ok ? location.value.room : null,
token: location.ok ? location.value.token : null,
room: location.value.room,
token: location.value.token,
wsUrl: signalingUrl(window.location),
onState: setState,
onStream: setStream,
onSourceChanged: setSwitched,
});
sessionRef.current = session;
session.start();
@@ -79,10 +46,10 @@ export function App() {
session.stop();
sessionRef.current = null;
};
}, [location, byKey, attemptKey]);
}, [location, attemptKey]);
useEffect(() => {
if (state.kind !== 'streaming' || !statsShown) {
if (state.kind !== 'streaming') {
setStats(null);
return;
}
@@ -96,14 +63,7 @@ export function App() {
cancelled = true;
clearInterval(timer);
};
}, [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]);
}, [state.kind]);
useEffect(() => {
const onChange = () => setIsFullscreen(Boolean(document.fullscreenElement));
@@ -121,38 +81,26 @@ 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 changerTheme = useCallback(() => {
setTheme((courant) => {
const suivant = themeSuivant(courant);
appliquerTheme(suivant);
garderTheme(suivant);
return suivant;
});
}, []);
const toggleMirror = useCallback(() => {
setMirror((current) => {
saveMirror(!current);
return !current;
const tourner = useCallback(() => {
setRotation((courante) => {
const suivante = rotationSuivante(courante);
garderRotation(suivante);
return suivante;
});
}, []);
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.
// Relance une série de tentatives sur la session existante, sans recharger
// la page: la qualité demandée et les écouteurs de réveil sont conservés.
// Une session arrêtée pour de bon est remplacée par une neuve.
const retry = useCallback(() => {
setStats(null);
if (sessionRef.current?.retry()) return;
@@ -160,94 +108,61 @@ export function App() {
setAttemptKey((key) => key + 1);
}, []);
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];
if (!location.ok) {
// Sans session dans l'adresse, on propose le code court (#19). La page
// d'accueil nue n'est pas une erreur: c'est l'entrée sans caméra.
const notice = {
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';
// 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).
// 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).
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={classes} ref={containerRef}>
<header className='topbar' {...hold}>
<div className={`app ${isFullscreen ? 'app-fullscreen' : ''}`} ref={containerRef}>
<header className='topbar'>
<span className='brand'>{t('appName')}</span>
<StatusBadge state={state} />
{location.value.fingerprint && (
<span className='badge' title={`${t('fingerprint')}: ${location.value.fingerprint}`}>
{location.value.fingerprint.slice(0, 11)}
</span>
)}
{insecure && (
<span className='badge badge-warn' title={t('insecureHint')}>
{t('insecureBadge')}
</span>
)}
<span className='spacer' />
<button
type='button'
className='button button-ghost button-theme'
onClick={changerTheme}
aria-label={t('themeButton', { current: t(`themes.${theme}`) })}
title={t('themeButton', { current: t(`themes.${theme}`) })}
>
{theme === 'sombre' ? '☾' : theme === 'clair' ? '☀' : '◐'}
</button>
{live && (
<button
type='button'
className='button button-ghost'
onClick={rotate}
onClick={tourner}
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'
@@ -259,16 +174,6 @@ export function App() {
{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'>
@@ -277,34 +182,14 @@ export function App() {
live={live}
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>
{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()}
/>
)}
<footer className='footer'>
<StatsBar stats={stats} />
<ChoixLangue />
</footer>
</div>
);
}
@@ -0,0 +1,27 @@
import { useId } from 'react';
import { useI18n } from '../i18n';
/**
* Choix de la langue (#21), parmi celles que sert l'hôte. Chacune s'affiche
* dans sa propre langue: qui ne lit pas la langue courante retrouve la sienne.
*/
export function ChoixLangue() {
const { t, langue, langues, changerLangue } = useI18n();
const id = useId();
if (langues.length < 2) return null;
return (
<span className='langue'>
<label htmlFor={id} className='visually-hidden'>
{t('language')}
</label>
<select id={id} value={langue} onChange={(e) => changerLangue(e.target.value)}>
{langues.map((l) => (
<option key={l.code} value={l.code} lang={l.code}>
{l.nom}
</option>
))}
</select>
</span>
);
}
-50
View File
@@ -1,50 +0,0 @@
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>
);
}
+3 -3
View File
@@ -7,9 +7,9 @@ type Props = {
};
/**
* 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.
* 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.
*/
export function ErrorPanel({ state, onRetry }: Props) {
const { t } = useI18n();
+14 -27
View File
@@ -1,20 +1,21 @@
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';
import { exchangeCode, qrDetector } from '../lib/pairing';
import { useI18n } from '../i18n';
import { isCompleteCode, normalizeCode, sessionFromScan } from '../lib/room';
import { ChoixLangue } from './ChoixLangue';
/** Un code d'exemple, dans le format affiché par l'hôte: pas une phrase. */
const EXEMPLE_CODE = 'K7M 4PQ';
type Props = {
/** Why we land here without a session, to say before the form. */
/** Pourquoi on arrive ici sans session, à dire avant le formulaire. */
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.
* Page d'accueil sans session (#19): taper le code court affiché par l'hôte,
* ou scanner son QR code quand le navigateur sait le faire.
*/
export function Pairing({ notice }: Props) {
const { t } = useI18n();
@@ -23,7 +24,6 @@ export function Pairing({ notice }: Props) {
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) => {
@@ -60,19 +60,7 @@ export function Pairing({ notice }: Props) {
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>
<h1>{t('appName')}</h1>
{notice && <p role='alert'>{notice}</p>}
<form onSubmit={submit} className='pairing-form'>
<label htmlFor='code'>{t('codeLabel')}</label>
@@ -85,7 +73,7 @@ export function Pairing({ notice }: Props) {
autoCapitalize='characters'
spellCheck={false}
maxLength={8}
placeholder={SAMPLE_CODE}
placeholder={EXEMPLE_CODE}
aria-describedby={error ? 'code-error' : undefined}
aria-invalid={error !== null}
/>
@@ -105,14 +93,13 @@ export function Pairing({ notice }: Props) {
</button>
)}
{scanning && <Scanner onClose={() => setScanning(false)} onError={setError} />}
<ChoixLangue />
</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. */
/** Caméra arrière, lecture du QR code quatre fois par seconde. */
function Scanner({ onClose, onError }: { onClose: () => void; onError: (m: string) => void }) {
const { t } = useI18n();
const videoRef = useRef<HTMLVideoElement | null>(null);
@@ -1,139 +0,0 @@
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>
);
}
+5 -5
View File
@@ -8,12 +8,12 @@ type Props = {
};
/**
* 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.
* 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.
*/
export function StatsBar({ stats }: Props) {
const { t, language } = useI18n();
const { t, langue } = useI18n();
const previous = useRef<{ bytes: number; at: number } | null>(null);
const [kbps, setKbps] = useState<number | null>(null);
@@ -57,7 +57,7 @@ export function StatsBar({ stats }: Props) {
<dd>
{kbps >= 1000
? t('mbps', {
value: (kbps / 1000).toLocaleString(language, { maximumFractionDigits: 1 }),
value: (kbps / 1000).toLocaleString(langue, { maximumFractionDigits: 1 }),
})
: t('kbps', { value: kbps })}
</dd>
+3 -3
View File
@@ -1,9 +1,9 @@
import { useI18n } from '../i18n';
import type { Translate } from '../lib/i18n';
import type { Traduire } from '../lib/i18n';
import type { ViewerState } from '../lib/session';
/** Turns the session state into a short label and a colour. */
export function describe(state: ViewerState, t: Translate): { text: string; tone: string } {
/** Traduit l'état de session en un libellé court et une couleur. */
export function describe(state: ViewerState, t: Traduire): { text: string; tone: string } {
switch (state.kind) {
case 'connecting':
return { text: t('connecting'), tone: 'pending' };
+29 -43
View File
@@ -1,25 +1,23 @@
import { useEffect, useRef, useState } from 'react';
import { probeRequested, startProbe } from '../lib/perfProbe';
import { type Rotation, rotatedBox } from '../lib/rotation';
import { boiteTournee, type Rotation } from '../lib/rotation';
type Props = {
stream: MediaStream | null;
live: boolean;
label: string;
rotation: Rotation;
mirror: boolean;
};
/**
* 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).
* 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. Une
* rotation change sa boîte et sa transformation, jamais le flux (#30).
*/
export function VideoStage({ stream, live, label, rotation, mirror }: Props) {
export function VideoStage({ stream, live, label, rotation }: Props) {
const videoRef = useRef<HTMLVideoElement | null>(null);
const stageRef = useRef<HTMLDivElement | null>(null);
const [size, setSize] = useState<{ width: number; height: number } | null>(null);
const [taille, setTaille] = useState<{ largeur: number; hauteur: number } | null>(null);
useEffect(() => {
const video = videoRef.current;
@@ -28,52 +26,40 @@ export function VideoStage({ stream, live, label, rotation, mirror }: Props) {
video.srcObject = stream;
}
if (stream) {
// `play()` may be refused if the user has not interacted; the video
// is muted, so in practice it goes through. The failure is ignored.
// `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.
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.
// La boîte tournée dépend de la taille de la scène: plein écran, passage
// en portrait, clavier virtuel la changent.
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 });
const observateur = new ResizeObserver(([entree]) => {
if (!entree) return;
const { width, height } = entree.contentRect;
setTaille({ largeur: width, hauteur: height });
});
observer.observe(stage);
return () => observer.disconnect();
observateur.observe(stage);
return () => observateur.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;
rotation !== 0 && taille
? (() => {
const boite = boiteTournee(taille.largeur, taille.hauteur, rotation);
return {
inset: 'auto',
left: '50%',
top: '50%',
width: `${boite.width}px`,
height: `${boite.height}px`,
transform: boite.transform,
};
})()
: undefined;
return (
<div className='stage' ref={stageRef}>
+65 -95
View File
@@ -1,150 +1,120 @@
import { createContext, type ReactNode, useCallback, useContext, useMemo, useState } from 'react';
import {
type AvailableLanguage,
type Catalog,
createTranslator,
FALLBACK_LANGUAGE,
pickLanguage,
type Translate,
type Catalogue,
choisirLangue,
LANGUE_DE_REPLI,
type LangueDisponible,
type Traduire,
traduction,
} 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.
* Textes du viewer (#21). Le catalogue vient de l'hôte (`/locales/`): ajouter
* une langue à l'hôte la rend disponible ici, sans recompiler le viewer. Le
* choix de l'appareil est gardé par lui seul, comme le thème.
*/
const KEY = 'rustscreen.language';
/** Key before #83. */
const LEGACY_KEY = 'rustscreen.langue';
const CLE = '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;
type Contexte = {
t: Traduire;
langue: string;
langues: LangueDisponible[];
changerLangue: (code: string) => void;
};
const I18n = createContext<Context | null>(null);
const I18n = createContext<Contexte | null>(null);
export function useI18n(): Context {
const context = useContext(I18n);
if (!context) throw new Error('useI18n outside of I18nProvider');
return context;
export function useI18n(): Contexte {
const contexte = useContext(I18n);
if (!contexte) throw new Error('useI18n hors de I18nProvider');
return contexte;
}
type Loaded = { language: string; catalogs: Catalog[] };
type Charge = { langue: string; catalogues: Catalogue[] };
export function I18nProvider({
initial,
languages,
langues,
children,
}: {
initial: Loaded;
languages: AvailableLanguage[];
initial: Charge;
langues: LangueDisponible[];
children: ReactNode;
}) {
const [loaded, setLoaded] = useState(initial);
const [chosen, setChosen] = useState(() => chosenLanguage(languages));
const [charge, setCharge] = useState(initial);
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 changerLangue = useCallback((code: string) => {
garderLangue(code);
// Le changement prend effet au rendu suivant: pas de rechargement, la
// session et le flux continuent.
void chargerCatalogues(code).then((catalogues) => {
if (catalogues.length === 0) return;
document.documentElement.lang = code;
setCharge({ langue: code, catalogues });
});
}, []);
const value = useMemo(
const valeur = useMemo(
() => ({
t: createTranslator(loaded.language, 'viewer', loaded.catalogs),
language: loaded.language,
languages,
chosen,
setLanguage,
t: traduction(charge.langue, 'viewer', charge.catalogues),
langue: charge.langue,
langues,
changerLangue,
}),
[loaded, languages, chosen, setLanguage],
[charge, langues, changerLangue],
);
return <I18n.Provider value={value}>{children}</I18n.Provider>;
return <I18n.Provider value={valeur}>{children}</I18n.Provider>;
}
/** The languages the host serves, empty if it does not answer. */
export async function loadLanguages(): Promise<AvailableLanguage[]> {
/** Les langues que sert l'hôte, vide s'il ne répond pas. */
export async function chargerLangues(): Promise<LangueDisponible[]> {
try {
const response = await fetch('/locales/index.json');
if (!response.ok) return [];
return (await response.json()) as AvailableLanguage[];
const reponse = await fetch('/locales/index.json');
if (!reponse.ok) return [];
return (await reponse.json()) as LangueDisponible[];
} 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(
/** La langue voulue puis l'anglais, ce qui existe des deux. */
export async function chargerCatalogues(code: string): Promise<Catalogue[]> {
const codes = code === LANGUE_DE_REPLI ? [code] : [code, LANGUE_DE_REPLI];
const catalogues = 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;
const reponse = await fetch(`/locales/${encodeURIComponent(c)}.json`);
return reponse.ok ? ((await reponse.json()) as Catalogue) : null;
} catch {
return null;
}
}),
);
return catalogs.filter((c): c is Catalog => c !== null);
return catalogues.filter((c): c is Catalogue => c !== null);
}
/** The choice kept by the device, otherwise the browser language. */
export function initialLanguage(available: AvailableLanguage[]): string {
return chosenLanguage(available) ?? browserLanguage(available);
/** Le choix gardé par l'appareil, sinon la langue du navigateur. */
export function langueDeDepart(disponibles: LangueDisponible[]): string {
const codes = disponibles.map((l) => l.code);
const gardee = lireLangue();
if (gardee && codes.includes(gardee)) return gardee;
return choisirLangue(navigator.languages ?? [navigator.language], codes);
}
/** 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 {
function lireLangue(): string | null {
try {
const storage = browserStorage();
return storage ? readMigrated(storage, KEY, LEGACY_KEY) : null;
return window.localStorage.getItem(CLE);
} catch {
return null;
}
}
function saveLanguage(code: string | null): void {
function garderLangue(code: string): void {
try {
if (code === null) {
window.localStorage.removeItem(KEY);
window.localStorage.removeItem(LEGACY_KEY);
} else {
window.localStorage.setItem(KEY, code);
}
window.localStorage.setItem(CLE, code);
} catch {
// Private browsing: the choice holds for the page only.
// Navigation privée: le choix vaut pour la page.
}
}
-159
View File
@@ -1,159 +0,0 @@
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();
});
});
-67
View File
@@ -1,67 +0,0 @@
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);
});
});
-77
View File
@@ -1,77 +0,0 @@
/**
* 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.
}
}
+19 -57
View File
@@ -1,78 +1,40 @@
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));
function memoire(): Pick<Storage, 'getItem' | 'setItem'> {
const valeurs = new Map<string, string>();
return {
values,
getItem: (k) => values.get(k) ?? null,
getItem: (k) => valeurs.get(k) ?? null,
setItem: (k, v) => {
values.set(k, v);
},
removeItem: (k) => {
values.delete(k);
valeurs.set(k, v);
},
};
}
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)', () => {
describe('identifiant d’appareil', () => {
it('se passe de randomUUID, absent hors contexte sécurisé (HTTP sur le LAN)', () => {
vi.stubGlobal('crypto', { getRandomValues: globalThis.crypto.getRandomValues.bind(crypto) });
try {
expect(deviceId(memory())).toMatch(/^[0-9a-f]{32}$/);
expect(deviceId(memoire())).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('reste le même d’une connexion à l’autre', () => {
const stockage = memoire();
expect(deviceId(stockage)).toBe(deviceId(stockage));
});
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');
it('survit à un stockage refusé', () => {
const refuse = {
getItem: () => {
throw new Error('refusé');
},
setItem: () => {
throw new Error('refusé');
},
};
expect(deviceId(storage)).toBe(legacy);
expect(storage.values.get('rustscreen.appareil')).toBe(legacy);
expect(deviceId(refuse)).toBe(deviceId(refuse));
});
});
+36 -31
View File
@@ -1,48 +1,53 @@
/**
* Id of this device, stable from one visit to the next.
* Identifiant de cet appareil, stable d'une visite à l'autre.
*
* Two constraints:
* Deux contraintes:
*
* - 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.
* - le viewer est servi en HTTP sur l'adresse du LAN, qui n'est pas un
* contexte sécurisé: `crypto.randomUUID()` n'y existe pas, alors que
* `crypto.getRandomValues()` si. Un `randomUUID` faisait échouer le `hello`
* sur tout autre appareil que l'hôte lui-même;
* - l'hôte reconnaît un appareil qu'il a déconnecté par cet identifiant: tiré
* à chaque connexion, il suffirait de recharger la page pour revenir.
*
* Local storage may be denied (private browsing): the id then lasts for the
* page only.
* Le stockage local peut être refusé (navigation privée): on garde alors un
* identifiant pour la durée de la page.
*/
import { browserStorage, type KeyValueStore, readMigrated } from './storage';
const CLE = 'rustscreen.appareil';
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 memoire: string | null = null;
let pageId: string | null = null;
export function deviceId(storage: KeyValueStore | null = browserStorage()): string {
export function deviceId(
storage: Pick<Storage, 'getItem' | 'setItem'> | null = stockage(),
): string {
try {
const known = storage ? readMigrated(storage, KEY, LEGACY_KEY) : null;
if (known && ID_PATTERN.test(known)) {
return known;
const connu = storage?.getItem(CLE);
if (connu && /^[0-9a-f]{32}$/.test(connu)) {
return connu;
}
} catch {
// Storage denied: page id below.
// Stockage refusé: identifiant de page ci-dessous.
}
const fresh = pageId ?? randomId();
pageId = fresh;
const neuf = memoire ?? aleatoire();
memoire = neuf;
try {
storage?.setItem(KEY, fresh);
storage?.setItem(CLE, neuf);
} catch {
// Same.
// Idem.
}
return fresh;
return neuf;
}
function randomId(): string {
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
function aleatoire(): string {
const octets = new Uint8Array(16);
crypto.getRandomValues(octets);
return Array.from(octets, (o) => o.toString(16).padStart(2, '0')).join('');
}
function stockage(): Storage | null {
try {
return window.localStorage;
} catch {
return null;
}
}
-41
View File
@@ -1,41 +0,0 @@
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();
});
});
-78
View File
@@ -1,78 +0,0 @@
/**
* 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.
}
}
+32 -32
View File
@@ -1,55 +1,55 @@
import { describe, expect, it } from 'vitest';
import { type Catalog, createTranslator, pickLanguage } from './i18n';
import { type Catalogue, choisirLangue, traduction } from './i18n';
const fr: Catalog = {
const fr: Catalogue = {
viewer: {
greeting: 'Bonjour {name}',
viewers: { '0': 'personne', one: '{count} spectateur', other: '{count} spectateurs' },
bonjour: 'Bonjour {nom}',
spectateurs: { '0': 'personne', one: '{count} spectateur', other: '{count} spectateurs' },
},
};
const en: Catalog = {
const en: Catalogue = {
viewer: {
greeting: 'Hello {name}',
onlyInEnglish: 'Only in English',
viewers: { '0': 'nobody', one: '{count} viewer', other: '{count} viewers' },
bonjour: 'Hello {nom}',
seulementEn: 'Only in English',
spectateurs: { '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');
describe('traduction (#21)', () => {
it('interpole les paramètres', () => {
const t = traduction('fr', 'viewer', [fr, en]);
expect(t('bonjour', { nom: '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('choisit la forme plurielle de la langue', () => {
const t = traduction('fr', 'viewer', [fr, en]);
expect(t('spectateurs', { count: 0 })).toBe('personne');
expect(t('spectateurs', { count: 1 })).toBe('1 spectateur');
expect(t('spectateurs', { 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('retombe sur l’anglais pour une clé manquante, jamais sur la clé brute', () => {
const t = traduction('fr', 'viewer', [fr, en]);
expect(t('seulementEn')).toBe('Only in English');
expect(t('nulle.part')).toBe('');
});
it('a language unknown to Intl breaks nothing', () => {
const t = createTranslator('xx-invalid-%', 'viewer', [en]);
expect(t('viewers', { count: 2 })).toBe('2 viewers');
it('une langue inconnue de Intl ne casse rien', () => {
const t = traduction('xx-invalide-%', 'viewer', [en]);
expect(t('spectateurs', { 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');
describe('choisirLangue', () => {
it('suit la langue de l’appareil, exactement ou par sa langue principale', () => {
expect(choisirLangue(['fr-FR', 'en'], ['en', 'fr'])).toBe('fr');
expect(choisirLangue(['fr-CA'], ['en', 'fr'])).toBe('fr');
expect(choisirLangue(['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');
it('retombe sur l’anglais pour une langue absente', () => {
expect(choisirLangue(['de-DE', 'it'], ['en', 'fr'])).toBe('en');
expect(choisirLangue([], ['en', 'fr'])).toBe('en');
});
});
+70 -77
View File
@@ -1,112 +1,105 @@
/**
* Translation (#21), without dependencies: key lookup, plurals,
* interpolation, English fallback, language choice.
* Traduction (#21), sans dépendance: recherche d'une clé, pluriel,
* interpolation, retour à l'anglais, choix de la langue.
*
* 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.
* Les textes vivent dans `locales/<langue>.json`, à la racine du dépôt, un
* fichier par langue, une section par application (`viewer`, `desktop`).
* Ajouter une langue, c'est ajouter un fichier: aucun code ne change. L'hôte
* les embarque et les sert au viewer (`/locales/`), la coque les embarque à la
* compilation.
*
* This module is pure: the desktop shell imports it as is, without React.
* Ce module est pur: la coque l'importe tel quel, sans React.
*/
export type Catalog = { [key: string]: string | Catalog };
export type Params = Record<string, string | number>;
export type Translate = (key: string, params?: Params) => string;
export type Catalogue = { [cle: string]: string | Catalogue };
export type Parametres = Record<string, string | number>;
export type Traduire = (cle: string, parametres?: Parametres) => string;
/** Une langue proposée, par son code et son nom dans cette langue. */
export type LangueDisponible = { code: string; nom: string };
/** La langue de repli: complète par contrat, vérifiée par `verifier-i18n`. */
export const LANGUE_DE_REPLI = 'en';
/**
* 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.
* Une fonction de traduction pour `section` (`viewer`, `desktop`), qui
* cherche dans `catalogues` dans l'ordre: la langue choisie, puis l'anglais.
* Une clé introuvable partout rend une chaîne vide, jamais la clé brute.
*/
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);
export function traduction(langue: string, section: string, catalogues: Catalogue[]): Traduire {
const regles = pluriels(langue);
return (cle, parametres) => {
for (const catalogue of catalogues) {
const valeur = chercher(catalogue, `${section}.${cle}`);
if (valeur === undefined) continue;
const texte = typeof valeur === 'string' ? valeur : pluriel(valeur, regles, parametres);
if (texte !== undefined) return interpoler(texte, parametres);
}
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];
function chercher(catalogue: Catalogue, chemin: string): string | Catalogue | undefined {
let noeud: string | Catalogue | undefined = catalogue;
for (const morceau of chemin.split('.')) {
if (noeud === undefined || typeof noeud === 'string') return undefined;
noeud = noeud[morceau];
}
return node;
return noeud;
}
/**
* A plural is an object of forms: an exact value (`"0"`), then the
* `Intl.PluralRules` category (`one`, `few`, `other`...).
* Un pluriel est un objet de formes: une valeur exacte (`"0"`), puis la
* catégorie de `Intl.PluralRules` (`one`, `few`, `other`...).
*/
function plural(
forms: Catalog,
rules: Intl.PluralRules,
params: Params | undefined,
function pluriel(
formes: Catalogue,
regles: Intl.PluralRules,
parametres: Parametres | undefined,
): string | undefined {
const count = params?.count;
if (typeof count !== 'number') {
return typeof forms.other === 'string' ? forms.other : undefined;
const nombre = parametres?.count;
if (typeof nombre !== 'number') {
return typeof formes.other === 'string' ? formes.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;
const exacte = formes[String(nombre)];
if (typeof exacte === 'string') return exacte;
const categorie = formes[regles.select(nombre)];
if (typeof categorie === 'string') return categorie;
return typeof formes.other === 'string' ? formes.other : undefined;
}
function pluralRules(language: string): Intl.PluralRules {
function pluriels(langue: string): Intl.PluralRules {
try {
return new Intl.PluralRules(language);
return new Intl.PluralRules(langue);
} catch {
return new Intl.PluralRules(FALLBACK_LANGUAGE);
return new Intl.PluralRules(LANGUE_DE_REPLI);
}
}
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,
function interpoler(texte: string, parametres: Parametres | undefined): string {
if (!parametres) return texte;
return texte.replace(/\{(\w+)\}/g, (entier, nom: string) =>
nom in parametres ? String(parametres[nom]) : entier,
);
}
/**
* 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.
* La langue à afficher: la première des préférences de l'appareil qui existe,
* exactement (`pt-BR`) ou par sa langue principale (`fr-CA` donne `fr`),
* sinon l'anglais.
*/
export function pickLanguage(preferences: readonly string[], available: readonly string[]): string {
const codes = available.map((code) => code.toLowerCase());
export function choisirLangue(
preferences: readonly string[],
disponibles: readonly string[],
): string {
const codes = disponibles.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;
const voulue = preference.toLowerCase();
const exacte = codes.indexOf(voulue);
if (exacte >= 0) return disponibles[exacte] ?? LANGUE_DE_REPLI;
const principale = voulue.split('-')[0];
const proche = codes.findIndex((code) => code.split('-')[0] === principale);
if (proche >= 0) return disponibles[proche] ?? LANGUE_DE_REPLI;
}
return codes.includes(FALLBACK_LANGUAGE)
? FALLBACK_LANGUAGE
: (available[0] ?? FALLBACK_LANGUAGE);
return codes.includes(LANGUE_DE_REPLI) ? LANGUE_DE_REPLI : (disponibles[0] ?? LANGUE_DE_REPLI);
}
+8 -9
View File
@@ -1,11 +1,10 @@
/**
* 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.
* Événements du système qui annoncent qu'une reconnexion a des chances de
* réussir maintenant: retour du réseau, changement d'interface, réveil de
* l'appareil, page restaurée depuis le cache de navigation.
*
* 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`).
* Ce module ne décide rien: il prévient la session, qui seule sait si elle est
* en attente, abandonnée ou déjà connectée (voir `ViewerSession.wake`).
*/
export type WakeReason = 'online' | 'network_change' | 'visible' | 'pageshow';
@@ -13,9 +12,9 @@ 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.
* Branche les écouteurs et renvoie la fonction qui les retire. Chaque cible est
* facultative: `navigator.connection` n'existe ni sous Safari ni sous Firefox,
* et rien de tout cela n'existe dans un test sans DOM.
*/
export function watchLifecycle(onWake: (reason: WakeReason) => void): () => void {
const cleanups: Array<() => void> = [];
+5 -5
View File
@@ -7,7 +7,7 @@ function respond(status: number, body: unknown): typeof fetch {
}
describe('exchangeCode', () => {
it('returns the session path, versioned', async () => {
it('rend le chemin de la session, versionné', async () => {
const outcome = await exchangeCode(
'k7m4pq',
respond(200, {
@@ -22,7 +22,7 @@ describe('exchangeCode', () => {
});
});
it('tells an unknown code, an expired one, and too many attempts apart', async () => {
it('distingue un code inconnu, expiré, et trop d’essais', async () => {
expect(await exchangeCode('x', respond(404, { status: 'unknown' }))).toEqual({
kind: 'unknown',
});
@@ -34,16 +34,16 @@ describe('exchangeCode', () => {
).toEqual({ kind: 'too_many_attempts', retryAfterS: 42 });
});
it('does not throw when the network fails', async () => {
it('ne lève pas quand le réseau échoue', async () => {
const broken: typeof fetch = async () => {
throw new TypeError('network');
throw new TypeError('réseau');
};
expect(await exchangeCode('x', broken)).toEqual({ kind: 'network' });
});
});
describe('qrDetector', () => {
it('steps aside when the browser has no BarcodeDetector', () => {
it('se retire quand le navigateur n’a pas BarcodeDetector', () => {
expect(qrDetector()).toBeNull();
});
});
+8 -8
View File
@@ -1,7 +1,7 @@
/**
* 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.
* Appairage sans caméra (#19): le code court affiché par l'hôte, échangé
* contre la room et le jeton. Et, quand le navigateur le permet, la lecture du
* QR code depuis la page elle-même.
*/
import { LINK_VERSION, type PairingResponse } from '../proto';
@@ -13,7 +13,7 @@ export type CodeOutcome =
| { kind: 'too_many_attempts'; retryAfterS: number }
| { kind: 'network' };
/** Exchanges a code for the session path. Never throws. */
/** Échange un code contre le chemin de la session. Ne lève jamais. */
export async function exchangeCode(
code: string,
fetchImpl: typeof fetch = fetch,
@@ -46,16 +46,16 @@ export async function exchangeCode(
}
}
/** The subset of the BarcodeDetector API in use. */
/** Le minimum de l'API BarcodeDetector dont on se sert. */
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.
* Un lecteur de QR code, si ce navigateur en expose un. Il faut aussi une
* caméra, donc un contexte sécurisé: une page servie en HTTP sur le LAN n'y a
* pas droit, et le code court prend le relais.
*/
export function qrDetector(): Detector | null {
const scope = globalThis as unknown as {
-50
View File
@@ -1,50 +0,0 @@
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);
});
});
Loaded 100 of 268 files, more files were not shown because too many files have changed in this diff. Show more