14 Commits
Author SHA1 Message Date
Guillaume AssierandClaude Opus 5.5 a7a77208fb chore: 0.5.0, parité Community
CI / Formatting, tests and builds (push) Successful in 2m36s
Release / Packages and release (push) Failing after 7s
Version 0.5.0 dans le workspace, le viewer, l'application de bureau et
les paquets Nix (hash npm du viewer recalculé; le hash pnpm de
l'interface ne change pas). Notes de version dans docs/releases/v0.5.0.md,
avec ce qui est vérifié et ce qui ne l'est pas. Les paquets Nix
annoncent la licence du dépôt, Apache-2.0, au lieu de MIT.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 11:37:36 +01:00
Guillaume AssierandClaude Opus 5.5 0c24b2b5d2 refactor: code en anglais, rustscreen ouvre l'application de bureau
CI / Formatting, tests and builds (push) Successful in 3m19s
Code en anglais (#83): identifiants, noms de fichiers et de modules,
commentaires, journal (champ event, noms d'événements anglais),
messages d'erreur, commandes Tauri, types générés, clés de traduction,
sorties de rustscreen-cli, scripts, Nix et CI. Les textes affichés
passent toujours par locales/ (français et anglais); la documentation et
les commits restent en français. AGENTS.md porte la règle.

Ce qui est déjà écrit chez l'utilisateur se relit: anciens noms de
champs des réglages (alias serde), reglages.json à défaut de
settings.json, anciennes clés localStorage dont l'identifiant d'appareil,
jeton de restauration du portail, anciennes options de la ligne de
commande, ancien argument du démarrage automatique.

rustscreen ouvre l'application de bureau (#84): la ligne de commande
devient rustscreen-cli. Le paquet Nix par défaut construit l'application
(interface pnpm, Tauri avec WebKitGTK et PipeWire, icône de barre
système), avec rustscreen-cli et le viewer.

Début du jalon 0.6.0, pas encore essayé en vrai: miroir du viewer
(#29), barres qui s'effacent en fenêtre et en plein écran (#31, #81),
confirmation avant de quitter pendant un partage (#43), démarrage
automatique caché dans la barre système et fichier .desktop réparé au
lancement (#32).

Closes #83, #84
Refs #29, #31, #32, #43, #81

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 11:11:34 +01:00
Guillaume AssierandClaude Opus 5.5 73d1ef905a fix(capture): lire les tampons MemFd de GNOME, l'écran partagé était noir
CI / Formatage, tests et builds (push) Successful in 2m23s
GNOME livre les images du portail dans des tampons MemFd que PipeWire ne
mappe pas: data() est vide malgré MAP_BUFFERS. La capture les ignorait
sans rien dire, n'avait jamais d'image, et le spectateur recevait une
piste vide. La zone utile se lit maintenant par pread sur le descripteur,
sans mmap.

Le journal dit désormais comment arrive le premier tampon
(premier_tampon), la première panne de capture ou d'encodage, et la
première image encodée: une panne de ce genre ne reste plus muette.

Banc PipeWire sans portail ajouté (examples/pipewire_local.rs). Vérifié
sur GNOME 46 Wayland, écran 1920x1080: première image chez Firefox en
534 ms, image non noire.

Closes #80

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 21:33:01 +01:00
Guillaume AssierandClaude Opus 5.5 8bde177aa5 chore(ci): diviser par deux la durée d'une MR
CI / Formatage, tests et builds (push) Successful in 2m28s
- les tests export_bindings tournent avec le reste: l'étape « types à
  jour » ne fait plus que comparer, au lieu d'une seconde invocation de
  cargo qui recompilait la moitié du workspace (34 s); elle voit aussi un
  type nouveau jamais commité, par git status
- le binaire qui démarre est celui que les tests ont compilé; le build
  release ne tourne plus que sur main (76 s), la release le refait
- dépendances en debug « line-tables-only »: binaires de test trois fois
  plus légers (283 à 99 Mo), édition de liens plus courte, traces de
  pile toujours lisibles

Refs #78

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 18:35:07 +01:00
Guillaume AssierandClaude Opus 5.5 2f145183ff chore(deps): verrous à jour après les mises à jour Renovate
CI / Formatage, tests et builds (push) Successful in 3m26s
CI / Formatage, tests et builds (pull_request) Successful in 3m6s
Cargo.lock suit base64 0.23 et tokio-tungstenite 0.30 (#77, #74), celui
de la coque aussi pour base64. pnpm 12.15 (#73) réécrit pnpm-lock.yaml
sans changer de version de dépendance. Portes vérifiées: fmt, clippy avec
et sans PipeWire, tests du workspace, lint, tests et build de la coque.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 17:31:18 +01:00
Guillaume Assier 78f54ffc53 Merge remote-tracking branch 'origin/renovate/actions-checkout-7.x' 2026-10-26 17:28:47 +01:00
Guillaume Assier b4e3b85a6c Merge remote-tracking branch 'origin/renovate/pnpm-12.x' 2026-10-26 17:28:47 +01:00
Guillaume Assier 2c57894373 Merge remote-tracking branch 'origin/renovate/tokio-tungstenite-0.x' 2026-10-26 17:28:47 +01:00
Guillaume Assier 085e0ddffb Merge remote-tracking branch 'origin/renovate/base64-0.x' 2026-10-26 17:28:47 +01:00
Guillaume AssierandClaude Opus 5.5 c4f2c229b3 feat: parité Community, appairage, fenêtre seule, barre système, langues
CI / Formatage, tests et builds (push) Successful in 3m16s
- appairage: lien du QR code versionné (v=1, empreinte en HTTPS), code
  court de six caractères échangé par /api/code avec essais limités,
  jeton qui expire et se régénère, token_expired distinct de bad_token;
  un appareil déjà admis revient après l'échéance (#19)
- une seule fenêtre: filtrage des fenêtres sans intérêt et de rustscreen
  lui-même, fenêtre réduite refusée avec sa raison et reprise à la
  restauration, fenêtre par le portail sous Wayland, limite affichée
  avant le démarrage (#17)
- icône de barre système qui suit l'état, menu ouvrir, reprendre,
  arrêter, quitter; fermer la fenêtre garde le partage (réglable), repli
  sur une réduction sans barre système (#22)
- traduction: locales/*.json servis par l'hôte au viewer et embarqués
  par la coque, langue de l'appareil, retour à l'anglais, contrôle de
  lint contre les textes en dur; français et anglais (#21)
- thème clair et sombre du viewer, contraste AA vérifié pour les deux
  applications (#28)
- rotation du flux par quart de tour, image entière (#30)
- VP9 temps réel: encodeur direct sur vpx-sys, premier paquet à la
  première image, type de charge utile choisi selon le codec, demandes
  d'image clé honorées, --codec et réglage codec (#67)

Corrige aussi le débordement de la page du viewer, où la taille
naturelle du flux poussait le pied de page hors de l'écran.

Closes #17, #19, #21, #22, #28, #30, #67

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 17:28:09 +01:00
renovate-bot 9099f22a63 fix(deps): update rust crate base64 to 0.23.0
renovate/artifacts Artifact file update failure
CI / Formatage, tests et builds (pull_request) Successful in 4m53s
2026-10-26 16:17:20 +00:00
renovate-bot 1ca03fe077 chore(deps): update rust crate tokio-tungstenite to 0.30.0
renovate/artifacts Artifact file update failure
CI / Formatage, tests et builds (pull_request) Successful in 3m2s
2026-10-26 15:18:15 +00:00
renovate-bot 90ac8a82da chore(deps): update pnpm to v12.15.0
renovate/artifacts Artifact file update failure
CI / Formatage, tests et builds (pull_request) Successful in 3m2s
2026-10-26 15:17:36 +00:00
renovate-bot 374e4e9143 chore(deps): update actions/checkout action to v7
CI / Formatage, tests et builds (pull_request) Successful in 2m58s
2026-10-25 18:17:30 +00:00
211 changed files with 14634 additions and 8359 deletions

No files matched your search

+69 -55
View File
@@ -1,20 +1,19 @@
# Chaîne d'intégration continue de rustscreen.
# rustscreen continuous integration.
#
# Elle tourne sur Gitea, sur le runner `rustscreen-ci`, qui est un hôte et non un
# conteneur : la machine n'a pas de démon Docker, mais elle a cargo, node et
# nasm. Ce runner est enregistré pour ce dépôt : celui d'Exoledge ne voit que les
# jobs de l'organisation Exoledge, et rustscreen vit sous `heap`. Le label est explicite pour qu'un changement d'environnement se voie
# dans le diff plutôt qu'en pleine exécution.
# It runs on Gitea, on the `rustscreen-ci` runner, which is a host and not a
# container: the machine has no Docker daemon, but it has cargo, node and nasm.
# This runner is registered for this repository: Exoledge's only sees jobs from
# the Exoledge organization, and rustscreen lives under `heap`. The label is
# explicit so that an environment change shows up in the diff rather than in
# the middle of a run.
#
# Deux précautions qui coûtent cher quand on les oublie :
# Two precautions that cost a lot when forgotten:
#
# - libvpx n'est pas fourni par le système. `env-libvpx-sys` exige un préfixe
# explicite, donc la chaîne construit libvpx une fois dans le cache et le
# réutilise. Sans ce cache, chaque exécution repaierait dix minutes de
# compilation C.
# - les caches sont rangés par dépôt. Le runner est partagé avec d'autres
# projets : un `CARGO_TARGET_DIR` commun ferait se marcher dessus des
# compilations qui n'ont rien à voir.
# - libvpx is not provided by the system. `env-libvpx-sys` requires an explicit
# prefix, so the pipeline builds libvpx once into the cache and reuses it.
# Without that cache, every run would pay ten minutes of C compilation again.
# - caches are kept per repository. The runner is shared with other projects:
# a common `CARGO_TARGET_DIR` would make unrelated builds trample each other.
name: CI
@@ -27,17 +26,17 @@ permissions:
contents: read
jobs:
integrer:
name: Formatage, tests et builds
integrate:
name: Formatting, tests and builds
runs-on: rustscreen-ci
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: Outils et caches
- name: Tools and caches
run: |
set -euo pipefail
# Les caches vivent hors du dépôt, et le répertoire est propre à ce
# projet: la machine de la chaîne est partagée avec d'autres.
# Caches live outside the repository, in a directory specific to this
# project: the CI machine is shared with others.
cache="${RUSTSCREEN_CACHE_DIR:-$HOME/.cache/rustscreen-ci}"
mkdir -p "$cache"
{
@@ -45,9 +44,9 @@ jobs:
echo "VPX_PREFIX=$cache/libvpx"
echo "npm_config_cache=$cache/npm"
} >> "$GITHUB_ENV"
# nasm, file et desktop-file-validate peuvent être installés par
# l'administrateur du runner dans ~/.local/bin, hors du PATH de la
# session. Absents, la chaîne se replie sur ce que le système fournit.
# 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.
if [ -d "$HOME/.local/bin" ]; then
echo "PATH=$HOME/.local/bin:$PATH" >> "$GITHUB_ENV"
fi
@@ -60,15 +59,15 @@ jobs:
cargo fmt --version
node --version
npm --version
nasm -v || echo "nasm absent: libvpx sera construit sans assembleur, encodage plus lent"
nasm -v || echo "nasm missing: libvpx will be built without an assembler, slower encoding"
- name: Bibliothèque libvpx
- name: libvpx library
run: |
set -euo pipefail
# La version est figée par le script : au-delà de 1.13, les bindings
# pré-générés de `env-libvpx-sys` ne suffisent plus.
# The version is pinned by the script: beyond 1.13, the pre-generated
# bindings of `env-libvpx-sys` are no longer enough.
if [ -f "$VPX_PREFIX/lib/libvpx.a" ]; then
echo "libvpx déjà construite dans $VPX_PREFIX"
echo "libvpx already built in $VPX_PREFIX"
else
./scripts/build-libvpx.sh "$VPX_PREFIX"
fi
@@ -78,72 +77,87 @@ jobs:
echo "VPX_VERSION=1.13.0"
} >> "$GITHUB_ENV"
- name: Dépendances du viewer
- name: Viewer dependencies
run: |
set -euo pipefail
cd apps/viewer
# `npm ci` plutôt que `npm install` : le fichier de verrouillage est la
# référence, la chaîne ne négocie aucune version.
# `npm ci` rather than `npm install`: the lock file is the reference,
# the pipeline negotiates no version.
npm ci --no-audit --no-fund
- name: Lint et types du viewer
- name: Viewer lint and types
run: |
set -euo pipefail
cd apps/viewer
npm run lint
npx tsc --noEmit
- name: Tests du viewer
- name: Viewer tests
run: |
set -euo pipefail
cd apps/viewer
npm test
- name: Bundle du viewer
- name: Viewer bundle
run: |
set -euo pipefail
cd apps/viewer
npm run build
- name: Formatage
- name: Formatting
run: cargo fmt --all --check
- name: Clippy
run: cargo clippy --workspace --all-targets -- -D warnings
- name: Tests
run: cargo test --workspace -- --skip export_bindings
# The `export_bindings` tests write the TypeScript types: they run
# here, with the rest, and the "up to date" step only compares. A
# second cargo invocation, with different features, rebuilt half of
# the workspace (34 s, #78).
run: cargo test --workspace
- name: Capture Wayland (PipeWire)
- name: Wayland capture (PipeWire)
run: |
set -euo pipefail
# 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).
# The feature requires libpipewire-0.3 and libclang (bindgen). The
# runner does not always have them: without them, the step says so and
# passes, and the release is the one that fails (see release.yml).
if pkg-config --exists libpipewire-0.3; then
cargo clippy -p rs-capture -p rs-session --features rs-session/pipewire --all-targets -- -D warnings
cargo test -p rs-capture --features pipewire
else
echo "libpipewire-0.3 absente du runner: capture Wayland non vérifiée"
echo "libpipewire-0.3 missing on the runner: Wayland capture not checked"
fi
- name: Binaire de publication
- name: The binary starts
run: |
set -euo pipefail
# La chaîne ne se contente pas de tester : elle vérifie que le binaire
# se construit et démarre, parce qu'un produit qui ne démarre pas passe
# tous les tests unitaires.
cargo build --release -p rs-session --bin rustscreen
"$CARGO_TARGET_DIR/release/rustscreen" --version
# 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: Le protocole TypeScript est à jour
- name: Release binary
# On main only: the whole stack in release costs more than a minute,
# and the release workflow rebuilds it anyway (#78).
if: github.event_name == 'push'
run: |
set -euo pipefail
# Les types du protocole sont générés depuis Rust. Un écart entre le
# dépôt et la génération veut dire que le viewer compile contre une
# version périmée du protocole, ce qui ne se voit qu'en production.
cargo test -p rs-proto -p rs-store -p rs-session export_bindings >/dev/null
git diff --exit-code -- apps/viewer/src/proto apps/desktop/src/bindings || {
echo "types TypeScript générés pas à jour : lancer make proto et commiter" >&2
cargo build --release -p rs-session --bin rustscreen-cli
"$CARGO_TARGET_DIR/release/rustscreen-cli" --version
- name: The TypeScript protocol is up to date
run: |
set -euo pipefail
# The protocol types are generated from Rust. A gap between the
# repository and the generated output means the viewer compiles
# against a stale protocol, which only shows in production.
# Written by the "Tests" step: all that is left is to compare.
# `status` rather than `diff`: a new type, never committed, counts too.
drift=$(git status --porcelain -- apps/viewer/src/proto apps/desktop/src/bindings)
if [ -n "$drift" ]; then
echo "$drift" >&2
echo "generated TypeScript types are out of date: run make proto and commit" >&2
exit 1
}
fi
+42 -42
View File
@@ -1,14 +1,14 @@
# Publication : une étiquette `vX.Y.Z` produit une release avec ses artefacts.
# Release: a `vX.Y.Z` tag produces a release with its artifacts.
#
# Rien d'autre ne déclenche cette chaîne: pas de bouton, pas de commande tapée
# sur un portable, et pas de numéro de version écrit à la main dans un fichier.
# L'étiquette git est la seule source de la version; le binaire et l'AppImage en
# découlent, et la release dit ce qu'elle contient.
# Nothing else triggers this pipeline: no button, no command typed on a laptop,
# and no version number written by hand in a file. The git tag is the single
# source of the version; the binary and the AppImage follow from it, and the
# release states what it contains.
#
# Elle vérifie d'abord que l'étiquette correspond à la version déclarée dans le
# `Cargo.toml`: une release `v0.2.0` construite sur un `Cargo.toml` en `0.1.0`
# mentirait sur son contenu, et c'est le genre d'erreur qu'on ne voit qu'après
# avoir distribué le paquet.
# It first checks that the tag matches the version declared in `Cargo.toml`: a
# `v0.2.0` release built from a `Cargo.toml` at `0.1.0` would lie about its
# contents, and that is the kind of mistake only noticed after the package has
# been distributed.
name: Release
@@ -21,20 +21,20 @@ permissions:
jobs:
release:
name: Paquets et release
name: Packages and release
runs-on: rustscreen-ci
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
with:
# `git describe` et l'historique depuis l'étiquette précédente ont
# besoin des étiquettes, que le clone superficiel ne prend pas.
# `git describe` and the history since the previous tag need the
# tags, which a shallow clone does not fetch.
fetch-depth: 0
- name: Outils et caches
- name: Tools and caches
run: |
set -euo pipefail
# Les caches vivent hors du dépôt, et le répertoire est propre à ce
# projet: la machine de la chaîne est partagée avec d'autres.
# Caches live outside the repository, in a directory specific to this
# project: the CI machine is shared with others.
cache="${RUSTSCREEN_CACHE_DIR:-$HOME/.cache/rustscreen-ci}"
mkdir -p "$cache"
{
@@ -42,26 +42,26 @@ jobs:
echo "VPX_PREFIX=$cache/libvpx"
echo "npm_config_cache=$cache/npm"
} >> "$GITHUB_ENV"
# nasm, file et desktop-file-validate peuvent être installés par
# l'administrateur du runner dans ~/.local/bin, hors du PATH de la
# session. Absents, la chaîne se replie sur ce que le système fournit.
# 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.
if [ -d "$HOME/.local/bin" ]; then
echo "PATH=$HOME/.local/bin:$PATH" >> "$GITHUB_ENV"
fi
- name: Version et étiquette
- name: Version and tag
run: |
set -euo pipefail
etiquette="${GITHUB_REF_NAME#v}"
declaree=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)
if [ "$etiquette" != "$declaree" ]; then
echo "étiquette v$etiquette mais Cargo.toml déclare $declaree" >&2
tag="${GITHUB_REF_NAME#v}"
declared=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)
if [ "$tag" != "$declared" ]; then
echo "tag v$tag but Cargo.toml declares $declared" >&2
exit 1
fi
echo "VERSION=$etiquette" >> "$GITHUB_ENV"
echo "version $etiquette confirmée"
echo "VERSION=$tag" >> "$GITHUB_ENV"
echo "version $tag confirmed"
- name: Bibliothèque libvpx
- name: libvpx library
run: |
set -euo pipefail
if [ ! -f "$VPX_PREFIX/lib/libvpx.a" ]; then
@@ -80,21 +80,21 @@ jobs:
npm ci --no-audit --no-fund
npm run build
- name: Binaire
- name: Binary
run: |
set -euo pipefail
# 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.
# A binary released without PipeWire captures nothing under Wayland,
# the product's target (ADR 0009): the release fails rather than ship
# it. The runner needs libpipewire-0.3-dev and libclang-dev.
if ! pkg-config --exists libpipewire-0.3; then
echo "libpipewire-0.3 introuvable: installer libpipewire-0.3-dev et libclang-dev sur le runner" >&2
echo "libpipewire-0.3 not found: install libpipewire-0.3-dev and libclang-dev on the runner" >&2
exit 1
fi
cargo build --release -p rs-session --features pipewire --bin rustscreen
# 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
cargo build --release -p rs-session --features pipewire --bin rustscreen-cli
# The binary is distributed: its symbols only help development
# diagnostics and weigh half of the file.
strip "$CARGO_TARGET_DIR/release/rustscreen-cli"
"$CARGO_TARGET_DIR/release/rustscreen-cli" --version
- name: AppImage
run: |
@@ -103,20 +103,20 @@ jobs:
- name: Release
env:
# Le jeton de la chaîne, avec les droits d'écriture demandés plus haut.
# The pipeline token, with the write permission requested above.
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
# `RELEASE_NOTES` désigne un fichier versionné quand il existe; sinon
# le script écrit une note minimale plutôt que d'échouer.
# `RELEASE_NOTES` points to a versioned file when it exists; otherwise
# the script writes a minimal note rather than failing.
notes="docs/releases/${GITHUB_REF_NAME}.md"
if [ ! -f "$notes" ]; then
echo "pas de notes pour ${GITHUB_REF_NAME}, note minimale" >&2
echo "no notes for ${GITHUB_REF_NAME}, minimal note" >&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"
"$CARGO_TARGET_DIR/release/rustscreen-cli"
+69 -25
View File
@@ -12,19 +12,34 @@ code. La cible fonctionnelle est le plan **Pro** de Deskreen, plus les fonctions
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), écran virtuel par le portail (GNOME 46, KDE), conversion BGRA vers I420, encodage
VP8 qui suit les changements de résolution, session str0m par spectateur, serveur local avec jeton,
viewer React qui reprend seul après une coupure ou une veille, coque desktop Tauri, réglages
persistants, inhibition de veille, journal JSON local et archive de diagnostics.
Ce qui manque: l'icône de barre système, la capture Windows, et l'encodeur matériel.
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, 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.
Ce qui manque: la capture Windows et macOS, l'encodeur matériel, et la traduction des messages
produits par l'hôte (erreurs, avertissements), aujourd'hui en anglais seulement (#75).
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.
L'hôte tient dans `rs-session::Host`: démarrer, arrêter, déconnecter un spectateur, régler, et
publier l'état complet à chaque changement. Lancer `rustscreen` ouvre l'application de bureau
(`apps/desktop/src-tauri`); la ligne de commande est `rustscreen-cli`
(`rs-session/src/bin/rustscreen-cli.rs`). Les deux ne font que piloter l'hôte: aucune ne connaît
la capture ni le serveur.
## Conventions
### Langue
- **Le code est en anglais**: identifiants, noms de fichiers et de modules, commentaires, messages
et noms d'événements du journal, messages d'erreur, sorties de `rustscreen-cli`, scripts (#83).
- **Les textes affichés à l'utilisateur** passent par `locales/` (français et anglais), jamais en dur.
- **La documentation** (`docs/`, ce fichier, `README.md`) **et les messages de commit** restent en
français.
- Un format déjà écrit chez l'utilisateur garde ses anciens noms en lecture: alias `serde` des
réglages, `reglages.json` relu à défaut de `settings.json`, anciennes clés `localStorage`,
anciennes options de la ligne de commande, ancien fichier de restauration du portail.
### Rust
- Édition 2024, un crate par domaine sous `crates/`, préfixe `rs-`. Le spike jetable est sous
@@ -45,6 +60,13 @@ capture ni le serveur.
coque avec **pnpm** (`pnpm-lock.yaml`).
- Les types de la coque (`apps/desktop/src/bindings`) sont générés depuis `rs-store` et
`rs-session`, comme ceux du viewer depuis `rs-proto`: `make proto`.
- **Aucun texte en dur dans un composant.** Les textes vivent dans `locales/<langue>.json`, une
section par application, et passent par `t('clé')`. L'anglais est la langue de repli et doit
être complet, le français aussi. `npm run lint` (viewer) et `pnpm lint` (coque) lancent
`scripts/check-i18n.mjs`, qui refuse une clé absente de l'anglais et un texte en dur. Ajouter
une langue, c'est ajouter un fichier: l'hôte l'embarque (`rs-signaling/build.rs`) et la sert au
viewer, la coque l'embarque à la compilation. Le viewer et la coque partagent le cœur
(`apps/viewer/src/lib/i18n.ts`), sans React.
- Aucune dépendance à un service externe : pas d'analytics, pas de CDN, pas de police distante.
Le client doit fonctionner sur un LAN sans Internet.
- Le protocole vient de `rs-proto`. Un type de message en double (un côté Rust, un côté TS, écrit
@@ -95,19 +117,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.
Le banc d'essai actuel est le binaire `rustscreen` de `rs-session`: il assemble la vraie pile
Le banc d'essai actuel est le binaire `rustscreen-cli` de `rs-session`: il assemble la vraie pile
(capture, encodage, protocole, session, serveur) et sait aussi rejouer une mire IVF.
```bash
# mire synthétique: capture, conversion BGRA vers I420, encodage VP8, en direct
cargo run -p rs-session --bin rustscreen -- --synthetic --port 8099
cargo run -p rs-session --bin rustscreen-cli -- --synthetic --port 8099
# ou rejeu d'un fichier encodé, sans encodeur
cargo run -p rs-session --bin rustscreen -- spikes/str0m-mire/mire.ivf --port 8099
cargo run -p rs-session --bin rustscreen-cli -- 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/reglages.json`, partagés avec la coque). Sans TLS, le serveur est en HTTP simple:
sinon des réglages (`~/.config/rustscreen/settings.json`, partagés avec l'application de bureau). Sans TLS, le serveur est en HTTP simple:
pratique pour un navigateur local, insuffisant pour un vrai appareil (voir ADR 0005).
La capture réelle sous Wayland demande la feature `pipewire` (libpipewire-0.3 et libclang au
@@ -116,35 +138,46 @@ 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
cargo run --release -p rs-session --features pipewire --bin rustscreen-cli
# second écran créé par le portail, à la taille de la tablette
cargo run --release -p rs-session --features pipewire --bin rustscreen -- --virtuel --size 1280x800
cargo run --release -p rs-session --features pipewire --bin rustscreen-cli -- --virtual --size 1280x800
# archive de diagnostics, sans rien démarrer
cargo run -p rs-session --bin rustscreen -- --diagnostics
cargo run -p rs-session --bin rustscreen-cli -- --diagnostics
# VP9 au lieu de VP8 (même qualité pour moins de débit, 1,6x le calcul), une fenêtre par le portail
cargo run --release -p rs-session --features pipewire --bin rustscreen-cli -- --codec vp9 --pick-window
```
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-desktop)
make desktop # pnpm install, interface, puis binaire (target/release/rustscreen)
nix build .#rustscreen # le paquet: application de bureau, rustscreen-cli et viewer
make desktop-lint # biome, vitest, rustfmt et clippy de la coque
```
En debug, le binaire embarque `apps/desktop/dist` (feature `custom-protocol` par défaut);
`--no-default-features` charge le serveur Vite (`pnpm --dir apps/desktop dev`) à la place.
Le chemin se force avec `RUSTSCREEN_CAPTURE=portail|x11|synthetique`. Le test X11 réel se lance
Le chemin se force avec `RUSTSCREEN_CAPTURE=portal|x11|synthetic`. Le test X11 réel se lance
contre un serveur jetable: `Xephyr :5 & DISPLAY=:5 xeyes &` puis
`RUSTSCREEN_X11_TEST=:5 cargo test -p rs-capture x11 -- --ignored`. Pour plusieurs moniteurs,
lancer Xephyr avec `+extension RANDR` et en déclarer avec `xrandr --setmonitor` (voir le test).
Avec openbox sur ce serveur, le même test réduit puis restaure une fenêtre partagée (#17).
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`. Ne jamais y écrire un titre de fenêtre ni une
image (ADR 0008).
Pour essayer la coque ou un navigateur sans rien ouvrir sur le bureau, préférer `Xvfb` à
`Xephyr`, qui affiche une fenêtre. L'icône de barre système, elle, passe par le bus de session: elle
apparaît dans la vraie barre. Elle se vérifie par D-Bus (`org.kde.StatusNotifierWatcher`, menu
`com.canonical.dbusmenu`), et son menu se pilote par `Event`.
Le journal JSON (`~/.local/state/rustscreen/logs`) nomme les étapes d'une session par le champ
`event`: `portal_granted`, `capture_format`, `first_buffer`, `first_frame_encoded`,
`session_opened`, `ice_candidate_selected`, `first_frame_sent`, `quality_change`, `disconnected`
(avec `cause`), `capture_revoked`, `capture_failed`, `encode_failed`, et côté hôte `share_started`,
`share_ended`, `share_interrupted`, `viewer_disconnected`, `resolution_changed`, `sleep_inhibited`,
`sleep_released`, `wake_detected`, `capture_restarted`, `address_changed`, `settings_changed`,
`access_regenerated`, `code_accepted`, `code_rejected`. Avant la 0.6, ces noms étaient en français
(champ `evenement`). Ne jamais y écrire un titre de fenêtre ni une image (ADR 0008).
Le spike historique `spikes/str0m-mire` reste pour comparer les mesures:
@@ -173,6 +206,12 @@ vérifier qu'une régression ne casse pas le transport.
connexion depuis un autre appareil que l'hôte, alors que tous les essais sur `127.0.0.1`
passaient. Tester le viewer par l'adresse du LAN, jamais seulement par le loopback.
- **Le type de charge utile suit le codec encodé**, jamais le premier venu: `payload_params().next()`
prenait VP8 pendant qu'on envoyait du VP9, et le navigateur affichait un écran noir sans erreur.
- **libvpx 1.13 plante en VP9 à la vitesse 6**, et avec le réglage « contenu écran » à toute vitesse
(SIGSEGV dans `vpx_variance8x8_sse2`, reproduit en C pur; corrigé en 1.14). L'encodeur est figé
à la vitesse 7 et le test `vp9_survives_moving_content` tombe si quelqu'un remet 6.
## Pièges du portail, appris à la dure
La négociation du portail a « compilé et passé les tests » avec trois bugs que seule une vraie
@@ -183,5 +222,10 @@ 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 `aucune_connexion_sortante`).
inodes de `/proc/self/fd` (voir le test `no_outbound_connection`).
Generated
+71 -62
View File
@@ -81,7 +81,7 @@ dependencies = [
"nom 7.1.3",
"num-traits",
"rusticata-macros",
"thiserror 2.0.21",
"thiserror",
"time",
]
@@ -181,10 +181,10 @@ dependencies = [
"serde_json",
"serde_path_to_error",
"serde_urlencoded",
"sha1",
"sha1 0.10.7",
"sync_wrapper",
"tokio",
"tokio-tungstenite",
"tokio-tungstenite 0.29.0",
"tower",
"tower-layer",
"tower-service",
@@ -1650,35 +1650,35 @@ dependencies = [
[[package]]
name = "rs-capture"
version = "0.4.0"
version = "0.5.0"
dependencies = [
"pipewire",
"rs-proto",
"rustix",
"thiserror 2.0.21",
"thiserror",
"tracing",
"x11rb",
]
[[package]]
name = "rs-codec"
version = "0.4.0"
version = "0.5.0"
dependencies = [
"env-libvpx-sys",
"rs-capture",
"rs-proto",
"thiserror 2.0.21",
"thiserror",
"tracing",
"vpx-encode",
]
[[package]]
name = "rs-diag"
version = "0.4.0"
version = "0.5.0"
dependencies = [
"if-addrs",
"serde",
"serde_json",
"thiserror 2.0.21",
"thiserror",
"tracing",
"tracing-appender",
"tracing-subscriber",
@@ -1687,12 +1687,12 @@ dependencies = [
[[package]]
name = "rs-platform"
version = "0.4.0"
version = "0.5.0"
dependencies = [
"futures-util",
"if-addrs",
"serde",
"thiserror 2.0.21",
"thiserror",
"tokio",
"tracing",
"zbus",
@@ -1700,30 +1700,30 @@ dependencies = [
[[package]]
name = "rs-proto"
version = "0.4.0"
version = "0.5.0"
dependencies = [
"serde",
"serde_json",
"thiserror 2.0.21",
"thiserror",
"ts-rs",
]
[[package]]
name = "rs-rtc"
version = "0.4.0"
version = "0.5.0"
dependencies = [
"rs-codec",
"str0m",
"thiserror 2.0.21",
"thiserror",
"tokio",
"tracing",
]
[[package]]
name = "rs-session"
version = "0.4.0"
version = "0.5.0"
dependencies = [
"base64 0.22.1",
"base64 0.23.1",
"futures-util",
"png",
"rs-capture",
@@ -1736,16 +1736,16 @@ dependencies = [
"rs-store",
"serde",
"serde_json",
"thiserror 2.0.21",
"thiserror",
"tokio",
"tokio-tungstenite",
"tokio-tungstenite 0.30.0",
"tracing",
"ts-rs",
]
[[package]]
name = "rs-signaling"
version = "0.4.0"
version = "0.5.0"
dependencies = [
"axum",
"axum-server",
@@ -1761,7 +1761,7 @@ dependencies = [
"serde",
"serde_json",
"sha2",
"thiserror 2.0.21",
"thiserror",
"tokio",
"tower-http",
"tracing",
@@ -1769,12 +1769,12 @@ dependencies = [
[[package]]
name = "rs-store"
version = "0.4.0"
version = "0.5.0"
dependencies = [
"rs-proto",
"serde",
"serde_json",
"thiserror 2.0.21",
"thiserror",
"tracing",
"ts-rs",
]
@@ -1866,7 +1866,7 @@ dependencies = [
"rand 0.9.5",
"rustc-hash",
"slab",
"thiserror 2.0.21",
"thiserror",
]
[[package]]
@@ -1978,6 +1978,17 @@ dependencies = [
"digest 0.10.7",
]
[[package]]
name = "sha1"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"
dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
"digest 0.11.3",
]
[[package]]
name = "sha2"
version = "0.11.1"
@@ -2216,33 +2227,13 @@ dependencies = [
"winapi-util",
]
[[package]]
name = "thiserror"
version = "1.0.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
dependencies = [
"thiserror-impl 1.0.69",
]
[[package]]
name = "thiserror"
version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
dependencies = [
"thiserror-impl 2.0.21",
]
[[package]]
name = "thiserror-impl"
version = "1.0.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
"thiserror-impl",
]
[[package]]
@@ -2341,7 +2332,19 @@ dependencies = [
"futures-util",
"log",
"tokio",
"tungstenite",
"tungstenite 0.29.0",
]
[[package]]
name = "tokio-tungstenite"
version = "0.30.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "17a073bfed563fa236697a068031408a93cd9522e08abf9933ead3e73411bd71"
dependencies = [
"futures-util",
"log",
"tokio",
"tungstenite 0.30.0",
]
[[package]]
@@ -2470,7 +2473,7 @@ checksum = "050686193eb999b4bb3bc2acfa891a13da00f79734704c4b8b4ef1a10b368a3c"
dependencies = [
"crossbeam-channel",
"symlink",
"thiserror 2.0.21",
"thiserror",
"time",
"tracing-subscriber",
]
@@ -2544,7 +2547,7 @@ version = "12.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "756050066659291d47a554a9f558125db17428b073c5ffce1daf5dcb0f7231d8"
dependencies = [
"thiserror 2.0.21",
"thiserror",
"ts-rs-macros",
]
@@ -2572,8 +2575,24 @@ dependencies = [
"httparse",
"log",
"rand 0.9.5",
"sha1",
"thiserror 2.0.21",
"sha1 0.10.7",
"thiserror",
]
[[package]]
name = "tungstenite"
version = "0.30.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e48ac77174b19c110a50ab2128b24215ac9cb40e0e12e093fb602d175c569d22"
dependencies = [
"bytes",
"data-encoding",
"http",
"httparse",
"log",
"rand 0.10.3",
"sha1 0.11.0",
"thiserror",
]
[[package]]
@@ -2658,16 +2677,6 @@ version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "vpx-encode"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd1f41af42de7667cbdba44e8c38c36e9ede970f1291c32ea57c0ded8eb6f4b6"
dependencies = [
"env-libvpx-sys",
"thiserror 1.0.69",
]
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
@@ -2883,7 +2892,7 @@ dependencies = [
"oid-registry",
"ring",
"rusticata-macros",
"thiserror 2.0.21",
"thiserror",
"time",
]
+7 -1
View File
@@ -16,7 +16,7 @@ members = [
exclude = ["apps/desktop/src-tauri"]
[workspace.package]
version = "0.4.0"
version = "0.5.0"
edition = "2024"
rust-version = "1.90"
license = "Apache-2.0"
@@ -27,3 +27,9 @@ serde = { version = "1", features = ["derive"] }
serde_json = "1"
thiserror = "2"
tracing = "0.1"
# Les dépendances sans informations de débogage complètes: des binaires de test
# trois fois plus légers et une édition de liens plus courte (#78). Les numéros
# de ligne restent, une trace de pile se lit toujours; nos crates gardent tout.
[profile.dev.package."*"]
debug = "line-tables-only"
+12 -12
View File
@@ -1,4 +1,4 @@
# Portes du projet. `make` seul lance tout ce qui doit être vert avant un commit.
# Project gates. Plain `make` runs everything that must pass before a commit.
.PHONY: all fmt lint test build proto bench clean desktop desktop-lint
@@ -13,15 +13,15 @@ lint:
cargo clippy --workspace --all-targets -- -D warnings
npm --prefix apps/viewer run lint
# `--skip export_bindings` : les tests de génération de ts-rs écriraient dans
# apps/viewer/src/proto à chaque exécution. La cible `proto` s'en charge, avec
# le formatage qui va avec.
# `--skip export_bindings`: the ts-rs generation tests would write into
# apps/viewer/src/proto on every run. The `proto` target handles that, along
# with the matching formatting.
test:
cargo test --workspace -- --skip export_bindings
# Les types TypeScript du protocole sont générés, jamais écrits à la main.
# Ils sont exclus du formateur et du linter (voir biome.json): leur format
# appartient à ts-rs, sinon chaque `make` laisse un diff dans le dépôt.
# The protocol's TypeScript types are generated, never written by hand.
# They are excluded from the formatter and the linter (see biome.json): their
# format belongs to ts-rs, otherwise every `make` leaves a diff in the repository.
proto:
cargo test -p rs-proto -p rs-store -p rs-session export_bindings
@@ -29,13 +29,13 @@ build:
cargo build --workspace
npm --prefix apps/viewer run build
# Banc d'essai: toujours en release, un binaire debug fausse les mesures.
# Test bench: always in release, a debug binary skews the measurements.
bench:
cargo run --release -p rs-session --bin rustscreen -- --synthetic
cargo run --release -p rs-session --bin rustscreen-cli -- --synthetic
# 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.
# The Tauri shell: WebKitGTK at build time, so inside `nix develop .#desktop`.
# Its crate has its own workspace; it shares the target directory to avoid
# rebuilding everything. pnpm for the shell's interface, npm for the viewer.
desktop:
pnpm --dir apps/desktop install --frozen-lockfile
pnpm --dir apps/desktop build
+5 -3
View File
@@ -13,7 +13,7 @@ hôte en Rust, un client web en TypeScript et une interface desktop Tauri.
- 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,
- **écran virtuel** par le portail du bureau (`--virtual`): 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
@@ -65,6 +65,7 @@ offre SaaS multi-tenant. Ils sont cadrés dans le backlog comme extensions, pas
```
apps/desktop UI Tauri (front TS) + src-tauri (commandes, cycle de vie)
apps/viewer client navigateur (TS, Vite)
locales textes de l'interface, un fichier JSON par langue
crates/rs-proto types partagés, versions, modèle de session
crates/rs-capture abstraction de capture + implémentations par OS
crates/rs-codec conversion de pixels et encodeurs vidéo
@@ -88,8 +89,9 @@ docs architecture, ADR, matrice de fonctionnalités, backlog
## Installer
```sh
nix run . # Nix: reproductible, tout est inclus
./scripts/build-appimage.sh # AppImage: un fichier, rien à installer
nix run . # l'application de bureau (Nix: reproductible, tout est inclus)
nix run .#rustscreen-cli # la ligne de commande seule
./scripts/build-appimage.sh # AppImage de la ligne de commande: un fichier, rien à installer
```
Détails, prérequis et limites dans [docs/PACKAGING.md](docs/PACKAGING.md). Les deux paquets
+4 -4
View File
@@ -1,14 +1,14 @@
{
"name": "@rustscreen/desktop",
"private": true,
"version": "0.4.0",
"version": "0.5.0",
"type": "module",
"packageManager": "pnpm@12.9.0",
"description": "Coque desktop de rustscreen: choisir la source, voir les spectateurs, couper.",
"packageManager": "pnpm@12.15.0",
"description": "rustscreen desktop shell: pick the source, see the viewers, stop.",
"scripts": {
"dev": "vite",
"build": "tsc --noEmit && vite build",
"lint": "biome lint src",
"lint": "biome lint src && node ../../scripts/check-i18n.mjs apps/desktop/src desktop",
"format": "biome format --write src",
"test": "vitest run"
},
+62 -62
View File
@@ -7,153 +7,153 @@ importers:
configDependencies: {}
packageManagerDependencies:
pnpm:
specifier: 12.9.0
version: 12.9.0
specifier: 12.15.0
version: 12.15.0
packages:
'@pnpm/exe.android-arm64@12.9.0':
resolution: {integrity: sha512-/53fHFwP1mBYQjli6h3LBZsocAMjrEY6hCDiomIwdLIFbtxHrWucPg/s8ozOG3K6Qt8yEA78v7fCcNrgZKTlEQ==}
'@pnpm/exe.android-arm64@12.15.0':
resolution: {integrity: sha512-eVCqmscY70LGvgRzu3mi8IBWBFGix+a6mNZoWmXxESsBdeiKEF9xQSuaeel10yn+zI7TXy2jlI63vFLzETk+aQ==}
cpu: [arm64]
os: [android]
'@pnpm/exe.android-x64@12.9.0':
resolution: {integrity: sha512-QI+Md3q3Df0WbDGpqciRw9ge0r7CGbxSlP3HcyIf34/YdZsbmUTl416oWOe3RrkZpVVVCA20f8B9esYrITpArA==}
'@pnpm/exe.android-x64@12.15.0':
resolution: {integrity: sha512-Gx/WbkFcdUFUg8g8AShezcS9EiQxfYvdAm2hfKLO8sfJmJvKOCt5fzlgHWDzmGhoclibgW+tUGZ/KF4F4wOTCA==}
cpu: [x64]
os: [android]
'@pnpm/exe.darwin-arm64@12.9.0':
resolution: {integrity: sha512-mWr7fGPYJ12GuvU/q0SyJfj7X/9Eqa5dA6cc+yUUAKRdYEcqW4lQcsDd1ArfxJNSDYooz9X+UhFeVxKO9e/xDA==}
'@pnpm/exe.darwin-arm64@12.15.0':
resolution: {integrity: sha512-N0ZykiDWCvqSBJvt71j7cSoBR993FqvYZFtmpCtqvW3pguiI+NAgraLPA5OTwu5mV+/d8hYpVcPktJA3xFDLtA==}
cpu: [arm64]
os: [darwin]
'@pnpm/exe.darwin-x64@12.9.0':
resolution: {integrity: sha512-fr4ns4FyMLptdYbWqW3yc/yvbfQP7D1RBCFUJpSPr7tOzd3JxZvl+Tkvg65kEAGU5wXI6vl3eCOofumEj/n3Gw==}
'@pnpm/exe.darwin-x64@12.15.0':
resolution: {integrity: sha512-7Ntr2HlBUxzwWOg7NwDxCbRW/3vXuqKO+hcXm+w3SBi9rrHY53li1wLqWVT7Gjxd+lVEHM1QJZo6WJEGFU8C6A==}
cpu: [x64]
os: [darwin]
'@pnpm/exe.freebsd-x64@12.9.0':
resolution: {integrity: sha512-4+hZPeJzSSw1oOrfUg+v4QylHv6qKhdgcCnKt9ooryE79p1Z9oyozVJ5em+g6ajbvv6jlH+epnht8/s9Cp5M3Q==}
'@pnpm/exe.freebsd-x64@12.15.0':
resolution: {integrity: sha512-btOiyL7fL7W4uQGH0aqFai2TNC3IoKcZ7gNHBVbEFZt2dWrnrD0SufL3iGs3fLlmb4OtuU35uf4Zpr9V9Jh9mA==}
cpu: [x64]
os: [freebsd]
'@pnpm/exe.linux-arm64-musl@12.9.0':
resolution: {integrity: sha512-+mHQSbA6M6W71PyV0IxYu2T43lZA8rAhlw4Gy7EMlyiv8H2GWJAXtUXl2huw7tnsar2AhCRlPn/ZvUv+/mIBkA==}
'@pnpm/exe.linux-arm64-musl@12.15.0':
resolution: {integrity: sha512-pNC38k+O+90FOjbPNSnw0E7apq1PKTmz3fFe1amn+lys/U5kL++uzir8bRiho8ONcyA3d9EU7wdqcY0DKkj+JA==}
cpu: [arm64]
os: [linux]
libc: [musl]
'@pnpm/exe.linux-arm64@12.9.0':
resolution: {integrity: sha512-U1mBoG27+J/HuWYtVZOQrvbiKnTlDsDVzyroKQqHsJaTHTXi0H5Y+fU1GjUyMcNG5r/EXtbhp9iAwQt64uXTxQ==}
'@pnpm/exe.linux-arm64@12.15.0':
resolution: {integrity: sha512-qML/8aCXslh8td/w4U+HJNqUcZ2+m6EfTbWScIzZRmyPsRFN+xB4LP1U/hymxc1iSJiKtG56HJx2fvUErWFIGw==}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@pnpm/exe.linux-ppc64@12.9.0':
resolution: {integrity: sha512-P5bgei3i6wjlKq6s4PNg/0cvik354upY2wW3YGSfweYTABnAZP2zGzgMc0eO5SHTz934Cbya8Z0YFRdw6MfmCg==}
'@pnpm/exe.linux-ppc64@12.15.0':
resolution: {integrity: sha512-tjRDUUl7RCJ6T/6eoNPxOqkwU4Mzi5RtTXmSAxujyz37OTwwsMU7Ps087Zk4gHcUvRSeyF40ZFsew3vtE+nmUA==}
cpu: [ppc64]
os: [linux]
libc: [glibc]
'@pnpm/exe.linux-riscv64@12.9.0':
resolution: {integrity: sha512-oNx2uOo2gVrRckEvz7V+FKeq9HOF0rKNHcCyxRRHSXEXpmP6ZMMgJ+iU/m/zfSGp6bAcC5mvAE270FhAeIeKhA==}
'@pnpm/exe.linux-riscv64@12.15.0':
resolution: {integrity: sha512-bF1uBWEfbwaeryz6lIiaJ8AWD082otZfvzGX5l+6LZRpRwUEpJHUsJrORaYP5/cNMv5ZR2p6TvvcJcQzwtDzmw==}
cpu: [riscv64]
os: [linux]
libc: [glibc]
'@pnpm/exe.linux-s390x@12.9.0':
resolution: {integrity: sha512-OChHS7hOlqdBMtZqjIB1QoZGNfzLPSsvTa2kYanf3qso5Q+KgnROQ+uV4a0wRGC6sdshSA63+Ui8MCylRy6iwA==}
'@pnpm/exe.linux-s390x@12.15.0':
resolution: {integrity: sha512-zKMhIzsexYMToeLmqV5jPsvV/f9vwsJb2kUH2NFYzalbxImeBrlA4kL7GwF8gD4pagV6jYYcJb8RjbZIdjHptg==}
cpu: [s390x]
os: [linux]
libc: [glibc]
'@pnpm/exe.linux-x64-musl@12.9.0':
resolution: {integrity: sha512-ubZPsDMXS+LEnPa7wZD18E+KTpOAZPt+ms/khfIROt+6Cp0A2kayQA8aIsvV7+jGZD0xoknvaGN/P3v9OisZUg==}
'@pnpm/exe.linux-x64-musl@12.15.0':
resolution: {integrity: sha512-A9J0Jg0Rdx+qQU4qXtwyST5tto9IOu1zi4fDk35nbc6DWahggbcKtFvZPKFwL2qgUXGXOX//hXv6z/sp6emO8A==}
cpu: [x64]
os: [linux]
libc: [musl]
'@pnpm/exe.linux-x64@12.9.0':
resolution: {integrity: sha512-ElANYUwQuMfWqMJR4m5L5h9zKjvGKcA8hi2put4J1DMx2smVaNGkGnxkgeIYgMjmF7UFxlZDcL4jItkScgsW4A==}
'@pnpm/exe.linux-x64@12.15.0':
resolution: {integrity: sha512-yc+QlZR+9+nr29J4fRzhMoapgxTBDndq/+peyoq1XUufnQFnfbXUMFudDIKzHi545linGqmOmXfn0NoufNgcOg==}
cpu: [x64]
os: [linux]
libc: [glibc]
'@pnpm/exe.win32-arm64@12.9.0':
resolution: {integrity: sha512-cqnBKZg5e9fFghmYtgJLyZOAsS1EyLeDVJ0qNsjR7hcc+dq1mWRiDo0erqdj2PGoYaVogyF9WejZSJoKvlfXDw==}
'@pnpm/exe.win32-arm64@12.15.0':
resolution: {integrity: sha512-fPXZxuY1VclkOga9bc53qNCXcegfeoBR8+Ue+AospDwKzuGGSHll0oDxkLfkmpjyRqpe7bH5DyQPYp/xSMaIVA==}
cpu: [arm64]
os: [win32]
'@pnpm/exe.win32-x64@12.9.0':
resolution: {integrity: sha512-khqst6QGgHdKs2lEmz0N75qN/EoOcEywNQlRPfBrBrq1SytHra6ro/xViueJkVvDOz9gEO8oYcXTdZeAjErjMg==}
'@pnpm/exe.win32-x64@12.15.0':
resolution: {integrity: sha512-nrd+Tp1We1DGj4DGG5Bea9lZNh9y1PjlLBdEwdInS4D0h0UIDtM7JaGGGDJhNzIwcHASyihWI7HLV+dtG+fhYg==}
cpu: [x64]
os: [win32]
pnpm@12.9.0:
resolution: {integrity: sha512-j2TvoLeSmGypiuVoeRvNdyKAfidMTwwdmFPGIRZJXFhBGduYdioqU0OxaE02G5rib90W1VFmbXY1NG0/roMN3Q==}
engines: {node: '>=18.*'}
pnpm@12.15.0:
resolution: {integrity: sha512-s5UdbW/0qfE9x89WzSjSuOs328ycaOUuHhGRhz6p+CoBcoerULqtxczElPA2xnwOR+sTYIwvo29HcRth6hKOYQ==}
engines: {node: '>=18'}
hasBin: true
snapshots:
'@pnpm/exe.android-arm64@12.9.0':
'@pnpm/exe.android-arm64@12.15.0':
optional: true
'@pnpm/exe.android-x64@12.9.0':
'@pnpm/exe.android-x64@12.15.0':
optional: true
'@pnpm/exe.darwin-arm64@12.9.0':
'@pnpm/exe.darwin-arm64@12.15.0':
optional: true
'@pnpm/exe.darwin-x64@12.9.0':
'@pnpm/exe.darwin-x64@12.15.0':
optional: true
'@pnpm/exe.freebsd-x64@12.9.0':
'@pnpm/exe.freebsd-x64@12.15.0':
optional: true
'@pnpm/exe.linux-arm64-musl@12.9.0':
'@pnpm/exe.linux-arm64-musl@12.15.0':
optional: true
'@pnpm/exe.linux-arm64@12.9.0':
'@pnpm/exe.linux-arm64@12.15.0':
optional: true
'@pnpm/exe.linux-ppc64@12.9.0':
'@pnpm/exe.linux-ppc64@12.15.0':
optional: true
'@pnpm/exe.linux-riscv64@12.9.0':
'@pnpm/exe.linux-riscv64@12.15.0':
optional: true
'@pnpm/exe.linux-s390x@12.9.0':
'@pnpm/exe.linux-s390x@12.15.0':
optional: true
'@pnpm/exe.linux-x64-musl@12.9.0':
'@pnpm/exe.linux-x64-musl@12.15.0':
optional: true
'@pnpm/exe.linux-x64@12.9.0':
'@pnpm/exe.linux-x64@12.15.0':
optional: true
'@pnpm/exe.win32-arm64@12.9.0':
'@pnpm/exe.win32-arm64@12.15.0':
optional: true
'@pnpm/exe.win32-x64@12.9.0':
'@pnpm/exe.win32-x64@12.15.0':
optional: true
pnpm@12.9.0:
pnpm@12.15.0:
optionalDependencies:
'@pnpm/exe.android-arm64': 12.9.0
'@pnpm/exe.android-x64': 12.9.0
'@pnpm/exe.darwin-arm64': 12.9.0
'@pnpm/exe.darwin-x64': 12.9.0
'@pnpm/exe.freebsd-x64': 12.9.0
'@pnpm/exe.linux-arm64': 12.9.0
'@pnpm/exe.linux-arm64-musl': 12.9.0
'@pnpm/exe.linux-ppc64': 12.9.0
'@pnpm/exe.linux-riscv64': 12.9.0
'@pnpm/exe.linux-s390x': 12.9.0
'@pnpm/exe.linux-x64': 12.9.0
'@pnpm/exe.linux-x64-musl': 12.9.0
'@pnpm/exe.win32-arm64': 12.9.0
'@pnpm/exe.win32-x64': 12.9.0
'@pnpm/exe.android-arm64': 12.15.0
'@pnpm/exe.android-x64': 12.15.0
'@pnpm/exe.darwin-arm64': 12.15.0
'@pnpm/exe.darwin-x64': 12.15.0
'@pnpm/exe.freebsd-x64': 12.15.0
'@pnpm/exe.linux-arm64': 12.15.0
'@pnpm/exe.linux-arm64-musl': 12.15.0
'@pnpm/exe.linux-ppc64': 12.15.0
'@pnpm/exe.linux-riscv64': 12.15.0
'@pnpm/exe.linux-s390x': 12.15.0
'@pnpm/exe.linux-x64': 12.15.0
'@pnpm/exe.linux-x64-musl': 12.15.0
'@pnpm/exe.win32-arm64': 12.15.0
'@pnpm/exe.win32-x64': 12.15.0
---
lockfileVersion: '9.0'
+50 -22
View File
@@ -448,6 +448,12 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]]
name = "byteorder-lite"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
[[package]]
name = "bytes"
version = "1.12.1"
@@ -2040,6 +2046,19 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "image"
version = "0.25.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"
dependencies = [
"bytemuck",
"byteorder-lite",
"moxcms",
"num-traits",
"png",
]
[[package]]
name = "indexmap"
version = "1.9.3"
@@ -2511,6 +2530,16 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "moxcms"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"
dependencies = [
"num-traits",
"pxfm",
]
[[package]]
name = "muda"
version = "0.20.0"
@@ -3197,6 +3226,12 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "pxfm"
version = "0.1.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
[[package]]
name = "qrcode"
version = "0.14.1"
@@ -3418,7 +3453,7 @@ dependencies = [
[[package]]
name = "rs-capture"
version = "0.4.0"
version = "0.5.0"
dependencies = [
"pipewire",
"rs-proto",
@@ -3430,17 +3465,17 @@ dependencies = [
[[package]]
name = "rs-codec"
version = "0.4.0"
version = "0.5.0"
dependencies = [
"env-libvpx-sys",
"rs-capture",
"thiserror 2.0.21",
"tracing",
"vpx-encode",
]
[[package]]
name = "rs-diag"
version = "0.4.0"
version = "0.5.0"
dependencies = [
"if-addrs",
"serde",
@@ -3454,7 +3489,7 @@ dependencies = [
[[package]]
name = "rs-platform"
version = "0.4.0"
version = "0.5.0"
dependencies = [
"futures-util",
"if-addrs",
@@ -3467,7 +3502,7 @@ dependencies = [
[[package]]
name = "rs-proto"
version = "0.4.0"
version = "0.5.0"
dependencies = [
"serde",
"serde_json",
@@ -3477,7 +3512,7 @@ dependencies = [
[[package]]
name = "rs-rtc"
version = "0.4.0"
version = "0.5.0"
dependencies = [
"rs-codec",
"str0m",
@@ -3488,9 +3523,9 @@ dependencies = [
[[package]]
name = "rs-session"
version = "0.4.0"
version = "0.5.0"
dependencies = [
"base64 0.22.1",
"base64 0.23.1",
"png",
"rs-capture",
"rs-codec",
@@ -3510,7 +3545,7 @@ dependencies = [
[[package]]
name = "rs-signaling"
version = "0.4.0"
version = "0.5.0"
dependencies = [
"axum",
"axum-server",
@@ -3532,7 +3567,7 @@ dependencies = [
[[package]]
name = "rs-store"
version = "0.4.0"
version = "0.5.0"
dependencies = [
"rs-proto",
"serde",
@@ -3616,11 +3651,13 @@ dependencies = [
[[package]]
name = "rustscreen-desktop"
version = "0.4.0"
version = "0.5.0"
dependencies = [
"libloading 0.8.9",
"rs-diag",
"rs-session",
"rs-store",
"serde",
"tauri",
"tauri-build",
"tracing",
@@ -4385,6 +4422,7 @@ dependencies = [
"gtk",
"heck 0.5.0",
"http",
"image",
"jni",
"libc",
"log",
@@ -5218,16 +5256,6 @@ version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "vpx-encode"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd1f41af42de7667cbdba44e8c38c36e9ede970f1291c32ea57c0ded8eb6f4b6"
dependencies = [
"env-libvpx-sys",
"thiserror 1.0.69",
]
[[package]]
name = "vswhom"
version = "0.1.0"
+22 -10
View File
@@ -1,32 +1,44 @@
[package]
name = "rustscreen-desktop"
description = "Coque desktop de rustscreen: choisir ce qu'on partage, voir qui regarde, couper."
version = "0.4.0"
description = "rustscreen desktop shell: choose what to share, see who is watching, stop."
version = "0.5.0"
edition = "2024"
rust-version = "1.90"
license = "Apache-2.0"
repository = "https://gitea-nubo.hopledge.com/heap/rustscreen"
# 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.
# Outside the main workspace: WebKitGTK and GTK are needed at build time, and
# the host CI does not have them. `nix develop .#desktop` provides them.
# Launching rustscreen opens this desktop application (#84); the command line
# is `rustscreen-cli` (crates/rs-session).
[[bin]]
name = "rustscreen"
path = "src/main.rs"
[workspace]
[features]
# 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.
# The built interface (`dist`) is embedded in the binary. Without this
# feature, Tauri loads `devUrl` (the Vite server, `pnpm dev`): that is the
# development mode, `--no-default-features`. The Tauri CLI makes this choice on
# its own; we do without it, hence the explicit choice.
default = ["custom-protocol"]
custom-protocol = ["tauri/custom-protocol"]
# Capture Wayland réelle (ADR 0009), comme le binaire en ligne de commande.
# Real Wayland capture (ADR 0009), like the command-line binary.
pipewire = ["rs-session/pipewire"]
[dependencies]
rs-diag = { path = "../../../crates/rs-diag" }
rs-session = { path = "../../../crates/rs-session" }
rs-store = { path = "../../../crates/rs-store" }
tauri = { version = "2.12.5", features = [] }
# `tray-icon`: system tray icon (#22); `image-png`: its icons.
tauri = { version = "2.12.5", features = ["tray-icon", "image-png"] }
tracing = "0.1"
serde = { version = "1.0.229", features = ["derive"] }
[target.'cfg(target_os = "linux")'.dependencies]
# Trial load of libayatana-appindicator before creating the icon (#22).
libloading = "0.8.9"
[build-dependencies]
tauri-build = { version = "2.7.4", features = [] }
@@ -1,7 +1,7 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "La fenêtre principale: écouter l'état de l'hôte. Les commandes de l'application sont autorisées par défaut.",
"description": "The main window: listen to the host state. The application commands are allowed by default.",
"windows": ["main"],
"permissions": ["core:default"]
}
+247 -79
View File
@@ -1,157 +1,325 @@
//! Coque desktop de rustscreen (#15): l'écran que voit l'hôte.
//! rustscreen desktop shell (#15): the screen the host sees.
//!
//! 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.
//! It does nothing but relay: each command calls [`rs_session::Host`], and
//! each state change goes to the interface through the `state` event, the
//! complete state every time. The interface therefore keeps no share state of
//! its own, and cannot show a button that lies.
mod tray;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use rs_session::{
Application, Config, Etat, Hote, InterfaceProposee, SourceChoisie, SourceProposee, Surcharges,
Config, Host, HostState, InterfaceOption, Overrides, Phase, SettingsOutcome, SourceChoice,
SourceOption,
};
use rs_store::{Refus, Reglages};
use tauri::{Emitter, Manager, RunEvent, State};
use rs_store::{CloseAction, Rejection, Settings};
use tauri::{Emitter, Manager, RunEvent, State, WindowEvent};
const FILTRE: &str = "rustscreen_desktop=info,rs_session=info,rs_signaling=info,rs_rtc=info,\
/// The last started source, so that the system tray menu can restart a share
/// without opening the window.
#[derive(Default)]
struct LastSource(Mutex<Option<SourceChoice>>);
/// The system tray icon, if this desktop has one: without it, hiding the
/// window would make the application impossible to find.
struct MaybeTray(Option<Arc<tray::Tray<tauri::Wry>>>);
impl MaybeTray {
fn present(&self) -> bool {
self.0.is_some()
}
}
fn last_source_known(app: &tauri::AppHandle) -> bool {
app.state::<LastSource>()
.0
.lock()
.unwrap_or_else(|e| e.into_inner())
.is_some()
}
// The binary is `rustscreen` (#84): its log target follows.
const FILTER: &str = "rustscreen=info,rs_session=info,rs_signaling=info,rs_rtc=info,\
rs_capture=info,rs_codec=info,rs_platform=info,rs_diag=info,\
rs_store=info,str0m=warn";
#[tauri::command]
fn etat(hote: State<'_, Hote>) -> Etat {
hote.etat()
fn state(host: State<'_, Host>) -> HostState {
host.state()
}
#[tauri::command]
async fn sources(hote: State<'_, Hote>) -> Result<Vec<SourceProposee>, ()> {
Ok(hote.sources().await)
async fn sources(host: State<'_, Host>) -> Result<Vec<SourceOption>, ()> {
Ok(host.sources().await)
}
#[tauri::command]
async fn demarrer(hote: State<'_, Hote>, choix: SourceChoisie) -> Result<(), String> {
hote.demarrer(choix).await
async fn start(
host: State<'_, Host>,
last: State<'_, LastSource>,
choice: SourceChoice,
) -> Result<(), String> {
*last.0.lock().unwrap_or_else(|e| e.into_inner()) = Some(choice.clone());
host.start(choice).await
}
#[tauri::command]
async fn arreter(hote: State<'_, Hote>) -> Result<(), ()> {
hote.arreter().await;
async fn stop(host: State<'_, Host>) -> Result<(), ()> {
host.stop().await;
Ok(())
}
#[tauri::command]
fn deconnecter(hote: State<'_, Hote>, connexion: u64) -> bool {
hote.deconnecter(connexion)
fn disconnect(host: State<'_, Host>, connection: u64) -> bool {
host.disconnect(connection)
}
#[tauri::command]
fn reglages(hote: State<'_, Hote>) -> Reglages {
hote.reglages()
fn regenerate_access(host: State<'_, Host>) -> bool {
host.regenerate_access()
}
/// The texts of the system tray menu, in the language of the interface.
#[tauri::command]
fn translate_tray(
app: tauri::AppHandle,
host: State<'_, Host>,
tray: State<'_, MaybeTray>,
texts: tray::TrayTexts,
) {
if let Some(tray) = &tray.0 {
tray.translate(texts);
tray.follow(&host.state(), last_source_known(&app));
}
}
#[tauri::command]
async fn modifier_reglages(
hote: State<'_, Hote>,
reglages: Reglages,
) -> Result<Application, Vec<Refus>> {
hote.modifier_reglages(reglages).await
fn settings(host: State<'_, Host>) -> Settings {
host.settings()
}
#[tauri::command]
fn interfaces(hote: State<'_, Hote>) -> Vec<InterfaceProposee> {
hote.interfaces()
async fn update_settings(
host: State<'_, Host>,
settings: Settings,
) -> Result<SettingsOutcome, Vec<Rejection>> {
host.update_settings(settings).await
}
/// É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 exporter_diagnostics(hote: State<'_, Hote>) -> Result<String, String> {
let hote = hote.inner().clone();
fn interfaces(host: State<'_, Host>) -> Vec<InterfaceOption> {
host.interfaces()
}
/// Writes the diagnostics archive to the download folder and returns its
/// path: the user sends it themselves (ADR 0008).
#[tauri::command]
async fn export_diagnostics(host: State<'_, Host>) -> Result<String, String> {
let host = host.inner().clone();
tauri::async_runtime::spawn_blocking(move || {
let (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())
let (name, bytes) = host.diagnostics()?;
let dir = download_dir();
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
let path = dir.join(name);
std::fs::write(&path, bytes).map_err(|e| e.to_string())?;
tracing::info!(event = "diagnostics_exported", "archive written");
Ok(path.display().to_string())
})
.await
.map_err(|e| e.to_string())?
}
/// `XDG_DOWNLOAD_DIR` de `user-dirs.dirs` quand il existe, sinon le dossier
/// personnel.
fn dossier_telechargements() -> PathBuf {
let maison = std::env::var_os("HOME")
/// `XDG_DOWNLOAD_DIR` from `user-dirs.dirs` when it exists, otherwise the home
/// folder.
fn download_dir() -> PathBuf {
let home = std::env::var_os("HOME")
.map(PathBuf::from)
.unwrap_or_default();
let config = std::env::var_os("XDG_CONFIG_HOME")
.map(PathBuf::from)
.unwrap_or_else(|| maison.join(".config"));
.unwrap_or_else(|| home.join(".config"));
std::fs::read_to_string(config.join("user-dirs.dirs"))
.ok()
.and_then(|texte| {
texte.lines().find_map(|ligne| {
let valeur = ligne.strip_prefix("XDG_DOWNLOAD_DIR=")?.trim_matches('"');
.and_then(|text| {
text.lines().find_map(|line| {
let value = line.strip_prefix("XDG_DOWNLOAD_DIR=")?.trim_matches('"');
Some(PathBuf::from(
valeur.replace("$HOME", &maison.display().to_string()),
value.replace("$HOME", &home.display().to_string()),
))
})
})
.unwrap_or(maison)
.unwrap_or(home)
}
/// A click in the system tray menu.
fn on_tray_click(app: &tauri::AppHandle, id: &str) {
let host = app.state::<Host>().inner().clone();
match id {
tray::OPEN => tray::show(app),
tray::START => {
let last = app
.state::<LastSource>()
.0
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone();
match last {
Some(choice) => {
tauri::async_runtime::spawn(async move {
// The failure shows in the window, through the state.
let _ = host.start(choice).await;
});
}
None => tray::show(app),
}
}
tray::STOP => {
tauri::async_runtime::spawn(async move { host.stop().await });
}
tray::QUIT => request_quit(app),
_ => {}
}
}
/// Autostart argument: the application starts hidden in the system tray
/// (#32).
const AUTOSTARTED: &str = "--autostarted";
/// The former spelling, still written in the `.desktop` files of existing
/// installations: it keeps being accepted.
const AUTOSTARTED_LEGACY: &str = "--au-demarrage";
/// Quit, or ask first if a share is running (#43): a reflex gesture must not
/// cut a presentation short. The window comes back and asks the question; the
/// `quit` command concludes.
fn request_quit(app: &tauri::AppHandle) {
let host = app.state::<Host>();
if host.state().phase == Phase::Stopped || !host.settings().confirm_quit {
app.exit(0);
return;
}
tray::show(app);
if let Err(error) = app.emit("confirm-quit", ()) {
tracing::warn!(%error, "quit confirmation not requested: quitting");
app.exit(0);
}
}
/// Answer to the confirmation: quit, and stop asking if so wished.
#[tauri::command]
async fn quit(
app: tauri::AppHandle,
host: State<'_, Host>,
dont_ask_again: bool,
) -> Result<(), Vec<Rejection>> {
if dont_ask_again {
let mut settings = host.settings();
settings.confirm_quit = false;
host.update_settings(settings).await?;
}
app.exit(0);
Ok(())
}
fn main() {
let journal = rs_diag::initialiser(rs_diag::dossier_journaux().as_deref(), FILTRE);
let executable = std::env::current_exe().ok();
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());
let autostarted = std::env::args().any(|a| a == AUTOSTARTED || a == AUTOSTARTED_LEGACY);
let hote = tauri::async_runtime::block_on(Hote::nouveau(Config {
let host = tauri::async_runtime::block_on(Host::new(Config {
version: env!("CARGO_PKG_VERSION").into(),
viewer_dir: std::env::var_os("RUSTSCREEN_VIEWER").map(PathBuf::from),
tls: false,
magasin: rs_store::Magasin::par_defaut(),
surcharges: Surcharges::default(),
journaux: journal.dossier.clone(),
demarrage_auto: executable.map(|exe| (exe, String::new())),
store: rs_store::Store::user_default(),
overrides: Overrides::default(),
log_dir: log.dir.clone(),
autostart: executable.map(|exe| (exe, AUTOSTARTED.to_string())),
}));
let application = tauri::Builder::default()
.manage(hote.clone())
.manage(host.clone())
.manage(LastSource::default())
.invoke_handler(tauri::generate_handler![
etat,
state,
sources,
demarrer,
arreter,
deconnecter,
reglages,
modifier_reglages,
start,
stop,
disconnect,
regenerate_access,
translate_tray,
quit,
settings,
update_settings,
interfaces,
exporter_diagnostics,
export_diagnostics,
])
.setup(move |app| {
// L'état part vers l'interface à chaque changement, complet.
let poignee = app.handle().clone();
let mut abonne = hote.abonner();
let tray = tray::Tray::create(app.handle(), on_tray_click).map(Arc::new);
app.manage(MaybeTray(tray.clone()));
// The window is created hidden: at session start, it stays so if
// the system tray exists to find it again; otherwise it is shown,
// an invisible application would be lost.
if !(autostarted && tray.is_some()) {
tray::show(app.handle());
}
// The state goes to the interface and to the icon on each change,
// complete: the icon follows the real state at the same moment as
// the window.
let handle = app.handle().clone();
let mut subscriber = host.subscribe();
if let Some(tray) = &tray {
tray.follow(&subscriber.borrow(), false);
}
tauri::async_runtime::spawn(async move {
while abonne.changed().await.is_ok() {
let etat = abonne.borrow_and_update().clone();
if let Err(erreur) = poignee.emit("etat", etat) {
tracing::warn!(%erreur, "état non transmis à l'interface");
while subscriber.changed().await.is_ok() {
let state = subscriber.borrow_and_update().clone();
if let Some(tray) = &tray {
tray.follow(&state, last_source_known(&handle));
}
if let Err(error) = handle.emit("state", state) {
tracing::warn!(%error, "state not sent to the interface");
}
}
});
Ok(())
})
.on_window_event(|window, event| {
if let WindowEvent::CloseRequested { api, .. } = event {
let app = window.app_handle();
let host = app.state::<Host>();
if host.settings().close_action == CloseAction::Quit {
// Closing means quitting: same confirmation as the menu.
api.prevent_close();
request_quit(app);
return;
}
// Closing does not cut a share (#22): the window hides in the
// system tray. Without a tray, it minimizes during a share,
// and closes the application otherwise.
if app.state::<MaybeTray>().present() {
api.prevent_close();
let _ = window.hide();
} else if host.state().phase != Phase::Stopped {
api.prevent_close();
let _ = window.minimize();
}
}
})
.build(tauri::generate_context!())
.expect("application Tauri");
.expect("Tauri application");
application.run(move |app, evenement| {
// Fermer la fenêtre 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());
application.run(move |app, event| {
// Quitting stops the share cleanly: portal session closed, sleep
// released, viewers told.
if let RunEvent::Exit = event {
let host = app.state::<Host>().inner().clone();
tauri::async_runtime::block_on(host.stop());
}
});
drop(journal);
drop(log);
}
+302
View File
@@ -0,0 +1,302 @@
//! System tray icon and session menu (#22).
//!
//! The icon tells the real state: it follows the same `state` as the window,
//! at the same moment, so in well under a second. The menu can start (the last
//! chosen source), stop, open the window and quit, without the window being
//! open.
//!
//! On Linux, the icon goes through StatusNotifierItem (libayatana-appindicator,
//! loaded at run time). GNOME without the AppIndicator extension shows nothing:
//! [`available`] detects it, and closing the window then falls back to a plain
//! minimize, so as never to hide a share with no way to find it again.
//!
//! The texts come from the interface (`translate_tray`), in its language
//! (#21): translations live in `locales/`, not here. The English below (the fallback language) only
//! serves before the first update.
use std::sync::Mutex;
use rs_session::{HostState, Phase};
use serde::Deserialize;
use tauri::image::Image;
use tauri::menu::{Menu, MenuItem, PredefinedMenuItem};
use tauri::tray::{MouseButton, MouseButtonState, TrayIcon, TrayIconBuilder, TrayIconEvent};
use tauri::{AppHandle, Manager, Runtime};
const ICON: &[u8] = include_bytes!("../icons/icon.png");
/// What the menu offers; the identifier comes back in the click event.
pub const OPEN: &str = "open";
pub const START: &str = "start";
pub const STOP: &str = "stop";
pub const QUIT: &str = "quit";
/// The forms of the live status: Rust does not know the plural rules of each
/// language, the interface gives it those for 0, for 1 and for the rest.
#[derive(Debug, Clone, Deserialize)]
pub struct PluralForms {
pub zero: String,
pub one: String,
/// With `{count}` to replace.
pub other: String,
}
/// The menu texts, translated by the interface.
#[derive(Debug, Clone, Deserialize)]
pub struct TrayTexts {
pub none: String,
pub starting: String,
pub live: PluralForms,
pub open: String,
pub start: String,
pub resume: String,
pub stop: String,
pub quit: String,
}
impl Default for TrayTexts {
fn default() -> Self {
Self {
none: "Not sharing".into(),
starting: "Starting to share…".into(),
live: PluralForms {
zero: "Live, nobody is watching".into(),
one: "Live, 1 viewer".into(),
other: "Live, {count} viewers".into(),
},
open: "Open rustscreen".into(),
start: "Start sharing…".into(),
resume: "Resume the last share".into(),
stop: "Stop sharing".into(),
quit: "Quit".into(),
}
}
}
impl TrayTexts {
fn status(&self, state: &HostState) -> String {
match state.phase {
Phase::Stopped => self.none.clone(),
Phase::Starting => self.starting.clone(),
Phase::Live => match state.share.as_ref().map_or(0, |s| s.devices.len()) {
0 => self.live.zero.clone(),
1 => self.live.one.clone(),
n => self.live.other.replace("{count}", &n.to_string()),
},
}
}
}
pub struct Tray<R: Runtime> {
icon: TrayIcon<R>,
status: MenuItem<R>,
open: MenuItem<R>,
start: MenuItem<R>,
stop: MenuItem<R>,
quit: MenuItem<R>,
idle: Image<'static>,
live: Image<'static>,
texts: Mutex<TrayTexts>,
}
impl<R: Runtime> Tray<R> {
/// Creates the icon and its menu. `None` when this desktop has no system
/// tray: the application then lives in its window only.
pub fn create(
app: &AppHandle<R>,
on_click: impl Fn(&AppHandle<R>, &str) + Send + Sync + 'static,
) -> Option<Self> {
if !available() {
tracing::info!("no system tray on this desktop: window only");
return None;
}
let build = || -> tauri::Result<Self> {
let idle = Image::from_bytes(ICON)?.to_owned();
let live = with_dot(&idle);
let texts = TrayTexts::default();
let status = MenuItem::with_id(app, "status", &texts.none, false, None::<&str>)?;
let open = MenuItem::with_id(app, OPEN, &texts.open, true, None::<&str>)?;
let start = MenuItem::with_id(app, START, &texts.start, true, None::<&str>)?;
let stop = MenuItem::with_id(app, STOP, &texts.stop, false, None::<&str>)?;
let quit = MenuItem::with_id(app, QUIT, &texts.quit, true, None::<&str>)?;
let menu = Menu::with_items(
app,
&[
&status,
&PredefinedMenuItem::separator(app)?,
&open,
&start,
&stop,
&PredefinedMenuItem::separator(app)?,
&quit,
],
)?;
let icon = TrayIconBuilder::with_id("rustscreen")
.icon(idle.clone())
.tooltip(format!("rustscreen: {}", texts.none))
.menu(&menu)
.show_menu_on_left_click(false)
.on_menu_event(move |app, event| on_click(app, event.id().as_ref()))
.on_tray_icon_event(|icon, event| {
// Windows and macOS: a left click reopens the window. On
// Linux, StatusNotifierItem only sends the menu.
if let TrayIconEvent::Click {
button: MouseButton::Left,
button_state: MouseButtonState::Up,
..
} = event
{
show(icon.app_handle());
}
})
.build(app)?;
Ok(Self {
icon,
status,
open,
start,
stop,
quit,
idle,
live,
texts: Mutex::new(texts),
})
};
match build() {
Ok(tray) => Some(tray),
Err(error) => {
tracing::warn!(%error, "system tray icon impossible");
None
}
}
}
/// Changes the menu language; the caller redraws with [`Tray::follow`].
pub fn translate(&self, texts: TrayTexts) {
let result = (|| -> tauri::Result<()> {
self.open.set_text(&texts.open)?;
self.stop.set_text(&texts.stop)?;
self.quit.set_text(&texts.quit)?;
Ok(())
})();
if let Err(error) = result {
tracing::warn!(%error, "system tray menu not translated");
}
*self.texts.lock().unwrap_or_else(|e| e.into_inner()) = texts;
}
/// Makes the icon, the tooltip and the menu match the state.
pub fn follow(&self, state: &HostState, last_source: bool) {
let texts = self.texts.lock().unwrap_or_else(|e| e.into_inner()).clone();
let text = texts.status(state);
let icon = if state.phase == Phase::Live {
&self.live
} else {
&self.idle
};
let result = (|| -> tauri::Result<()> {
self.icon.set_icon(Some(icon.clone()))?;
self.icon.set_tooltip(Some(format!("rustscreen: {text}")))?;
self.status.set_text(&text)?;
// Starting from the menu restarts the last source; without one,
// the menu opens the window to pick one.
self.start.set_text(if last_source {
&texts.resume
} else {
&texts.start
})?;
self.start.set_enabled(state.phase == Phase::Stopped)?;
self.stop.set_enabled(state.phase != Phase::Stopped)?;
Ok(())
})();
if let Err(error) = result {
tracing::warn!(%error, "system tray not updated");
}
}
}
/// Reopens the main window, hidden or minimized.
pub fn show<R: Runtime>(app: &AppHandle<R>) {
if let Some(window) = app.get_webview_window("main") {
let _ = window.unminimize();
let _ = window.show();
let _ = window.set_focus();
}
}
/// Is there a system tray? On Linux, it takes a StatusNotifierItem host on the
/// session bus and the library that talks to it.
#[cfg(target_os = "linux")]
fn available() -> bool {
let library = ["libayatana-appindicator3.so.1", "libappindicator3.so.1"]
.iter()
.any(|name| library_loads(name));
library && status_notifier_host()
}
#[cfg(not(target_os = "linux"))]
fn available() -> bool {
true
}
/// Can the dynamic loader open this library? tray-icon panics otherwise,
/// instead of returning an error. Looking for the file is not enough: a binary
/// built by Nix does not read the system cache, the same loading as its own
/// must be tried.
#[cfg(target_os = "linux")]
fn library_loads(name: &str) -> bool {
// SAFETY: this is the library tray-icon will load anyway right after,
// through the same search path; its constructors (GObject type
// registration) are meant to run once loaded, and keeping it loaded avoids
// a second pass.
match unsafe { libloading::Library::new(name) } {
Ok(library) => {
std::mem::forget(library);
true
}
Err(_) => false,
}
}
/// Does `org.kde.StatusNotifierWatcher` have an owner on the session bus? It
/// is the one that shows the icons (KDE, Ubuntu, GNOME with the AppIndicator
/// extension).
#[cfg(target_os = "linux")]
fn status_notifier_host() -> bool {
std::process::Command::new("busctl")
.args([
"--user",
"call",
"org.freedesktop.DBus",
"/org/freedesktop/DBus",
"org.freedesktop.DBus",
"NameHasOwner",
"s",
"org.kde.StatusNotifierWatcher",
])
.output()
.is_ok_and(|output| String::from_utf8_lossy(&output.stdout).trim() == "b true")
}
/// The "live" icon: the same one, with a red dot at the bottom right, readable
/// even at 16 pixels.
fn with_dot(base: &Image<'_>) -> Image<'static> {
let (w, h) = (base.width(), base.height());
let mut rgba = base.rgba().to_vec();
let radius = w.min(h) as f32 * 0.22;
let (cx, cy) = (w as f32 - radius - 1.0, h as f32 - radius - 1.0);
for y in 0..h {
for x in 0..w {
let d = ((x as f32 + 0.5 - cx).powi(2) + (y as f32 + 0.5 - cy).powi(2)).sqrt();
let i = ((y * w + x) * 4) as usize;
if d <= radius {
rgba[i..i + 4].copy_from_slice(&[0xdc, 0x26, 0x26, 0xff]);
} else if d <= radius + w as f32 * 0.03 {
// White rim: the dot stands out on a dark bar as on a light
// one.
rgba[i..i + 4].copy_from_slice(&[0xff, 0xff, 0xff, 0xff]);
}
}
}
Image::new_owned(rgba, w, h)
}
+3 -2
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "rustscreen",
"version": "0.4.0",
"version": "0.5.0",
"identifier": "local.rustscreen.desktop",
"build": {
"frontendDist": "../dist",
@@ -15,7 +15,8 @@
"width": 1100,
"height": 760,
"minWidth": 800,
"minHeight": 560
"minHeight": 560,
"visible": false
}
],
"security": {
+162 -110
View File
@@ -1,190 +1,242 @@
import { useCallback, useEffect, useState } from 'react';
import type { Etat } from './bindings/Etat';
import type { SourceChoisie } from './bindings/SourceChoisie';
import type { SourceProposee } from './bindings/SourceProposee';
import type { HostState } from './bindings/HostState';
import type { SourceChoice } from './bindings/SourceChoice';
import type { SourceOption } from './bindings/SourceOption';
import type { Theme } from './bindings/Theme';
import { ChoixSource } from './components/ChoixSource';
import { PanneauPartage } from './components/PanneauPartage';
import { Reglages } from './components/Reglages';
import type { Hote } from './lib/hote';
import { actions, cle, statut } from './lib/vue';
import { textes } from './strings';
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 } from './lib/host';
import { actions, key, status, trayTexts } from './lib/view';
export function App({ hote }: { hote: Hote }) {
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');
// L'état vient de l'hôte, toujours complet: on s'abonne avant de lire, pour
// ne pas manquer un changement entre les deux.
/**
* The language comes from the host settings, or from the desktop. Changing it
* retranslates the interface and the system tray menu at the next render
* (#21).
*/
export function App({ host }: { host: Host }) {
const [setting, setSetting] = useState<string | null>(null);
useEffect(() => {
let arreter: (() => void) | undefined;
let fini = false;
hote.ecouter(setEtat).then((stop) => {
if (fini) stop();
else arreter = stop;
host.settings().then((s) => setSetting(s.language));
}, [host]);
const language = effectiveLanguage(setting, navigator.languages ?? [navigator.language]);
return (
<I18nProvider language={language}>
<Shell host={host} onLanguage={setSetting} />
</I18nProvider>
);
}
function Shell({ host, onLanguage }: { host: Host; onLanguage: (code: string | null) => void }) {
const { t, language } = useI18n();
const [state, setState] = useState<HostState | null>(null);
const [sources, setSources] = useState<SourceOption[] | null>(null);
const [selection, setSelection] = useState<SourceChoice | null>(null);
const [sending, setSending] = useState(false);
const [settingsOpen, setSettingsOpen] = useState(false);
const [confirmQuit, setConfirmQuit] = useState(false);
const [theme, setTheme] = useState<Theme>('system');
// The state comes from the host, always complete: subscribe before reading,
// so as not to miss a change in between.
useEffect(() => {
let unlisten: (() => void) | undefined;
let done = false;
host.listen(setState).then((stop) => {
if (done) stop();
else unlisten = stop;
});
hote.etat().then(setEtat);
hote.reglages().then((r) => setTheme(r.theme));
host.state().then(setState);
let unlistenQuit: (() => void) | undefined;
host
.listenQuit(() => setConfirmQuit(true))
.then((stop) => {
if (done) stop();
else unlistenQuit = stop;
});
host.settings().then((s) => setTheme(s.theme));
return () => {
fini = true;
arreter?.();
done = true;
unlisten?.();
unlistenQuit?.();
};
}, [hote]);
}, [host]);
useEffect(() => {
document.documentElement.dataset.theme = theme;
}, [theme]);
const actualiser = useCallback(() => {
// The system tray menu is drawn by Rust: it receives its texts in the
// language of the interface.
useEffect(() => {
document.documentElement.lang = language;
host.translateTray(trayTexts(t)).catch(() => undefined);
}, [host, t, language]);
const refresh = useCallback(() => {
setSources(null);
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.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]);
}, [host]);
const phase = etat?.phase;
const phase = state?.phase;
useEffect(() => {
if (phase === 'arrete') {
actualiser();
if (phase === 'stopped') {
refresh();
}
}, [phase, actualiser]);
}, [phase, refresh]);
if (!etat) {
return <div className='chargement'>{textes.titre}</div>;
if (!state) {
return <div className='loading'>{t('title')}</div>;
}
const boutons = actions(etat, selection, envoi);
const etiquette = statut(etat);
const envoyer = async (commande: () => Promise<unknown>) => {
setEnvoi(true);
const buttons = actions(state, selection, sending);
const badge = status(state, t);
const send = async (command: () => Promise<unknown>) => {
setSending(true);
try {
await commande();
await command();
} catch {
// L'erreur arrive aussi dans l'état (`erreur`), qui l'affiche.
// The error also arrives in the state (`error`), which shows it.
} finally {
setEnvoi(false);
setSending(false);
}
};
const portail = selection?.type === 'portail';
const portal = selection?.type === 'portal';
return (
<div className='app'>
<header className='entete'>
<h1>{textes.titre}</h1>
<span className={`pastille ${etiquette.ton}`} role='status'>
{etiquette.texte}
<header className='header'>
<h1>{t('title')}</h1>
<span className={`badge ${badge.tone}`} role='status'>
{badge.text}
</span>
{etat.phase === 'en_cours' && (
<span className='veille' title={etat.veille_inhibee.join(', ')}>
{etat.veille_inhibee.length > 0 ? textes.veille : textes.veilleAbsente}
{state.phase === 'live' && (
<span className='sleep' title={state.sleep_inhibited.join(', ')}>
{state.sleep_inhibited.length > 0 ? t('sleepInhibited') : t('sleepNotInhibited')}
</span>
)}
<span className='espace' />
<button type='button' className='bouton discret' onClick={() => setReglagesOuverts(true)}>
{textes.reglages}
<span className='spacer' />
<button type='button' className='button muted' onClick={() => setSettingsOpen(true)}>
{t('settings')}
</button>
</header>
<main className='contenu'>
<Bandeaux etat={etat} />
<main className='content'>
<Banners state={state} />
{etat.phase === 'en_cours' && etat.partage ? (
<PanneauPartage
partage={etat.partage}
onDeconnecter={(connexion) => envoyer(() => hote.deconnecter(connexion))}
{state.phase === 'live' && state.share ? (
<SharePanel
share={state.share}
onDisconnect={(connection) => send(() => host.disconnect(connection))}
onNewCode={() => send(() => host.regenerateAccess())}
/>
) : (
<ChoixSource
<SourcePicker
sources={sources}
selection={selection}
actif={boutons.choisir}
onChoisir={setSelection}
onActualiser={actualiser}
enabled={buttons.pick}
onPick={setSelection}
onRefresh={refresh}
/>
)}
</main>
<footer className='barre'>
{etat.phase === 'demarrage' && (
<p className='attente' role='status'>
{portail ? textes.attenteBureau : textes.attente}
<footer className='action-bar'>
{state.phase === 'starting' && (
<p className='waiting' role='status'>
{portal ? t('waitingDesktop') : t('waiting')}
</p>
)}
<span className='espace' />
{boutons.demarrer.visible && (
<span className='spacer' />
{buttons.start.visible && (
<button
type='button'
className='bouton principal'
disabled={!boutons.demarrer.actif}
onClick={() => selection && envoyer(() => hote.demarrer(selection))}
className='button primary'
disabled={!buttons.start.enabled}
onClick={() => selection && send(() => host.start(selection))}
>
{textes.demarrer}
{t('start')}
</button>
)}
{boutons.annuler.visible && (
{buttons.cancel.visible && (
<button
type='button'
className='bouton'
disabled={!boutons.annuler.actif}
onClick={() => hote.arreter()}
className='button'
disabled={!buttons.cancel.enabled}
onClick={() => host.stop()}
>
{textes.annuler}
{t('cancel')}
</button>
)}
{boutons.arreter.visible && (
{buttons.stop.visible && (
<button
type='button'
className='bouton danger'
disabled={!boutons.arreter.actif}
onClick={() => envoyer(() => hote.arreter())}
className='button danger'
disabled={!buttons.stop.enabled}
onClick={() => send(() => host.stop())}
>
{textes.arreter}
{t('stop')}
</button>
)}
</footer>
{reglagesOuverts && (
<Reglages
hote={hote}
demarrageAuto={etat.capacites.demarrage_auto}
onFermer={() => setReglagesOuverts(false)}
onEnregistre={(r) => setTheme(r.theme)}
{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);
}}
/>
)}
</div>
);
}
function Bandeaux({ etat }: { etat: Etat }) {
function Banners({ state }: { state: HostState }) {
const { t } = useI18n();
return (
<>
{etat.erreur && etat.phase === 'arrete' && (
<div className='bandeau erreur' role='alert'>
<strong>{textes.erreurDemarrage}</strong> {etat.erreur}
{state.error && state.phase === 'stopped' && (
<div className='banner error' role='alert'>
<strong>{t('startFailed')}</strong> {state.error}
</div>
)}
{etat.arret && etat.phase === 'arrete' && (
<div className='bandeau erreur' role='alert'>
<strong>{textes.arretBureau}</strong> {etat.arret.raison}
{state.stop && state.phase === 'stopped' && (
<div className='banner error' role='alert'>
<strong>{t('stoppedByDesktop')}</strong> {state.stop.reason}
</div>
)}
{etat.reglages_recuperes && <div className='bandeau alerte'>{etat.reglages_recuperes}</div>}
{etat.avertissements.map((a) => (
<div key={a} className='bandeau alerte' role='alert'>
{a}
{state.settings_recovered && <div className='banner warning'>{state.settings_recovered}</div>}
{state.warnings.map((w) => (
<div key={w} className='banner warning' role='alert'>
{w}
</div>
))}
{etat.reglages_en_attente.length > 0 && (
<div className='bandeau info'>
<strong>{textes.enAttente}</strong> {etat.reglages_en_attente.join('; ')}
{state.pending_settings.length > 0 && (
<div className='banner info'>
<strong>{t('pendingSettings')}</strong> {state.pending_settings.join('; ')}
</div>
)}
</>
@@ -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 { 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
@@ -1,14 +0,0 @@
// 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
@@ -1,14 +0,0 @@
// 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
@@ -1,11 +0,0 @@
// 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
@@ -0,0 +1,15 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type Capabilities = {
/**
* `wayland`, `x11` or `none`.
*/
session: string, desktop: string, portal: boolean, virtual_display: boolean,
/**
* The binary can consume a PipeWire stream (`pipewire` feature).
*/
pipewire: boolean,
/**
* Autostart can be set from this application.
*/
autostart: boolean, };
-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 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, };
@@ -1,6 +1,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* Langue de l'interface. Le français seul est traduit pour l'instant (#21).
* What closing the desktop application window does (#22).
*/
export type Langue = "fr" | "en";
export type CloseAction = "tray" | "quit";
+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.
/**
* Video codec of the shares (#67). VP9 keeps the same quality at a lower
* bitrate, but costs 1.6x the CPU of VP8 (`docs/perf.md`).
*/
export type Codec = "vp8" | "vp9";
-36
View File
@@ -1,36 +0,0 @@
// 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, };
+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 { Capabilities } from "./Capabilities";
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, to display as is.
*/
error: string | null, stop: Stop | null,
/**
* What still works but deserves to be known (interface down, address
* changed).
*/
warnings: Array<string>,
/**
* 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<string>,
/**
* The settings file was unusable at startup: what was done about it.
*/
settings_recovered: string | 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.
/**
* Une interface réseau proposée dans les réglages.
* A network interface offered in the settings.
*/
export type InterfaceProposee = { nom: string, adresses: Array<string>, active: boolean, };
export type InterfaceOption = { name: string, addresses: Array<string>, active: 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.
/**
* 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" };
-28
View File
@@ -1,28 +0,0 @@
// 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,
/**
* 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.
/**
* Où en est le partage.
* Where the share stands.
*/
export type Phase = "arrete" | "demarrage" | "en_cours";
export type Phase = "stopped" | "starting" | "live";
-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.
/**
* 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, };
-34
View File
@@ -1,34 +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 { AppareilConfiance } from "./AppareilConfiance";
import type { Langue } from "./Langue";
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, langue: Langue,
/**
* Spectateurs simultanés.
*/
limite: number,
/**
* Qualité proposée au démarrage d'un partage.
*/
qualite: QualityPreset,
/**
* Lancer l'hôte à l'ouverture de session (#32).
*/
demarrage_auto: boolean, appareils_confiance: Array<AppareilConfiance>, };
+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.
/**
* 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: string, };
+53
View File
@@ -0,0 +1,53 @@
// 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 { 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,
/**
* 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,
/**
* 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>, };
@@ -0,0 +1,14 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* What a settings change produces.
*/
export type SettingsOutcome = {
/**
* Fields applied right away.
*/
immediate: Array<string>,
/**
* Fields waiting for the next share, with the reason.
*/
next_share: Array<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 { 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>, limit: number, started_ms: number, };
+16
View File
@@ -0,0 +1,16 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { SourceKind } from "../../../viewer/src/proto/SourceKind";
import type { Label } from "./Label";
/**
* The source being shared.
*/
export type SharedSource = { kind: SourceKind, name: string, label: Label,
/**
* `portal`, `x11`, `synthetic` or `ivf`.
*/
backend: string,
/**
* Current encoded size: it follows a resolution change.
*/
width: number, height: number, };
+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.
/**
* 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": "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, };
@@ -1,11 +0,0 @@
// 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,
/**
* Taille d'un écran virtuel. Ignorée pour un écran existant.
*/
taille: [number, number] | null, } | { "type": "mire", chemin: string, };
+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.
/**
* 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
@@ -0,0 +1,35 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { SourceKind } from "../../../viewer/src/proto/SourceKind";
import type { Label } from "./Label";
import type { SourceChoice } from "./SourceChoice";
import type { SourceNote } from "./SourceNote";
/**
* A source offered in the list.
*/
export type SourceOption = { choice: SourceChoice, kind: SourceKind,
/**
* English name, for the command line. A window title may be in it: it
* stays in the local interface, never in the log (ADR 0008).
*/
name: string,
/**
* The name to display, which the interface translates.
*/
label: Label, width: number, height: number,
/**
* Thumbnail as a `data:image/png` URL, when the platform allows taking
* one without consent (X11). Never under Wayland: the portal shows
* nothing before the user agrees.
*/
thumbnail: string | null,
/**
* What to know before choosing ("the desktop will ask which one").
*/
note: SourceNote | null,
/**
* False for a source that is listed but not shareable right now
* (minimized window, desktop that cannot share a window): the note says
* why, before starting and not after (#17).
*/
available: boolean, };
@@ -1,15 +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";
/**
* La source en cours de partage.
*/
export type SourcePartagee = { genre: SourceKind, nom: string,
/**
* `portail`, `x11`, `synthetique` ou `ivf`.
*/
chemin: string,
/**
* Taille encodée courante: elle suit un changement de résolution.
*/
largeur: number, hauteur: number, };
@@ -1,23 +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 { SourceChoisie } from "./SourceChoisie";
/**
* Une source proposée dans la liste.
*/
export type SourceProposee = { choix: SourceChoisie, genre: SourceKind,
/**
* Nom affiché. Un titre de fenêtre peut s'y trouver: il reste dans
* l'interface locale, jamais dans le journal (ADR 0008).
*/
nom: string, 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: string | null, };
+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.
/**
* Why the last share stopped, when it was not the user.
*/
export type Stop = { reason: string,
/**
* 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.
/**
* Thème de l'interface de l'hôte.
* Theme of the host interface.
*/
export type Theme = "systeme" | "clair" | "sombre";
export type Theme = "system" | "light" | "dark";
@@ -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";
/**
* A device allowed to come back without scanning again (#34). The storage
* exists already so that the format does not need a new version that day.
*/
export type TrustedDevice = { id: DeviceId, name: 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.
/**
* A connected viewer.
*/
export type ViewerDevice = {
/**
* Number to send back to disconnect it.
*/
connection: number, name: string, platform: string | null, address: string,
/**
* Arrival, in Unix milliseconds.
*/
since_ms: number, };
@@ -1,81 +0,0 @@
import { useMemo, useState } from 'react';
import type { SourceChoisie } from '../bindings/SourceChoisie';
import type { SourceProposee } from '../bindings/SourceProposee';
import { cle, filtrer } from '../lib/vue';
import { textes } from '../strings';
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 [recherche, setRecherche] = useState('');
const visibles = useMemo(() => filtrer(sources ?? [], recherche), [sources, recherche]);
const choisie = selection ? cle(selection) : null;
return (
<section className='choix' aria-labelledby='choix-titre'>
<div className='choix-entete'>
<h2 id='choix-titre'>{textes.choisirTitre}</h2>
{sources && sources.length > SEUIL_RECHERCHE && (
<input
type='search'
className='recherche'
placeholder={textes.recherche}
aria-label={textes.recherche}
value={recherche}
onChange={(e) => setRecherche(e.target.value)}
/>
)}
<button type='button' className='bouton discret' onClick={onActualiser} disabled={!actif}>
{textes.actualiser}
</button>
</div>
{sources === null && <p className='aide'>{textes.chargementSources}</p>}
{sources !== null && visibles.length === 0 && <p className='aide'>{textes.aucuneSource}</p>}
<ul className='sources'>
{visibles.map((source) => {
const id = cle(source.choix);
const selectionnee = id === choisie;
return (
<li key={id}>
<button
type='button'
className={`source${selectionnee ? ' selectionnee' : ''}`}
aria-pressed={selectionnee}
disabled={!actif}
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={source.nom}>
{source.nom}
</span>
{source.largeur > 0 && (
<span className='source-taille'>
{source.largeur} × {source.hauteur}
</span>
)}
{source.note && <span className='source-note'>{source.note}</span>}
</button>
</li>
);
})}
</ul>
</section>
);
}
@@ -0,0 +1,52 @@
import { useId, useState } from 'react';
import { useI18n } from '../i18n';
type Props = {
viewers: number;
onCancel: () => void;
onQuit: (dontAskAgain: boolean) => void;
};
/**
* Quitting during a share (#43): say so before cutting the viewers off.
* "Don't ask again" can be turned back on in the settings.
*/
export function ConfirmQuit({ viewers, onCancel, onQuit }: Props) {
const { t } = useI18n();
const [dontAskAgain, setDontAskAgain] = useState(false);
const id = useId();
return (
<div className='overlay'>
<div
className='dialog'
role='alertdialog'
aria-modal='true'
aria-labelledby={`${id}-title`}
aria-describedby={`${id}-text`}
onKeyDown={(e) => e.key === 'Escape' && onCancel()}
>
<h2 id={`${id}-title`}>{t('quitTitle')}</h2>
<p id={`${id}-text`}>{t('quitText', { count: viewers })}</p>
<label className='checkbox'>
<input
type='checkbox'
checked={dontAskAgain}
onChange={(e) => setDontAskAgain(e.target.checked)}
/>
{t('dontAskAgain')}
</label>
<div className='dialog-actions'>
<span className='spacer' />
{/* biome-ignore lint/a11y/noAutofocus: the safe choice gets the focus, Enter stops nothing */}
<button type='button' className='button' onClick={onCancel} autoFocus>
{t('cancel')}
</button>
<button type='button' className='button danger' onClick={() => onQuit(dontAskAgain)}>
{t('quitConfirm')}
</button>
</div>
</div>
</div>
);
}
@@ -1,116 +0,0 @@
import { useEffect, useState } from 'react';
import type { Partage } from '../bindings/Partage';
import { duree } from '../lib/vue';
import { textes } from '../strings';
type Props = {
partage: Partage;
onDeconnecter: (connexion: number) => void;
};
export function PanneauPartage({ partage, onDeconnecter }: Props) {
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(':');
return (
<section className='partage'>
<div className='carte qr-carte'>
<h2>{textes.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>{textes.lien}</span>
<span className='lien-ligne'>
<input readOnly value={partage.url} onFocus={(e) => e.target.select()} />
<button type='button' className='bouton' onClick={copier}>
{copie ? textes.copie : textes.copier}
</button>
</span>
</label>
{partage.empreinte && (
<p className='empreinte'>
{textes.empreinte}: <code>{partage.empreinte}</code>
</p>
)}
</div>
<div className='carte'>
<dl className='faits'>
<dt>{textes.source}</dt>
<dd>
{partage.source.nom}
<span className='discret'>
{' '}
{partage.source.largeur} × {partage.source.hauteur}
</span>
</dd>
<dt>{textes.ecoute}</dt>
<dd>
{partage.interface ? `${partage.interface} (${hote})` : textes.toutesInterfaces}
<span className='discret'> port {partage.ecoute.split(':').pop()}</span>
</dd>
<dt>{textes.depuis}</dt>
<dd>{duree(partage.demarre_ms, maintenant)}</dd>
</dl>
<h2 className='spectateurs-titre'>
{textes.spectateurs}
<span className='compteur'>
{textes.places(partage.appareils.length, partage.limite)}
</span>
</h2>
{partage.appareils.length === 0 ? (
<p className='aide'>{textes.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={textes.deconnecterAide}
onClick={() => onDeconnecter(appareil.connexion)}
>
{textes.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;
}
-241
View File
@@ -1,241 +0,0 @@
import { useEffect, useId, useState } from 'react';
import type { QualityPreset } from '../../../viewer/src/proto/QualityPreset';
import type { InterfaceProposee } from '../bindings/InterfaceProposee';
import type { Langue } from '../bindings/Langue';
import type { Refus } from '../bindings/Refus';
import type { Reglages as ReglagesHote } from '../bindings/Reglages';
import type { Theme } from '../bindings/Theme';
import { type Hote, refusDe } from '../lib/hote';
import { resumeApplication } from '../lib/vue';
import { textes } from '../strings';
type Props = {
hote: Hote;
demarrageAuto: boolean;
onFermer: () => void;
onEnregistre: (reglages: ReglagesHote) => void;
};
export function Reglages({ hote, demarrageAuto, onFermer, onEnregistre }: Props) {
const [reglages, setReglages] = useState<ReglagesHote | null>(null);
const [interfaces, setInterfaces] = useState<InterfaceProposee[]>([]);
const [refus, setRefus] = useState<Refus[]>([]);
const [message, setMessage] = useState<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(resumeApplication(application));
onEnregistre(reglages);
} catch (e) {
setRefus(refusDe(e));
setMessage(null);
} finally {
setEnvoi(false);
}
};
const exporter = async () => {
try {
setMessage(textes.diagnosticsEcrits(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`}>{textes.reglages}</h2>
<form
className='formulaire'
onSubmit={(e) => {
e.preventDefault();
enregistrer();
}}
>
<Champ
id={`${id}-port`}
libelle={textes.port}
aide={textes.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={textes.interface}
aide={textes.interfaceAide}
erreur={erreur('interface')}
>
<select
id={`${id}-interface`}
value={reglages.interface ?? ''}
onChange={(e) => changer('interface', e.target.value === '' ? null : e.target.value)}
>
<option value=''>{textes.toutesInterfaces}</option>
{interfaces.map((i) => (
<option key={i.nom} value={i.nom}>
{i.nom} ({i.adresses.join(', ')}){i.active ? '' : `, ${textes.interfaceInactive}`}
</option>
))}
{absente && reglages.interface && (
<option value={reglages.interface}>
{reglages.interface}, {textes.interfaceInactive}
</option>
)}
</select>
</Champ>
<Champ id={`${id}-limite`} libelle={textes.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}-qualite`} libelle={textes.qualite} erreur={erreur('qualite')}>
<select
id={`${id}-qualite`}
value={reglages.qualite}
onChange={(e) => changer('qualite', e.target.value as QualityPreset)}
>
{(Object.keys(textes.qualites) as QualityPreset[]).map((q) => (
<option key={q} value={q}>
{textes.qualites[q]}
</option>
))}
</select>
</Champ>
<Champ id={`${id}-theme`} libelle={textes.theme}>
<select
id={`${id}-theme`}
value={reglages.theme}
onChange={(e) => changer('theme', e.target.value as Theme)}
>
{(Object.keys(textes.themes) as Theme[]).map((t) => (
<option key={t} value={t}>
{textes.themes[t]}
</option>
))}
</select>
</Champ>
<Champ id={`${id}-langue`} libelle={textes.langue}>
<select
id={`${id}-langue`}
value={reglages.langue}
onChange={(e) => changer('langue', e.target.value as Langue)}
>
{(Object.keys(textes.langues) as Langue[]).map((l) => (
<option key={l} value={l}>
{textes.langues[l]}
</option>
))}
</select>
</Champ>
{demarrageAuto && (
<label className='case'>
<input
type='checkbox'
checked={reglages.demarrage_auto}
onChange={(e) => changer('demarrage_auto', e.target.checked)}
/>
{textes.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}
</p>
)}
<div className='pied'>
<button type='button' className='bouton discret' onClick={exporter}>
{textes.diagnostics}
</button>
<span className='espace' />
<button type='button' className='bouton discret' onClick={onFermer}>
{textes.fermer}
</button>
<button type='submit' className='bouton principal' disabled={envoi}>
{textes.enregistrer}
</button>
</div>
<p className='aide'>{textes.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>
);
}
@@ -0,0 +1,303 @@
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 { outcomeSummary } from '../lib/view';
const QUALITIES: QualityPreset[] = ['saver', 'balanced', 'sharp'];
const CODECS: Codec[] = ['vp8', 'vp9'];
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) => rejections.find((r) => r.field === field)?.message;
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);
}
};
const exportDiagnostics = async () => {
try {
setMessage({ type: 'diagnostics', path: await host.exportDiagnostics() });
} catch (e) {
setRejections([{ field: 'diagnostics', message: String(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}-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>
<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>
)}
{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={exportDiagnostics}>
{t('diagnostics')}
</button>
<span className='spacer' />
<button type='button' className='button muted' onClick={onClose}>
{t('close')}
</button>
<button type='submit' className='button primary' disabled={sending}>
{t('save')}
</button>
</div>
<p className='help'>{t('diagnosticsHelp')}</p>
{error('diagnostics') && <p className='field-error'>{error('diagnostics')}</p>}
</form>
</div>
</div>
);
}
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>
);
}
+142
View File
@@ -0,0 +1,142 @@
import { useEffect, useState } from 'react';
import type { Share } from '../bindings/Share';
import { useI18n } from '../i18n';
import { displayCode, displayName, duration, expiry } from '../lib/view';
type Props = {
share: Share;
onDisconnect: (connection: number) => void;
onNewCode: () => void;
};
export function SharePanel({ share, onDisconnect, onNewCode }: 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 home = share.url.split('/r/')[0] ?? share.url;
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>
<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}>
<span className='device-name'>{device.name}</span>
<span className='muted'>
{[device.platform, device.address].filter(Boolean).join(' · ')}
{' · '}
{duration(device.since_ms, now)}
</span>
<button
type='button'
className='button muted danger'
title={t('disconnectHelp')}
onClick={() => onDisconnect(device.connection)}
>
{t('disconnect')}
</button>
</li>
))}
</ul>
)}
</div>
</section>
);
}
/** The current time, refreshed every second for the displayed durations. */
function useNow(): number {
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
const timer = setInterval(() => setNow(Date.now()), 1000);
return () => clearInterval(timer);
}, []);
return now;
}
@@ -0,0 +1,83 @@
import { useMemo, useState } from 'react';
import type { SourceChoice } from '../bindings/SourceChoice';
import type { SourceOption } from '../bindings/SourceOption';
import { useI18n } from '../i18n';
import { displayName, filter, key } from '../lib/view';
type Props = {
sources: SourceOption[] | null;
selection: SourceChoice | null;
enabled: boolean;
onPick: (choice: SourceChoice) => void;
onRefresh: () => 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 }: 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>
</section>
);
}
+66
View File
@@ -0,0 +1,66 @@
import { createContext, type ReactNode, useContext, useMemo } from 'react';
import {
type AvailableLanguage,
type Catalog,
createTranslator,
FALLBACK_LANGUAGE,
pickLanguage,
type Translate,
} from '../../viewer/src/lib/i18n';
/**
* Texts of the shell (#21). The same files as the viewer (`locales/*.json`),
* embedded at build time: the shell has no server to ask when no share is
* running. A file added to the folder is one more language, with no code to
* change.
*/
type LocaleFile = Catalog & { _language: AvailableLanguage };
const FILES = Object.values(
import.meta.glob<LocaleFile>('../../../locales/*.json', { eager: true, import: 'default' }),
);
/** The embedded languages, by code. */
export const LANGUAGES: AvailableLanguage[] = FILES.map((f) => f._language).sort((a, b) =>
a.name.localeCompare(b.name),
);
function catalog(code: string): Catalog | undefined {
return FILES.find((f) => f._language.code === code);
}
/**
* The language to display: the setting if it names an embedded language,
* otherwise the desktop's (`navigator.languages` reflects the session locale).
*/
export function effectiveLanguage(setting: string | null, preferences: readonly string[]): string {
const codes = LANGUAGES.map((l) => l.code);
if (setting && codes.includes(setting)) return setting;
return pickLanguage(preferences, codes);
}
/** The shell translation in `code`, English as fallback. */
export function translatorFor(code: string): Translate {
const catalogs = [catalog(code), catalog(FALLBACK_LANGUAGE)].filter(
(c): c is Catalog => c !== undefined,
);
return createTranslator(code, 'desktop', catalogs);
}
type Context = { t: Translate; language: string };
const I18n = createContext<Context | null>(null);
export function useI18n(): Context {
const context = useContext(I18n);
if (!context) throw new Error('useI18n outside of I18nProvider');
return context;
}
/** Changing `language` retranslates everything at the next render, without a restart. */
export function I18nProvider({ language, children }: { language: string; children: ReactNode }) {
const value = useMemo(() => ({ t: translatorFor(language), language }), [language]);
return <I18n.Provider value={value}>{children}</I18n.Provider>;
}
+62
View File
@@ -0,0 +1,62 @@
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 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>;
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'),
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: String(error) }];
}
-50
View File
@@ -1,50 +0,0 @@
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';
/**
* 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>;
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>;
};
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 }),
reglages: () => invoke<Reglages>('reglages'),
modifierReglages: (reglages) => invoke<Application>('modifier_reglages', { reglages }),
interfaces: () => invoke<InterfaceProposee[]>('interfaces'),
exporterDiagnostics: () => invoke<string>('exporter_diagnostics'),
};
/** 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) }];
}
+196
View File
@@ -0,0 +1,196 @@
import { describe, expect, it } from 'vitest';
import type { HostState } from '../bindings/HostState';
import type { Share } from '../bindings/Share';
import type { SourceOption } from '../bindings/SourceOption';
import { effectiveLanguage, LANGUAGES, translatorFor } from '../i18n';
import {
actions,
displayCode,
displayName,
duration,
expiry,
filter,
key,
outcomeSummary,
status,
trayTexts,
} 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');
expect(outcomeSummary({ immediate: [], next_share: ['port: would cut'] }, t)).toContain(
'prochain partage',
);
});
});
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');
});
});
+208
View File
@@ -0,0 +1,208 @@
import type { Translate } from '../../../viewer/src/lib/i18n';
import type { HostState } from '../bindings/HostState';
import type { Label } from '../bindings/Label';
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' };
}
}
}
/** 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 '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')}`;
}
/** 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.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'),
};
}
-112
View File
@@ -1,112 +0,0 @@
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 { actions, cle, duree, filtrer, resumeApplication, statut } from './vue';
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)).texte).toBe('En direct, 2 spectateurs');
expect(statut(etat('en_cours', { appareils: [] } as unknown as Partage)).ton).toBe('direct');
expect(statut(etat('demarrage')).ton).toBe('attente');
});
});
describe('sources', () => {
const source = (nom: string, id: string): SourceProposee => ({
choix: { type: 'x11', id },
genre: 'window',
nom,
largeur: 800,
hauteur: 600,
vignette: null,
note: null,
});
it('la recherche ignore accents et casse', () => {
const liste = [source('Présentation.odp', 'a'), source('Terminal', 'b')];
expect(filtrer(liste, 'presen').map((s) => s.nom)).toEqual(['Présentation.odp']);
expect(filtrer(liste, ' ')).toHaveLength(2);
});
it('la clé distingue écran existant et virtuel', () => {
expect(cle({ type: 'portail', virtuel: true, taille: null })).not.toBe(
cle({ type: 'portail', virtuel: 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: [] })).toContain(
'appliqués',
);
expect(
resumeApplication({ immediats: [], au_prochain_partage: ['port: couperait'] }),
).toContain('prochain partage');
});
it('aucun tiret cadratin', async () => {
const { textes } = await import('../strings');
expect(JSON.stringify(textes)).not.toContain(String.fromCodePoint(0x2014));
});
});
-116
View File
@@ -1,116 +0,0 @@
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 { textes } from '../strings';
/**
* 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): Statut {
switch (etat.phase) {
case 'arrete':
return { texte: textes.statutArrete, ton: 'repos' };
case 'demarrage':
return { texte: textes.statutDemarrage, ton: 'attente' };
case 'en_cours': {
const n = etat.partage?.appareils.length ?? 0;
return { texte: textes.statutEnCours(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':
return choix.virtuel ? 'portail:virtuel' : '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, sans tenir compte des accents ni de la casse. */
export function filtrer(sources: SourceProposee[], recherche: string): SourceProposee[] {
const cherche = normaliser(recherche.trim());
if (cherche === '') {
return sources;
}
return sources.filter((s) => normaliser(s.nom).includes(cherche));
}
/** 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): string {
if (application.au_prochain_partage.length > 0) {
return textes.reglagesEnAttente(application.au_prochain_partage);
}
if (application.immediats.length > 0) {
return textes.reglagesAppliques;
}
return textes.reglagesInchanges;
}
+3 -3
View File
@@ -1,14 +1,14 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { App } from './App';
import { hoteTauri } from './lib/hote';
import { tauriHost } from './lib/host';
import './styles.css';
const root = document.getElementById('root');
if (!root) throw new Error('élément racine absent');
if (!root) throw new Error('root element missing');
createRoot(root).render(
<StrictMode>
<App hote={hoteTauri} />
<App host={tauriHost} />
</StrictMode>,
);
-62
View File
@@ -1,62 +0,0 @@
/** Textes de l'interface. Le français seul pour l'instant (#21). */
export const textes = {
titre: 'rustscreen',
statutArrete: 'Aucun partage',
statutDemarrage: 'Démarrage…',
statutEnCours: (n: number) =>
n === 0 ? 'En direct, personne ne regarde' : `En direct, ${n} spectateur${n > 1 ? 's' : ''}`,
choisirTitre: 'Que voulez-vous partager ?',
recherche: 'Rechercher une fenêtre',
aucuneSource: 'Aucune source trouvée.',
chargementSources: 'Recherche des écrans et des fenêtres…',
actualiser: 'Actualiser',
demarrer: 'Démarrer le partage',
annuler: 'Annuler',
arreter: 'Arrêter le partage',
attenteBureau:
'Le bureau demande l’autorisation de partager: répondez à sa fenêtre pour continuer.',
attente: 'Ouverture de la capture…',
scanner: 'Scannez pour regarder',
lien: 'Lien de la session',
copier: 'Copier',
copie: 'Copié',
empreinte: 'Empreinte du certificat',
source: 'Source',
ecoute: 'Écoute',
toutesInterfaces: 'toutes les interfaces',
depuis: 'Depuis',
spectateurs: 'Spectateurs',
places: (n: number, limite: number) => `${n} sur ${limite}`,
personne: 'Personne pour l’instant. Le lien et le QR code ci-contre permettent de rejoindre.',
deconnecter: 'Déconnecter',
deconnecterAide: 'L’appareil est coupé et ne peut plus revenir avec ce lien.',
veille: 'Mise en veille suspendue pendant le partage',
veilleAbsente: 'La mise en veille n’a pas pu être suspendue: l’écran peut s’éteindre.',
reglages: 'Réglages',
fermer: 'Fermer',
enregistrer: 'Enregistrer',
port: 'Port d’écoute',
portAide: 'De 1024 à 65535. Le lien et le QR code suivent.',
interface: 'Interface réseau',
interfaceAide: 'Écouter sur une seule interface évite d’exposer l’écran sur un autre réseau.',
interfaceInactive: 'déconnectée',
limite: 'Spectateurs au plus',
qualite: 'Qualité par défaut',
qualites: { saver: 'Économe', balanced: 'Équilibrée', sharp: 'Nette' },
theme: 'Thème',
themes: { systeme: 'Comme le bureau', clair: 'Clair', sombre: 'Sombre' },
langue: 'Langue',
langues: { fr: 'Français', en: 'English (à venir)' },
demarrageAuto: 'Lancer rustscreen à l’ouverture de session',
diagnostics: 'Exporter les diagnostics',
diagnosticsAide:
'Une archive à transmettre vous-même: ni image, ni titre de fenêtre, ni adresse MAC.',
diagnosticsEcrits: (chemin: string) => `Archive écrite: ${chemin}`,
reglagesAppliques: 'Réglages enregistrés et appliqués.',
reglagesInchanges: 'Rien n’a changé.',
reglagesEnAttente: (champs: string[]) =>
`Enregistré. Appliqué au prochain partage: ${champs.join('; ')}.`,
enAttente: 'Réglages appliqués au prochain partage',
erreurDemarrage: 'Le partage n’a pas démarré',
arretBureau: 'Le partage s’est arrêté',
} as const;
+189 -141
View File
@@ -1,58 +1,60 @@
/* 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. */
/* Desktop shell. System fonts, no remote resource. Sizes in rem: the
interface follows the desktop scale factor (HiDPI) without images to double. */
:root {
--fond: #f5f6f8;
--bg: #f5f6f8;
--surface: #ffffff;
--bord: #d9dee5;
--texte: #18202a;
--discret: #5d6b7c;
--border: #d9dee5;
--text: #18202a;
--muted: #5d6b7c;
--accent: #2563eb;
--accent-texte: #ffffff;
--direct: #16a34a;
--attente: #d97706;
--danger: #dc2626;
--alerte-fond: #fff7e6;
--erreur-fond: #fdecec;
--info-fond: #eaf1ff;
--rayon: 10px;
--accent-text: #ffffff;
/* Dark enough for text on a light background: AA contrast (4.5:1) checked
for each text and background pair (#28). */
--live: #15803d;
--waiting: #b45309;
--danger: #b91c1c;
--warning-bg: #fff7e6;
--error-bg: #fdecec;
--info-bg: #eaf1ff;
--radius: 10px;
color-scheme: light;
font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Cantarell", sans-serif;
font-size: 15px;
}
:root[data-theme="sombre"] {
--fond: #0d1116;
:root[data-theme="dark"] {
--bg: #0d1116;
--surface: #151b23;
--bord: #2a3441;
--texte: #e9eef5;
--discret: #97a5b6;
--border: #2a3441;
--text: #e9eef5;
--muted: #97a5b6;
--accent: #4c9aff;
--accent-texte: #0d1116;
--direct: #3ddc84;
--attente: #f5a524;
--accent-text: #0d1116;
--live: #3ddc84;
--waiting: #f5a524;
--danger: #ff6b6b;
--alerte-fond: #2b2210;
--erreur-fond: #2e1517;
--info-fond: #13213a;
--warning-bg: #2b2210;
--error-bg: #2e1517;
--info-bg: #13213a;
color-scheme: dark;
}
@media (prefers-color-scheme: dark) {
:root[data-theme="systeme"] {
--fond: #0d1116;
:root[data-theme="system"] {
--bg: #0d1116;
--surface: #151b23;
--bord: #2a3441;
--texte: #e9eef5;
--discret: #97a5b6;
--border: #2a3441;
--text: #e9eef5;
--muted: #97a5b6;
--accent: #4c9aff;
--accent-texte: #0d1116;
--direct: #3ddc84;
--attente: #f5a524;
--accent-text: #0d1116;
--live: #3ddc84;
--waiting: #f5a524;
--danger: #ff6b6b;
--alerte-fond: #2b2210;
--erreur-fond: #2e1517;
--info-fond: #13213a;
--warning-bg: #2b2210;
--error-bg: #2e1517;
--info-bg: #13213a;
color-scheme: dark;
}
}
@@ -69,8 +71,8 @@ body,
}
body {
background: var(--fond);
color: var(--texte);
background: var(--bg);
color: var(--text);
-webkit-font-smoothing: antialiased;
}
@@ -88,11 +90,11 @@ h2 {
font-size: 1rem;
}
.chargement {
.loading {
display: grid;
height: 100%;
place-items: center;
color: var(--discret);
color: var(--muted);
}
.app {
@@ -101,8 +103,8 @@ h2 {
flex-direction: column;
}
.entete,
.barre {
.header,
.action-bar {
display: flex;
align-items: center;
gap: 0.75rem;
@@ -110,37 +112,37 @@ h2 {
background: var(--surface);
}
.entete {
border-bottom: 1px solid var(--bord);
.header {
border-bottom: 1px solid var(--border);
}
.barre {
border-top: 1px solid var(--bord);
.action-bar {
border-top: 1px solid var(--border);
min-height: 3.75rem;
}
.espace {
.spacer {
flex: 1;
}
.contenu {
.content {
flex: 1;
overflow: auto;
padding: 1.25rem;
}
.pastille {
.badge {
display: inline-flex;
align-items: center;
gap: 0.4rem;
padding: 0.2rem 0.65rem;
border-radius: 999px;
border: 1px solid var(--bord);
color: var(--discret);
border: 1px solid var(--border);
color: var(--muted);
font-size: 0.85rem;
}
.pastille::before {
.badge::before {
content: "";
width: 0.5rem;
height: 0.5rem;
@@ -148,108 +150,108 @@ h2 {
background: currentColor;
}
.pastille.direct {
color: var(--direct);
.badge.live {
color: var(--live);
border-color: currentColor;
}
.pastille.attente {
color: var(--attente);
.badge.waiting {
color: var(--waiting);
border-color: currentColor;
}
.veille {
color: var(--discret);
.sleep {
color: var(--muted);
font-size: 0.85rem;
}
.bouton {
.button {
padding: 0.5rem 1rem;
border: 1px solid var(--bord);
border: 1px solid var(--border);
border-radius: 8px;
background: var(--surface);
color: var(--texte);
color: var(--text);
font: inherit;
cursor: pointer;
}
.bouton:hover:not(:disabled) {
.button:hover:not(:disabled) {
border-color: var(--accent);
}
.bouton:disabled {
.button:disabled {
opacity: 0.5;
cursor: default;
}
.bouton.principal {
.button.primary {
background: var(--accent);
border-color: var(--accent);
color: var(--accent-texte);
color: var(--accent-text);
font-weight: 600;
}
.bouton.danger {
.button.danger {
color: var(--danger);
border-color: var(--danger);
}
.bouton.discret {
.button.muted {
padding: 0.35rem 0.75rem;
}
.aide,
.discret {
color: var(--discret);
.help,
.muted {
color: var(--muted);
font-size: 0.85rem;
}
.bandeau {
.banner {
margin-bottom: 1rem;
padding: 0.65rem 0.9rem;
border-radius: var(--rayon);
border: 1px solid var(--bord);
border-radius: var(--radius);
border: 1px solid var(--border);
}
.bandeau.erreur {
background: var(--erreur-fond);
.banner.error {
background: var(--error-bg);
border-color: var(--danger);
}
.bandeau.alerte {
background: var(--alerte-fond);
border-color: var(--attente);
.banner.warning {
background: var(--warning-bg);
border-color: var(--waiting);
}
.bandeau.info {
background: var(--info-fond);
.banner.info {
background: var(--info-bg);
border-color: var(--accent);
}
.choix-entete {
.picker-header {
display: flex;
align-items: center;
gap: 0.75rem;
margin-bottom: 1rem;
}
.choix-entete h2 {
.picker-header h2 {
flex: 1;
}
.recherche,
.formulaire input:not([type="checkbox"]),
.formulaire select,
.lien input {
.search,
.form input:not([type="checkbox"]),
.form select,
.link input {
padding: 0.45rem 0.6rem;
border: 1px solid var(--bord);
border: 1px solid var(--border);
border-radius: 8px;
background: var(--fond);
color: var(--texte);
background: var(--bg);
color: var(--text);
font: inherit;
}
.recherche {
.search {
width: 16rem;
}
@@ -269,10 +271,10 @@ h2 {
flex-direction: column;
gap: 0.3rem;
padding: 0.6rem;
border: 2px solid var(--bord);
border-radius: var(--rayon);
border: 2px solid var(--border);
border-radius: var(--radius);
background: var(--surface);
color: var(--texte);
color: var(--text);
font: inherit;
text-align: left;
cursor: pointer;
@@ -282,55 +284,64 @@ h2 {
border-color: var(--accent);
}
.source.selectionnee {
.source.selected {
border-color: var(--accent);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 25%, transparent);
}
.source:disabled {
cursor: default;
opacity: 0.7;
}
.vignette {
.source.unavailable {
border-style: dashed;
}
.thumbnail {
display: grid;
aspect-ratio: 16 / 9;
place-items: center;
overflow: hidden;
border-radius: 6px;
background: var(--fond);
background: var(--bg);
}
.vignette img {
/* The text keeps its contrast: only the picture fades. The note says why the
source cannot be shared (#17). */
.source:disabled .thumbnail {
opacity: 0.45;
}
.thumbnail img {
width: 100%;
height: 100%;
object-fit: contain;
}
.vignette-vide {
color: var(--discret);
.thumbnail-empty {
color: var(--muted);
font-size: 2.5rem;
}
.source-nom {
.source-name {
overflow: hidden;
font-weight: 600;
text-overflow: ellipsis;
white-space: nowrap;
}
.source-taille,
.source-size,
.source-note {
color: var(--discret);
color: var(--muted);
font-size: 0.8rem;
}
.attente {
.waiting {
margin: 0;
color: var(--attente);
color: var(--waiting);
}
.partage {
.share {
display: grid;
grid-template-columns: minmax(18rem, 22rem) 1fr;
gap: 1.25rem;
@@ -338,19 +349,19 @@ h2 {
}
@media (max-width: 860px) {
.partage {
.share {
grid-template-columns: 1fr;
}
}
.carte {
.card {
padding: 1.1rem;
border: 1px solid var(--bord);
border-radius: var(--rayon);
border: 1px solid var(--border);
border-radius: var(--radius);
background: var(--surface);
}
.qr-carte {
.qr-card {
display: flex;
flex-direction: column;
gap: 0.9rem;
@@ -368,87 +379,87 @@ h2 {
height: auto;
}
.lien {
.link {
display: flex;
flex-direction: column;
gap: 0.35rem;
font-size: 0.85rem;
color: var(--discret);
color: var(--muted);
}
.lien-ligne {
.link-row {
display: flex;
gap: 0.5rem;
}
.lien input {
.link input {
flex: 1;
min-width: 0;
font-family: ui-monospace, monospace;
font-size: 0.8rem;
}
.empreinte code {
.fingerprint code {
word-break: break-all;
}
.faits {
.facts {
display: grid;
grid-template-columns: auto 1fr;
gap: 0.4rem 1rem;
margin: 0 0 1.25rem;
}
.faits dt {
color: var(--discret);
.facts dt {
color: var(--muted);
}
.faits dd {
.facts dd {
margin: 0;
}
.spectateurs-titre {
.viewers-title {
display: flex;
align-items: baseline;
gap: 0.6rem;
margin-bottom: 0.6rem;
}
.compteur {
color: var(--discret);
.counter {
color: var(--muted);
font-size: 0.85rem;
font-weight: 400;
}
.appareils {
.devices {
margin: 0;
padding: 0;
list-style: none;
}
.appareils li {
.devices li {
display: grid;
grid-template-columns: 1fr auto;
align-items: center;
gap: 0.15rem 0.75rem;
padding: 0.6rem 0;
border-top: 1px solid var(--bord);
border-top: 1px solid var(--border);
}
.appareils li .discret {
.devices li .muted {
grid-column: 1;
}
.appareils li .bouton {
.devices li .button {
grid-column: 2;
grid-row: 1 / span 2;
}
.appareil-nom {
.device-name {
font-weight: 600;
}
.voile {
.overlay {
position: fixed;
inset: 0;
display: grid;
@@ -457,55 +468,92 @@ h2 {
background: rgb(0 0 0 / 45%);
}
.dialogue {
.dialog {
width: min(34rem, 100%);
max-height: 100%;
overflow: auto;
padding: 1.25rem;
border-radius: var(--rayon);
border-radius: var(--radius);
background: var(--surface);
}
.formulaire {
.form {
display: flex;
flex-direction: column;
gap: 0.9rem;
margin-top: 1rem;
}
.champ {
.field {
display: flex;
flex-direction: column;
gap: 0.3rem;
}
.champ label {
.field label {
font-weight: 600;
}
.champ.en-erreur input,
.champ.en-erreur select {
.field.has-error input,
.field.has-error select {
border-color: var(--danger);
}
.case {
.checkbox {
display: flex;
align-items: center;
gap: 0.5rem;
}
.erreur-champ {
.field-error {
color: var(--danger);
font-size: 0.85rem;
}
.confirmation {
margin: 0;
color: var(--direct);
color: var(--live);
}
.pied {
.dialog-actions {
display: flex;
align-items: center;
gap: 0.6rem;
}
/* Short code (#19): readable from afar, easy to dictate. */
.short-code {
display: flex;
flex-wrap: wrap;
gap: 0.35rem 0.75rem;
align-items: baseline;
font-size: 0.85rem;
}
.short-code > .muted:first-child {
flex-basis: 100%;
}
.code-value {
font:
700 1.6rem / 1.1 ui-monospace,
"SF Mono",
Menlo,
monospace;
letter-spacing: 0.12em;
color: var(--text);
}
.code-expired .code-value {
color: var(--muted);
text-decoration: line-through;
}
.code-new {
margin-left: auto;
}
.warning-text {
color: var(--waiting);
font-weight: 600;
}
+1 -1
View File
@@ -1,7 +1,7 @@
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';
// Servi par Tauri depuis `dist`: pas de serveur, pas de ressource distante.
// Served by Tauri from `dist`: no server, no remote resource.
export default defineConfig({
plugins: [react()],
clearScreen: false,
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "@rustscreen/viewer",
"version": "0.4.0",
"version": "0.5.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@rustscreen/viewer",
"version": "0.4.0",
"version": "0.5.0",
"dependencies": {
"react": "^19.2.0",
"react-dom": "^19.2.0"
+3 -3
View File
@@ -1,14 +1,14 @@
{
"name": "@rustscreen/viewer",
"private": true,
"version": "0.4.0",
"version": "0.5.0",
"type": "module",
"description": "Client navigateur de rustscreen: reçoit le flux WebRTC de l'hôte.",
"description": "rustscreen browser client: receives the WebRTC stream from the host.",
"scripts": {
"dev": "vite",
"build": "tsc --noEmit && vite build",
"preview": "vite preview",
"lint": "biome lint src",
"lint": "biome lint src && node ../../scripts/check-i18n.mjs apps/viewer/src viewer",
"format": "biome format --write src",
"test": "vitest run"
},
+151 -28
View File
@@ -1,16 +1,30 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { ErrorPanel } from './components/ErrorPanel';
import { LanguagePicker } from './components/LanguagePicker';
import { Pairing } from './components/Pairing';
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, savePinned } from './lib/controls';
import { parseRoomLocation, signalingUrl } from './lib/room';
import {
nextRotation,
type Rotation,
readMirror,
readRotation,
saveMirror,
saveRotation,
} from './lib/rotation';
import { type VideoStats, ViewerSession, type ViewerState } from './lib/session';
import { strings } from './strings';
import { applyTheme, nextTheme, readTheme, saveTheme, type Theme } from './lib/theme';
import { useActivity } from './lib/useActivity';
export function App() {
const { t } = useI18n();
const location = useMemo(
() => parseRoomLocation(window.location.pathname, window.location.search),
() => parseRoomLocation(window.location.pathname, window.location.search, window.location.hash),
[],
);
const [state, setState] = useState<ViewerState>({ kind: 'connecting', attempt: 0 });
@@ -18,12 +32,18 @@ export function App() {
const [stats, setStats] = useState<VideoStats | null>(null);
const [attemptKey, setAttemptKey] = useState(0);
const [isFullscreen, setIsFullscreen] = useState(false);
const [theme, setTheme] = useState<Theme>(() => readTheme());
const [rotation, setRotation] = useState<Rotation>(() => readRotation());
const [mirror, setMirror] = useState(() => readMirror());
const [pinned, setPinned] = useState(() => readPinned());
const [held, setHeld] = useState(false);
const active = useActivity(IDLE_DELAY_MS);
const sessionRef = useRef<ViewerSession | null>(null);
const containerRef = useRef<HTMLDivElement | null>(null);
// Une session par montage. Le nettoyage est obligatoire: sans lui, le double
// montage de StrictMode ouvre deux WebSocket et deux négociations.
// biome-ignore lint/correctness/useExhaustiveDependencies: attemptKey est la clé de relance du bouton « réessayer », volontairement sans usage dans le corps.
// One session per mount. The cleanup is mandatory: without it, the double
// mount of StrictMode opens two WebSockets and two negotiations.
// biome-ignore lint/correctness/useExhaustiveDependencies: attemptKey is the restart key of the "retry" button, deliberately unused in the body.
useEffect(() => {
if (!location.ok) return;
const session = new ViewerSession({
@@ -74,9 +94,40 @@ export function App() {
}
}, []);
// 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 cycleTheme = useCallback(() => {
setTheme((current) => {
const next = nextTheme(current);
applyTheme(next);
saveTheme(next);
return next;
});
}, []);
const rotate = useCallback(() => {
setRotation((current) => {
const next = nextRotation(current);
saveRotation(next);
return next;
});
}, []);
const toggleMirror = useCallback(() => {
setMirror((current) => {
saveMirror(!current);
return !current;
});
}, []);
const togglePinned = useCallback(() => {
setPinned((current) => {
savePinned(!current);
return !current;
});
}, []);
// Restarts a series of attempts on the existing session, without reloading
// the page: the requested quality and the wake listeners are kept. A
// session stopped for good is replaced by a new one.
const retry = useCallback(() => {
setStats(null);
if (sessionRef.current?.retry()) return;
@@ -85,41 +136,110 @@ export function App() {
}, []);
if (!location.ok) {
return (
<div className='app app-centered'>
<div className='panel' role='alert'>
<h1>{strings.appName}</h1>
<p>{location.reason === 'missing_token' ? strings.missingToken : strings.missingUrl}</p>
</div>
</div>
);
// 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 = {
missing_room: null,
missing_token: t('missingToken'),
malformed: t('missingUrl'),
newer_link: t('newerLink'),
}[location.reason];
return <Pairing notice={notice} />;
}
const live = state.kind === 'streaming';
// Décision #65: HTTP assumé sur le LAN. Le spectateur doit savoir ce qui est
// chiffré (le média) et ce qui ne l'est pas (la page et le signalement).
// Decision #65: HTTP on the LAN is assumed. The viewer must know what is
// encrypted (the media) and what is not (the page and signalling).
const insecure =
window.location.protocol === 'http:' &&
window.location.hostname !== 'localhost' &&
window.location.hostname !== '127.0.0.1';
const compact = isCompact(isFullscreen, pinned);
const visible = barsVisible({ compact, live, active, held });
// The bars stay shown while the pointer or the focus is on them: a button
// about to be touched must not disappear.
const hold = {
onPointerEnter: () => setHeld(true),
onPointerLeave: () => setHeld(false),
onFocus: () => setHeld(true),
onBlur: () => setHeld(false),
};
const classes = [
'app',
isFullscreen ? 'app-fullscreen' : '',
compact ? 'app-compact' : '',
visible ? '' : 'app-hidden',
]
.filter(Boolean)
.join(' ');
return (
<div className={`app ${isFullscreen ? 'app-fullscreen' : ''}`} ref={containerRef}>
<header className='topbar'>
<span className='brand'>{strings.appName}</span>
<div className={classes} ref={containerRef}>
<header className='topbar' {...hold}>
<span className='brand'>{t('appName')}</span>
<StatusBadge state={state} />
{insecure && (
<span className='badge badge-warn' title={strings.insecureHint}>
{strings.insecureBadge}
{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>
)}
<button
type='button'
className='button button-ghost button-theme'
onClick={cycleTheme}
aria-label={t('themeButton', { current: t(`themes.${theme}`) })}
title={t('themeButton', { current: t(`themes.${theme}`) })}
>
{theme === 'dark' ? '☾' : theme === 'light' ? '☀' : '◐'}
</button>
{live && (
<button
type='button'
className='button button-ghost'
onClick={rotate}
aria-label={t('rotate', { degrees: rotation })}
title={t('rotate', { degrees: rotation })}
>
↻
</button>
)}
{live && (
<button
type='button'
className='button button-ghost'
onClick={toggleMirror}
aria-pressed={mirror}
aria-label={t('mirror')}
title={t('mirror')}
>
⇋
</button>
)}
{live && !isFullscreen && (
<button
type='button'
className='button button-ghost'
onClick={togglePinned}
aria-pressed={pinned}
aria-label={t(pinned ? 'unpin' : 'pin')}
title={t(pinned ? 'unpin' : 'pin')}
>
{pinned ? '▣' : '▢'}
</button>
)}
{live && (
<button
type='button'
className='button button-ghost'
onClick={toggleFullscreen}
aria-label={isFullscreen ? strings.exitFullscreen : strings.fullscreen}
title={isFullscreen ? strings.exitFullscreen : strings.fullscreen}
aria-label={isFullscreen ? t('exitFullscreen') : t('fullscreen')}
title={isFullscreen ? t('exitFullscreen') : t('fullscreen')}
>
{isFullscreen ? '⤡' : '⤢'}
</button>
@@ -130,13 +250,16 @@ export function App() {
<VideoStage
stream={stream}
live={live}
label={live ? strings.streaming : strings.negotiating}
label={live ? t('streaming') : t('negotiating')}
rotation={rotation}
mirror={mirror}
/>
{state.kind === 'failed' && <ErrorPanel state={state} onRetry={retry} />}
</main>
<footer className='footer'>
<footer className='footer' {...hold}>
<StatsBar stats={stats} />
<LanguagePicker />
</footer>
</div>
);
+9 -8
View File
@@ -1,5 +1,5 @@
import { strings } from '../strings';
import { isRetryable, type ViewerState } from '../lib/session';
import { useI18n } from '../i18n';
import { isRetryable, messageFor, type ViewerState } from '../lib/session';
type Props = {
state: Extract<ViewerState, { kind: 'failed' }>;
@@ -7,19 +7,20 @@ type Props = {
};
/**
* Panneau d'erreur. Il dit ce qui s'est passé, si réessayer peut aider, et ne
* propose le bouton que dans ce cas: un bouton qui échoue toujours est pire
* qu'une explication.
* Error panel. It says what happened, whether retrying can help, and offers
* the button only in that case: a button that always fails is worse than an
* explanation.
*/
export function ErrorPanel({ state, onRetry }: Props) {
const { t } = useI18n();
const retryable = isRetryable(state.code);
return (
<div className='panel' role='alert'>
<h2>{strings.failedTitle}</h2>
<p>{state.message}</p>
<h2>{t('failedTitle')}</h2>
<p>{messageFor(state.code, t)}</p>
{retryable && (
<button type='button' className='button' onClick={onRetry}>
{strings.retry}
{t('retry')}
</button>
)}
</div>
@@ -0,0 +1,27 @@
import { useId } from 'react';
import { useI18n } from '../i18n';
/**
* Language picker (#21), among those the host serves. Each one shows in its
* own language: whoever cannot read the current language finds their own.
*/
export function LanguagePicker() {
const { t, language, languages, setLanguage } = useI18n();
const id = useId();
if (languages.length < 2) return null;
return (
<span className='language'>
<label htmlFor={id} className='visually-hidden'>
{t('language')}
</label>
<select id={id} value={language} onChange={(e) => setLanguage(e.target.value)}>
{languages.map((l) => (
<option key={l.code} value={l.code} lang={l.code}>
{l.name}
</option>
))}
</select>
</span>
);
}
+165
View File
@@ -0,0 +1,165 @@
import { type FormEvent, useCallback, useEffect, useRef, useState } from 'react';
import { exchangeCode, qrDetector } from '../lib/pairing';
import { useI18n } from '../i18n';
import { isCompleteCode, normalizeCode, sessionFromScan } from '../lib/room';
import { LanguagePicker } from './LanguagePicker';
/** A sample code, in the format the host shows: not a sentence. */
const SAMPLE_CODE = 'K7M 4PQ';
type Props = {
/** Why we land here without a session, to say before the form. */
notice: string | null;
};
/**
* Home page without a session (#19): type the short code shown by the host,
* or scan its QR code when the browser can.
*/
export function Pairing({ notice }: Props) {
const { t } = useI18n();
const [code, setCode] = useState('');
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [scanning, setScanning] = useState(false);
const [canScan] = useState(() => qrDetector() !== null);
const submit = useCallback(
async (event: FormEvent) => {
event.preventDefault();
const normalized = normalizeCode(code);
if (!isCompleteCode(normalized)) {
setError(t('codeIncomplete'));
return;
}
setBusy(true);
setError(null);
const outcome = await exchangeCode(normalized);
setBusy(false);
switch (outcome.kind) {
case 'accepted':
window.location.assign(outcome.path);
return;
case 'unknown':
setError(t('codeUnknown'));
return;
case 'expired':
setError(t('codeExpired'));
return;
case 'too_many_attempts':
setError(t('codeTooMany', { seconds: outcome.retryAfterS }));
return;
case 'network':
setError(t('codeNetwork'));
}
},
[code, t],
);
return (
<div className='app app-centered'>
<div className='panel pairing'>
<h1>{t('appName')}</h1>
{notice && <p role='alert'>{notice}</p>}
<form onSubmit={submit} className='pairing-form'>
<label htmlFor='code'>{t('codeLabel')}</label>
<input
id='code'
className='pairing-code'
value={code}
onChange={(event) => setCode(event.target.value.toUpperCase())}
autoComplete='off'
autoCapitalize='characters'
spellCheck={false}
maxLength={8}
placeholder={SAMPLE_CODE}
aria-describedby={error ? 'code-error' : undefined}
aria-invalid={error !== null}
/>
<button type='submit' className='button' disabled={busy}>
{t('codeSubmit')}
</button>
</form>
{error && (
<p id='code-error' className='pairing-error' role='alert'>
{error}
</p>
)}
<p className='pairing-hint'>{t('codeHint')}</p>
{canScan && !scanning && (
<button type='button' className='button button-ghost' onClick={() => setScanning(true)}>
{t('scanButton')}
</button>
)}
{scanning && <Scanner onClose={() => setScanning(false)} onError={setError} />}
<LanguagePicker />
</div>
</div>
);
}
/** Rear camera, reading the QR code four times per second. */
function Scanner({ onClose, onError }: { onClose: () => void; onError: (m: string) => void }) {
const { t } = useI18n();
const videoRef = useRef<HTMLVideoElement | null>(null);
useEffect(() => {
const detector = qrDetector();
if (!detector) return;
let stream: MediaStream | null = null;
let timer: ReturnType<typeof setInterval> | undefined;
let stopped = false;
void navigator.mediaDevices
.getUserMedia({ video: { facingMode: 'environment' }, audio: false })
.then((media) => {
if (stopped) {
for (const track of media.getTracks()) track.stop();
return;
}
stream = media;
const video = videoRef.current;
if (!video) return;
video.srcObject = media;
void video.play().catch(() => undefined);
timer = setInterval(() => {
void detector
.detect(video)
.then((codes) => {
for (const found of codes) {
const target = sessionFromScan(found.rawValue);
if (target) {
window.location.assign(target);
return;
}
}
})
.catch(() => undefined);
}, 250);
})
.catch(() => {
onError(t('scanDenied'));
onClose();
});
return () => {
stopped = true;
clearInterval(timer);
for (const track of stream?.getTracks() ?? []) track.stop();
};
}, [onClose, onError, t]);
return (
<div className='scanner'>
<video
ref={videoRef}
className='scanner-video'
playsInline
muted
aria-label={t('scanButton')}
/>
<button type='button' className='button button-ghost' onClick={onClose}>
{t('scanClose')}
</button>
</div>
);
}
+16 -9
View File
@@ -1,18 +1,19 @@
import { useEffect, useRef, useState } from 'react';
import { useI18n } from '../i18n';
import type { VideoStats } from '../lib/session';
import { strings } from '../strings';
type Props = {
stats: VideoStats | null;
};
/**
* Bandeau de statistiques. Le débit n'est pas fourni par `getStats` en une
* valeur: on le calcule entre deux relevés, ce qui évite d'afficher un chiffre
* qui ne veut rien dire sur la première seconde.
* Statistics strip. `getStats` does not give the bitrate as a single value:
* it is computed between two samples, which avoids showing a meaningless
* figure during the first second.
*/
export function StatsBar({ stats }: Props) {
const { t, language } = useI18n();
const previous = useRef<{ bytes: number; at: number } | null>(null);
const [kbps, setKbps] = useState<number | null>(null);
@@ -37,23 +38,29 @@ export function StatsBar({ stats }: Props) {
return (
<dl className='stats'>
<div>
<dt>{strings.statsResolution}</dt>
<dt>{t('statsResolution')}</dt>
<dd>
{stats.width}×{stats.height}
</dd>
</div>
<div>
<dt>{strings.statsRate}</dt>
<dt>{t('statsRate')}</dt>
<dd>{stats.fps}</dd>
</div>
<div>
<dt>{strings.statsFrames}</dt>
<dt>{t('statsFrames')}</dt>
<dd>{formatCount(stats.frames)}</dd>
</div>
{kbps !== null && (
<div>
<dt>{strings.statsBitrate}</dt>
<dd>{kbps >= 1000 ? `${(kbps / 1000).toFixed(1)} Mbit/s` : `${kbps} kbit/s`}</dd>
<dt>{t('statsBitrate')}</dt>
<dd>
{kbps >= 1000
? t('mbps', {
value: (kbps / 1000).toLocaleString(language, { maximumFractionDigits: 1 }),
})
: t('kbps', { value: kbps })}
</dd>
</div>
)}
</dl>
+12 -10
View File
@@ -1,29 +1,31 @@
import { useI18n } from '../i18n';
import type { Translate } from '../lib/i18n';
import type { ViewerState } from '../lib/session';
import { strings } from '../strings';
/** Traduit l'état de session en un libellé court et une couleur. */
export function describe(state: ViewerState): { text: string; tone: string } {
/** Turns the session state into a short label and a colour. */
export function describe(state: ViewerState, t: Translate): { text: string; tone: string } {
switch (state.kind) {
case 'connecting':
return { text: strings.connecting, tone: 'pending' };
return { text: t('connecting'), tone: 'pending' };
case 'negotiating':
return { text: strings.negotiating, tone: 'pending' };
return { text: t('negotiating'), tone: 'pending' };
case 'streaming':
return { text: strings.streaming, tone: 'live' };
return { text: t('streaming'), tone: 'live' };
case 'reconnecting':
return {
text: strings.reconnecting(Math.ceil(state.delayMs / 1000)),
text: t('reconnecting', { seconds: Math.ceil(state.delayMs / 1000) }),
tone: 'pending',
};
case 'ended':
return { text: strings.ended, tone: 'neutral' };
return { text: t('ended'), tone: 'neutral' };
case 'failed':
return { text: strings.failedTitle, tone: 'error' };
return { text: t('failedTitle'), tone: 'error' };
}
}
export function StatusBadge({ state }: { state: ViewerState }) {
const { text, tone } = describe(state);
const { t } = useI18n();
const { text, tone } = describe(state, t);
return (
<span className={`badge badge-${tone}`} role='status' aria-live='polite'>
{tone === 'live' && <span className='badge-dot' aria-hidden='true' />}
+57 -8
View File
@@ -1,17 +1,24 @@
import { useEffect, useRef } from 'react';
import { useEffect, useRef, useState } from 'react';
import { type Rotation, rotatedBox } from '../lib/rotation';
type Props = {
stream: MediaStream | null;
live: boolean;
label: string;
rotation: Rotation;
mirror: boolean;
};
/**
* La scène vidéo. La balise reste montée même sans flux: la démonter pour la
* remonter à chaque négociation ferait sauter le plein écran sur iOS.
* The video stage. The element stays mounted even without a stream:
* unmounting and remounting it at every negotiation would drop full screen on
* iOS. A rotation changes its box and its transform, never the stream (#30).
*/
export function VideoStage({ stream, live, label }: Props) {
export function VideoStage({ stream, live, label, rotation, mirror }: Props) {
const videoRef = useRef<HTMLVideoElement | null>(null);
const stageRef = useRef<HTMLDivElement | null>(null);
const [size, setSize] = useState<{ width: number; height: number } | null>(null);
useEffect(() => {
const video = videoRef.current;
@@ -20,15 +27,57 @@ export function VideoStage({ stream, live, label }: Props) {
video.srcObject = stream;
}
if (stream) {
// `play()` peut être refusé si l'utilisateur n'a pas interagi; la
// vidéo est muette, donc en pratique il passe. On ignore l'échec.
// `play()` may be refused if the user has not interacted; the video
// is muted, so in practice it goes through. The failure is ignored.
void video.play().catch(() => undefined);
}
}, [stream]);
// The turned box depends on the stage size: full screen, switching to
// portrait, the virtual keyboard all change it.
useEffect(() => {
const stage = stageRef.current;
if (!stage || typeof ResizeObserver === 'undefined') return;
const observer = new ResizeObserver(([entry]) => {
if (!entry) return;
const { width, height } = entry.contentRect;
setSize({ width, height });
});
observer.observe(stage);
return () => observer.disconnect();
}, []);
// Without rotation, the element keeps its box: the mirror alone flips it.
const style =
rotation === 0
? mirror
? { transform: 'scaleX(-1)' }
: undefined
: size
? (() => {
const box = rotatedBox(size.width, size.height, rotation, mirror);
return {
inset: 'auto',
left: '50%',
top: '50%',
width: `${box.width}px`,
height: `${box.height}px`,
transform: box.transform,
};
})()
: undefined;
return (
<div className='stage'>
<video ref={videoRef} className='stage-video' playsInline muted autoPlay aria-label={label} />
<div className='stage' ref={stageRef}>
<video
ref={videoRef}
className='stage-video'
style={style}
playsInline
muted
autoPlay
aria-label={label}
/>
{!live && (
<div className='stage-veil' role='status' aria-live='polite'>
<span className='stage-dot' aria-hidden='true' />
+124
View File
@@ -0,0 +1,124 @@
import { createContext, type ReactNode, useCallback, useContext, useMemo, useState } from 'react';
import {
type AvailableLanguage,
type Catalog,
createTranslator,
FALLBACK_LANGUAGE,
pickLanguage,
type Translate,
} from './lib/i18n';
import { browserStorage, readMigrated } from './lib/storage';
/**
* Viewer texts (#21). The catalog comes from the host (`/locales/`): adding a
* language to the host makes it available here, without rebuilding the
* viewer. The choice is kept by the device alone, like the theme.
*/
const KEY = 'rustscreen.language';
/** Key before #83. */
const LEGACY_KEY = 'rustscreen.langue';
type Context = {
t: Translate;
language: string;
languages: AvailableLanguage[];
setLanguage: (code: string) => void;
};
const I18n = createContext<Context | null>(null);
export function useI18n(): Context {
const context = useContext(I18n);
if (!context) throw new Error('useI18n outside of I18nProvider');
return context;
}
type Loaded = { language: string; catalogs: Catalog[] };
export function I18nProvider({
initial,
languages,
children,
}: {
initial: Loaded;
languages: AvailableLanguage[];
children: ReactNode;
}) {
const [loaded, setLoaded] = useState(initial);
const setLanguage = useCallback((code: string) => {
saveLanguage(code);
// 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 });
});
}, []);
const value = useMemo(
() => ({
t: createTranslator(loaded.language, 'viewer', loaded.catalogs),
language: loaded.language,
languages,
setLanguage,
}),
[loaded, languages, setLanguage],
);
return <I18n.Provider value={value}>{children}</I18n.Provider>;
}
/** The languages the host serves, empty if it does not answer. */
export async function loadLanguages(): Promise<AvailableLanguage[]> {
try {
const response = await fetch('/locales/index.json');
if (!response.ok) return [];
return (await response.json()) as AvailableLanguage[];
} catch {
return [];
}
}
/** The wanted language then English, whichever of the two exist. */
export async function loadCatalogs(code: string): Promise<Catalog[]> {
const codes = code === FALLBACK_LANGUAGE ? [code] : [code, FALLBACK_LANGUAGE];
const catalogs = await Promise.all(
codes.map(async (c) => {
try {
const response = await fetch(`/locales/${encodeURIComponent(c)}.json`);
return response.ok ? ((await response.json()) as Catalog) : null;
} catch {
return null;
}
}),
);
return catalogs.filter((c): c is Catalog => c !== null);
}
/** The choice kept by the device, otherwise the browser language. */
export function initialLanguage(available: AvailableLanguage[]): string {
const codes = available.map((l) => l.code);
const saved = readLanguage();
if (saved && codes.includes(saved)) return saved;
return pickLanguage(navigator.languages ?? [navigator.language], codes);
}
function readLanguage(): string | null {
try {
const storage = browserStorage();
return storage ? readMigrated(storage, KEY, LEGACY_KEY) : null;
} catch {
return null;
}
}
function saveLanguage(code: string): void {
try {
window.localStorage.setItem(KEY, code);
} catch {
// Private browsing: the choice holds for the page only.
}
}
+52
View File
@@ -0,0 +1,52 @@
import { describe, expect, it } from 'vitest';
import { barsVisible, isCompact, readPinned, savePinned } 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);
});
});
+55
View File
@@ -0,0 +1,55 @@
/**
* 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.
}
}
+57 -19
View File
@@ -1,40 +1,78 @@
import { describe, expect, it, vi } from 'vitest';
import { deviceId } from './device';
import type { KeyValueStore } from './storage';
function memoire(): Pick<Storage, 'getItem' | 'setItem'> {
const valeurs = new Map<string, string>();
function memory(
initial: Record<string, string> = {},
): KeyValueStore & { values: Map<string, string> } {
const values = new Map(Object.entries(initial));
return {
getItem: (k) => valeurs.get(k) ?? null,
values,
getItem: (k) => values.get(k) ?? null,
setItem: (k, v) => {
valeurs.set(k, v);
values.set(k, v);
},
removeItem: (k) => {
values.delete(k);
},
};
}
describe('identifiant d’appareil', () => {
it('se passe de randomUUID, absent hors contexte sécurisé (HTTP sur le LAN)', () => {
const denied: KeyValueStore = {
getItem: () => {
throw new Error('denied');
},
setItem: () => {
throw new Error('denied');
},
removeItem: () => {
throw new Error('denied');
},
};
describe('device id', () => {
it('does without randomUUID, missing outside a secure context (HTTP on the LAN)', () => {
vi.stubGlobal('crypto', { getRandomValues: globalThis.crypto.getRandomValues.bind(crypto) });
try {
expect(deviceId(memoire())).toMatch(/^[0-9a-f]{32}$/);
expect(deviceId(memory())).toMatch(/^[0-9a-f]{32}$/);
} finally {
vi.unstubAllGlobals();
}
});
it('reste le même d’une connexion à l’autre', () => {
const stockage = memoire();
expect(deviceId(stockage)).toBe(deviceId(stockage));
it('stays the same from one connection to the next', () => {
const storage = memory();
expect(deviceId(storage)).toBe(deviceId(storage));
});
it('survit à un stockage refusé', () => {
const refuse = {
getItem: () => {
throw new Error('refusé');
},
setItem: () => {
throw new Error('refusé');
},
it('survives a denied storage', () => {
expect(deviceId(denied)).toBe(deviceId(denied));
});
});
describe('device id migration (#83)', () => {
const legacy = '0123456789abcdef0123456789abcdef';
it('keeps the id stored under the old French key, moved to the new one', () => {
const storage = memory({ 'rustscreen.appareil': legacy });
expect(deviceId(storage)).toBe(legacy);
expect(storage.values.get('rustscreen.device')).toBe(legacy);
expect(storage.values.has('rustscreen.appareil')).toBe(false);
expect(deviceId(storage)).toBe(legacy);
});
it('prefers the new key when both exist', () => {
const current = 'fedcba9876543210fedcba9876543210';
const storage = memory({ 'rustscreen.device': current, 'rustscreen.appareil': legacy });
expect(deviceId(storage)).toBe(current);
});
it('keeps the old key when the new one cannot be written', () => {
const storage = memory({ 'rustscreen.appareil': legacy });
storage.setItem = () => {
throw new Error('quota');
};
expect(deviceId(refuse)).toBe(deviceId(refuse));
expect(deviceId(storage)).toBe(legacy);
expect(storage.values.get('rustscreen.appareil')).toBe(legacy);
});
});
+31 -36
View File
@@ -1,53 +1,48 @@
/**
* Identifiant de cet appareil, stable d'une visite à l'autre.
* Id of this device, stable from one visit to the next.
*
* Deux contraintes:
* Two constraints:
*
* - 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.
* - 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 stockage local peut être refusé (navigation privée): on garde alors un
* identifiant pour la durée de la page.
* Local storage may be denied (private browsing): the id then lasts for the
* page only.
*/
const CLE = 'rustscreen.appareil';
import { browserStorage, type KeyValueStore, readMigrated } from './storage';
let memoire: string | null = null;
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}$/;
export function deviceId(
storage: Pick<Storage, 'getItem' | 'setItem'> | null = stockage(),
): string {
let pageId: string | null = null;
export function deviceId(storage: KeyValueStore | null = browserStorage()): string {
try {
const connu = storage?.getItem(CLE);
if (connu && /^[0-9a-f]{32}$/.test(connu)) {
return connu;
const known = storage ? readMigrated(storage, KEY, LEGACY_KEY) : null;
if (known && ID_PATTERN.test(known)) {
return known;
}
} catch {
// Stockage refusé: identifiant de page ci-dessous.
// Storage denied: page id below.
}
const neuf = memoire ?? aleatoire();
memoire = neuf;
const fresh = pageId ?? randomId();
pageId = fresh;
try {
storage?.setItem(CLE, neuf);
storage?.setItem(KEY, fresh);
} catch {
// Idem.
// Same.
}
return neuf;
return fresh;
}
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;
}
function randomId(): string {
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
}
+55
View File
@@ -0,0 +1,55 @@
import { describe, expect, it } from 'vitest';
import { type Catalog, createTranslator, pickLanguage } from './i18n';
const fr: Catalog = {
viewer: {
greeting: 'Bonjour {name}',
viewers: { '0': 'personne', one: '{count} spectateur', other: '{count} spectateurs' },
},
};
const en: Catalog = {
viewer: {
greeting: 'Hello {name}',
onlyInEnglish: 'Only in English',
viewers: { '0': 'nobody', one: '{count} viewer', other: '{count} viewers' },
},
};
describe('createTranslator (#21)', () => {
it('interpolates the parameters', () => {
const t = createTranslator('fr', 'viewer', [fr, en]);
expect(t('greeting', { name: 'Ana' })).toBe('Bonjour Ana');
});
it('picks the plural form of the language', () => {
const t = createTranslator('fr', 'viewer', [fr, en]);
expect(t('viewers', { count: 0 })).toBe('personne');
expect(t('viewers', { count: 1 })).toBe('1 spectateur');
expect(t('viewers', { count: 3 })).toBe('3 spectateurs');
});
it('falls back to English for a missing key, never to the raw key', () => {
const t = createTranslator('fr', 'viewer', [fr, en]);
expect(t('onlyInEnglish')).toBe('Only in English');
expect(t('no.where')).toBe('');
});
it('a language unknown to Intl breaks nothing', () => {
const t = createTranslator('xx-invalid-%', 'viewer', [en]);
expect(t('viewers', { count: 2 })).toBe('2 viewers');
});
});
describe('pickLanguage', () => {
it('follows the device language, exactly or by its primary language', () => {
expect(pickLanguage(['fr-FR', 'en'], ['en', 'fr'])).toBe('fr');
expect(pickLanguage(['fr-CA'], ['en', 'fr'])).toBe('fr');
expect(pickLanguage(['pt-BR', 'pt'], ['en', 'pt-BR', 'pt'])).toBe('pt-BR');
});
it('falls back to English for a missing language', () => {
expect(pickLanguage(['de-DE', 'it'], ['en', 'fr'])).toBe('en');
expect(pickLanguage([], ['en', 'fr'])).toBe('en');
});
});
+112
View File
@@ -0,0 +1,112 @@
/**
* Translation (#21), without dependencies: key lookup, plurals,
* interpolation, English fallback, language choice.
*
* Texts live in `locales/<language>.json`, at the repository root, one file
* per language, one section per application (`viewer`, `desktop`). Adding a
* language means adding a file: no code changes. The host embeds them and
* serves them to the viewer (`/locales/`), the desktop shell embeds them at
* build time.
*
* This module is pure: the desktop shell imports it as is, without React.
*/
export type Catalog = { [key: string]: string | Catalog };
export type Params = Record<string, string | number>;
export type Translate = (key: string, params?: Params) => string;
/**
* A language on offer, by its code and its name in that language, as listed
* by the host's `/locales/index.json` and the `_language` header of each
* locale file.
*/
export type AvailableLanguage = { code: string; name: string };
/** The fallback language: complete by contract, checked by `check-i18n`. */
export const FALLBACK_LANGUAGE = 'en';
/**
* A translation function for `section` (`viewer`, `desktop`), which looks in
* `catalogs` in order: the chosen language, then English. A key found
* nowhere gives an empty string, never the raw key.
*/
export function createTranslator(
language: string,
section: string,
catalogs: Catalog[],
): Translate {
const rules = pluralRules(language);
return (key, params) => {
for (const catalog of catalogs) {
const value = lookup(catalog, `${section}.${key}`);
if (value === undefined) continue;
const text = typeof value === 'string' ? value : plural(value, rules, params);
if (text !== undefined) return interpolate(text, params);
}
return '';
};
}
function lookup(catalog: Catalog, path: string): string | Catalog | undefined {
let node: string | Catalog | undefined = catalog;
for (const part of path.split('.')) {
if (node === undefined || typeof node === 'string') return undefined;
node = node[part];
}
return node;
}
/**
* A plural is an object of forms: an exact value (`"0"`), then the
* `Intl.PluralRules` category (`one`, `few`, `other`...).
*/
function plural(
forms: Catalog,
rules: Intl.PluralRules,
params: Params | undefined,
): string | undefined {
const count = params?.count;
if (typeof count !== 'number') {
return typeof forms.other === 'string' ? forms.other : undefined;
}
const exact = forms[String(count)];
if (typeof exact === 'string') return exact;
const category = forms[rules.select(count)];
if (typeof category === 'string') return category;
return typeof forms.other === 'string' ? forms.other : undefined;
}
function pluralRules(language: string): Intl.PluralRules {
try {
return new Intl.PluralRules(language);
} catch {
return new Intl.PluralRules(FALLBACK_LANGUAGE);
}
}
function interpolate(text: string, params: Params | undefined): string {
if (!params) return text;
return text.replace(/\{(\w+)\}/g, (whole, name: string) =>
name in params ? String(params[name]) : whole,
);
}
/**
* The language to show: the first of the device preferences that exists,
* exactly (`pt-BR`) or by its primary language (`fr-CA` gives `fr`),
* otherwise English.
*/
export function pickLanguage(preferences: readonly string[], available: readonly string[]): string {
const codes = available.map((code) => code.toLowerCase());
for (const preference of preferences) {
const wanted = preference.toLowerCase();
const exact = codes.indexOf(wanted);
if (exact >= 0) return available[exact] ?? FALLBACK_LANGUAGE;
const primary = wanted.split('-')[0];
const close = codes.findIndex((code) => code.split('-')[0] === primary);
if (close >= 0) return available[close] ?? FALLBACK_LANGUAGE;
}
return codes.includes(FALLBACK_LANGUAGE)
? FALLBACK_LANGUAGE
: (available[0] ?? FALLBACK_LANGUAGE);
}
+9 -8
View File
@@ -1,10 +1,11 @@
/**
* É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.
* 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.
*
* 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`).
* This module decides nothing: it notifies the session, which alone knows
* whether it is waiting, has given up or is already connected (see
* `ViewerSession.wake`).
*/
export type WakeReason = 'online' | 'network_change' | 'visible' | 'pageshow';
@@ -12,9 +13,9 @@ export type WakeReason = 'online' | 'network_change' | 'visible' | 'pageshow';
type NavigatorWithConnection = Navigator & { connection?: EventTarget };
/**
* 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.
* Attaches the listeners and returns the function that removes them. Each
* target is optional: `navigator.connection` exists neither in Safari nor in
* Firefox, and none of this exists in a test without a DOM.
*/
export function watchLifecycle(onWake: (reason: WakeReason) => void): () => void {
const cleanups: Array<() => void> = [];
+49
View File
@@ -0,0 +1,49 @@
import { describe, expect, it } from 'vitest';
import { exchangeCode, qrDetector } from './pairing';
function respond(status: number, body: unknown): typeof fetch {
return async () => new Response(JSON.stringify(body), { status });
}
describe('exchangeCode', () => {
it('returns the session path, versioned', async () => {
const outcome = await exchangeCode(
'k7m4pq',
respond(200, {
status: 'accepted',
room: 'abc234',
token: '0123456789abcdef0123456789abcdef',
}),
);
expect(outcome).toEqual({
kind: 'accepted',
path: '/r/abc234?t=0123456789abcdef0123456789abcdef&v=1',
});
});
it('tells an unknown code, an expired one, and too many attempts apart', async () => {
expect(await exchangeCode('x', respond(404, { status: 'unknown' }))).toEqual({
kind: 'unknown',
});
expect(await exchangeCode('x', respond(410, { status: 'expired' }))).toEqual({
kind: 'expired',
});
expect(
await exchangeCode('x', respond(429, { status: 'too_many_attempts', retry_after_s: 42 })),
).toEqual({ kind: 'too_many_attempts', retryAfterS: 42 });
});
it('does not throw when the network fails', async () => {
const broken: typeof fetch = async () => {
throw new TypeError('network');
};
expect(await exchangeCode('x', broken)).toEqual({ kind: 'network' });
});
});
describe('qrDetector', () => {
it('steps aside when the browser has no BarcodeDetector', () => {
expect(qrDetector()).toBeNull();
});
});
+73
View File
@@ -0,0 +1,73 @@
/**
* Pairing without a camera (#19): the short code shown by the host, exchanged
* for the room and the token. And, when the browser allows it, reading the QR
* code from the page itself.
*/
import { LINK_VERSION, type PairingResponse } from '../proto';
export type CodeOutcome =
| { kind: 'accepted'; path: string }
| { kind: 'unknown' }
| { kind: 'expired' }
| { kind: 'too_many_attempts'; retryAfterS: number }
| { kind: 'network' };
/** Exchanges a code for the session path. Never throws. */
export async function exchangeCode(
code: string,
fetchImpl: typeof fetch = fetch,
): Promise<CodeOutcome> {
let body: PairingResponse;
try {
const response = await fetchImpl('/api/code', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code }),
});
body = (await response.json()) as PairingResponse;
} catch {
return { kind: 'network' };
}
switch (body.status) {
case 'accepted':
return {
kind: 'accepted',
path: `/r/${encodeURIComponent(body.room)}?t=${encodeURIComponent(body.token)}&v=${LINK_VERSION}`,
};
case 'unknown':
return { kind: 'unknown' };
case 'expired':
return { kind: 'expired' };
case 'too_many_attempts':
return { kind: 'too_many_attempts', retryAfterS: body.retry_after_s };
default:
return { kind: 'network' };
}
}
/** The subset of the BarcodeDetector API in use. */
type Detector = {
detect(source: CanvasImageSource): Promise<Array<{ rawValue: string }>>;
};
type DetectorConstructor = new (options: { formats: string[] }) => Detector;
/**
* A QR code reader, if this browser exposes one. It also needs a camera, hence
* a secure context: a page served over HTTP on the LAN does not get one, and
* the short code takes over.
*/
export function qrDetector(): Detector | null {
const scope = globalThis as unknown as {
BarcodeDetector?: DetectorConstructor;
isSecureContext?: boolean;
navigator?: Navigator;
};
if (!scope.BarcodeDetector || !scope.isSecureContext) return null;
if (!scope.navigator?.mediaDevices?.getUserMedia) return null;
try {
return new scope.BarcodeDetector({ formats: ['qr_code'] });
} catch {
return null;
}
}
+8 -8
View File
@@ -3,9 +3,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { ViewerSession, type ViewerState } from './session';
/**
* WebSocket qui échoue immédiatement, pour éprouver la reconnexion sans réseau
* ni navigateur. Il n'ouvre jamais: `close` arrive tout de suite, exactement
* comme un hôte éteint.
* WebSocket that fails at once, to exercise reconnection without network or
* browser. It never opens: `close` arrives straight away, exactly like a host
* that is off.
*/
class FailingWebSocket {
static readonly OPEN = 1;
@@ -45,7 +45,7 @@ class StubPeerConnection {
close(): void {}
}
describe('reconnexion', () => {
describe('reconnection', () => {
beforeEach(() => {
vi.useFakeTimers();
FailingWebSocket.instances = [];
@@ -58,7 +58,7 @@ describe('reconnexion', () => {
vi.useRealTimers();
});
it('réessaie, puis abandonne avec un message réseau', async () => {
it('retries, then gives up with a network message', async () => {
const states: ViewerState[] = [];
const session = new ViewerSession({
room: 'abc234',
@@ -70,7 +70,7 @@ describe('reconnexion', () => {
});
session.start();
// Laisse passer les microtâches qui déclenchent la fermeture.
// Lets the microtasks that trigger the close run.
await vi.advanceTimersByTimeAsync(0);
await vi.advanceTimersByTimeAsync(1000);
await vi.advanceTimersByTimeAsync(2000);
@@ -87,7 +87,7 @@ describe('reconnexion', () => {
expect(FailingWebSocket.instances.length).toBeLessThanOrEqual(3);
});
it('stop() coupe la reconnexion et ne rappelle plus l’état', async () => {
it('stop() cuts reconnection and no longer reports the state', async () => {
const states: ViewerState[] = [];
const session = new ViewerSession({
room: 'abc234',
@@ -106,7 +106,7 @@ describe('reconnexion', () => {
expect(states.length).toBe(before);
});
it('refuse de démarrer deux fois après stop()', async () => {
it('refuses to start again after stop()', async () => {
const session = new ViewerSession({
room: 'abc234',
token: '0123456789abcdef0123456789abcdef',
+39 -39
View File
@@ -4,11 +4,11 @@ import type { ClientMessage, StreamSettings } from '../proto';
import { ViewerSession, type ViewerState, WAKE_MIN_INTERVAL_MS } from './session';
/**
* Reprise après changement de réseau (#39) et après veille (#42).
* Resume after a network change (#39) and after sleep (#42).
*
* Un faux hôte répond comme le vrai: `welcome` au `hello`, `answer` à l'offre,
* `settings_applied` avec SON réglage par défaut à une demande de qualité.
* Quand il est « éteint » (ou le réseau coupé), la socket se ferme aussitôt.
* A fake host answers like the real one: `welcome` to `hello`, `answer` to the
* offer, `settings_applied` with ITS default setting to a quality request.
* When it is "off" (or the network is cut), the socket closes at once.
*/
const BALANCED: StreamSettings = { quality: 'balanced', max_bitrate_kbps: 3000, max_fps: 30 };
@@ -66,19 +66,19 @@ class FakeWebSocket {
} else if (message.type === 'offer') {
this.reply({ type: 'answer', sdp: 'v=0' });
} else if (message.type === 'quality_request') {
// Comme l'hôte actuel: il renvoie ce qu'il applique, pas la demande.
// Like the current host: it sends back what it applies, not the request.
this.reply({ type: 'settings_applied', settings: BALANCED });
}
}
/** Comme un navigateur: la fermeture demandée est notifiée plus tard. */
/** Like a browser: a requested close is notified later. */
close(): void {
if (this.readyState === FakeWebSocket.CLOSED) return;
this.readyState = FakeWebSocket.CLOSING;
queueMicrotask(() => this.drop());
}
/** Coupure vue par le spectateur: réseau perdu ou hôte arrêté. */
/** Dropout as seen by the viewer: network lost or host stopped. */
drop(): void {
if (this.readyState === FakeWebSocket.CLOSED) return;
this.readyState = FakeWebSocket.CLOSED;
@@ -120,7 +120,7 @@ class FakePeerConnection extends EventTarget {
if (host.up && this.connectionState === 'new') this.setConnectionState('connected');
});
}
/** Comme le navigateur: `close()` ne déclenche aucun événement. */
/** Like the browser: `close()` fires no event. */
close(): void {
this.connectionState = 'closed';
}
@@ -156,24 +156,24 @@ function newSession(
});
}
/** Laisse passer les microtâches (ouverture, réponses de l'hôte). */
/** Lets the microtasks run (open, host replies). */
async function settle(ms = 0): Promise<void> {
await vi.advanceTimersByTimeAsync(ms);
}
function lastSocket(): FakeWebSocket {
const ws = FakeWebSocket.instances.at(-1);
if (!ws) throw new Error('aucune socket');
if (!ws) throw new Error('no socket');
return ws;
}
function lastPeer(): FakePeerConnection {
const pc = FakePeerConnection.instances.at(-1);
if (!pc) throw new Error('aucune connexion WebRTC');
if (!pc) throw new Error('no WebRTC connection');
return pc;
}
/** Coupure franche: la socket tombe, puis la connexion WebRTC passe en échec. */
/** Clean cut: the socket drops, then the WebRTC connection fails. */
function cut(): void {
host.up = false;
const pc = lastPeer();
@@ -185,12 +185,12 @@ function goOnline(): void {
fakeWindow.dispatchEvent(new Event('online'));
}
/** Va jusqu'à l'abandon, hôte injoignable. */
/** Runs until giving up, host unreachable. */
async function exhaust(): Promise<void> {
for (let i = 0; i < 10; i += 1) await settle(15_000);
}
describe('reprise après changement de réseau ou veille', () => {
describe('resume after a network change or sleep', () => {
beforeEach(() => {
vi.useFakeTimers();
host.up = false;
@@ -211,7 +211,7 @@ describe('reprise après changement de réseau ou veille', () => {
vi.useRealTimers();
});
it('Wi-Fi vers Ethernet: `online` relance tout de suite, le flux revient en moins de 5 s', async () => {
it('Wi-Fi to Ethernet: `online` restarts at once, the stream is back within 5 s', async () => {
const states: ViewerState[] = [];
host.up = true;
const session = newSession(states);
@@ -223,12 +223,12 @@ describe('reprise après changement de réseau ou veille', () => {
cut();
await settle();
expect(states.at(-1)?.kind).toBe('reconnecting');
// Le Wi-Fi est parti, les premières tentatives échouent.
// Wi-Fi is gone, the first attempts fail.
await settle(3000);
expect(states.at(-1)?.kind).toBe('reconnecting');
const sockets = FakeWebSocket.instances.length;
// L'Ethernet arrive: pas d'attente de la minuterie (4 s à ce stade).
// Ethernet arrives: no waiting for the timer (4 s at this point).
host.up = true;
goOnline();
await settle();
@@ -238,14 +238,14 @@ describe('reprise après changement de réseau ou veille', () => {
session.stop();
});
it('`change` de navigator.connection relance pendant l’attente, et compte comme une tentative', async () => {
it('`change` on navigator.connection restarts while waiting, and counts as an attempt', async () => {
const states: ViewerState[] = [];
const session = newSession(states, { maxAttempts: 6 });
session.start();
await settle();
await settle(1000);
await settle(2000);
// Trois tentatives faites, la quatrième attend 4 s.
// Three attempts made, the fourth waits 4 s.
expect(FakeWebSocket.instances).toHaveLength(3);
expect(states.at(-1)).toMatchObject({ kind: 'reconnecting', attempt: 3, delayMs: 4000 });
@@ -253,19 +253,19 @@ describe('reprise après changement de réseau ou veille', () => {
await settle();
expect(FakeWebSocket.instances).toHaveLength(4);
expect(states).toContainEqual({ kind: 'connecting', attempt: 4 });
// L'échec de cette tentative reprend le délai suivant, pas le premier.
// The failure of this attempt resumes with the next delay, not the first.
expect(states.at(-1)).toMatchObject({ kind: 'reconnecting', attempt: 4, delayMs: 8000 });
session.stop();
});
it('limite les relances à une toutes les 2 s, même si les événements pleuvent', async () => {
it('limits restarts to one every 2 s, even when events pour in', async () => {
const states: ViewerState[] = [];
const session = newSession(states);
session.start();
await settle();
expect(FakeWebSocket.instances).toHaveLength(1);
// Changement d'interface: `online` et `change` arrivent ensemble.
// Interface change: `online` and `change` arrive together.
goOnline();
connection.dispatchEvent(new Event('change'));
fakeDocument.setVisibility('visible');
@@ -286,7 +286,7 @@ describe('reprise après changement de réseau ou veille', () => {
session.stop();
});
it('ne touche pas à une session qui diffuse', async () => {
it('leaves a streaming session alone', async () => {
const states: ViewerState[] = [];
host.up = true;
const session = newSession(states);
@@ -303,7 +303,7 @@ describe('reprise après changement de réseau ou veille', () => {
session.stop();
});
it('après abandon, le retour au premier plan ouvre UNE nouvelle série qui se termine', async () => {
it('after giving up, returning to the foreground opens ONE new series that ends', async () => {
const states: ViewerState[] = [];
const session = newSession(states, { maxAttempts: 3 });
session.start();
@@ -311,12 +311,12 @@ describe('reprise après changement de réseau ou veille', () => {
expect(states.at(-1)).toMatchObject({ kind: 'failed', code: 'network' });
expect(FakeWebSocket.instances).toHaveLength(3);
// Mise en veille: rien ne se passe.
// Going to sleep: nothing happens.
fakeDocument.setVisibility('hidden');
await exhaust();
expect(FakeWebSocket.instances).toHaveLength(3);
// Réveil, hôte toujours éteint: une série de trois, puis l'échec, sans boucle.
// Wake-up, host still off: a series of three, then failure, no loop.
fakeDocument.setVisibility('visible');
await exhaust();
expect(FakeWebSocket.instances).toHaveLength(6);
@@ -326,7 +326,7 @@ describe('reprise après changement de réseau ou veille', () => {
session.stop();
});
it('après abandon, `online` relance et retrouve le flux si l’hôte est revenu', async () => {
it('after giving up, `online` restarts and gets the stream back if the host returned', async () => {
const states: ViewerState[] = [];
const session = newSession(states, { maxAttempts: 2 });
session.start();
@@ -340,7 +340,7 @@ describe('reprise après changement de réseau ou veille', () => {
session.stop();
});
it('`pageshow` relance seulement pour une page restaurée du cache', async () => {
it('`pageshow` restarts only for a page restored from the cache', async () => {
const states: ViewerState[] = [];
const session = newSession(states, { maxAttempts: 2 });
session.start();
@@ -357,7 +357,7 @@ describe('reprise après changement de réseau ou veille', () => {
session.stop();
});
it('réveil sur un transport mort en silence: reconnexion, et la fermeture de l’ancienne socket ne casse pas la neuve', async () => {
it('wake-up on a silently dead transport: reconnection, and the close of the old socket does not break the new one', async () => {
const states: ViewerState[] = [];
host.up = true;
const session = newSession(states);
@@ -365,8 +365,8 @@ describe('reprise après changement de réseau ou veille', () => {
await settle();
expect(states.at(-1)?.kind).toBe('streaming');
// L'appareil a dormi: la connexion est morte sans qu'aucun événement
// n'ait été traité, la socket se croit encore ouverte.
// The device slept: the connection died without any event being
// handled, the socket still believes it is open.
lastPeer().connectionState = 'disconnected';
fakeDocument.setVisibility('visible');
await settle();
@@ -380,7 +380,7 @@ describe('reprise après changement de réseau ou veille', () => {
session.stop();
});
it('« Réessayer » relance une série sans attendre l’intervalle, et rien après stop()', async () => {
it('"Retry" starts a series without waiting for the interval, and nothing after stop()', async () => {
const states: ViewerState[] = [];
const session = newSession(states, { maxAttempts: 2 });
session.start();
@@ -402,7 +402,7 @@ describe('reprise après changement de réseau ou veille', () => {
expect(FakeWebSocket.instances).toHaveLength(5);
});
it('stop() retire les écouteurs du système', async () => {
it('stop() removes the system listeners', async () => {
const session = newSession([], { maxAttempts: 1 });
session.start();
await exhaust();
@@ -415,7 +415,7 @@ describe('reprise après changement de réseau ou veille', () => {
});
});
describe('qualité stable après reconnexions', () => {
describe('stable quality across reconnections', () => {
beforeEach(() => {
vi.useFakeTimers();
host.up = true;
@@ -445,7 +445,7 @@ describe('qualité stable après reconnexions', () => {
expect(states.at(-1)?.kind).toBe('streaming');
}
it('trois coupures de suite gardent la qualité initiale, jamais le minimum', async () => {
it('three dropouts in a row keep the initial quality, never the minimum', async () => {
const states: ViewerState[] = [];
const session = newSession(states, { quality: SHARP });
session.start();
@@ -457,17 +457,17 @@ describe('qualité stable après reconnexions', () => {
expect(FakeWebSocket.instances).toHaveLength(4);
for (const ws of FakeWebSocket.instances) {
expect(qualityRequests(ws)).toEqual([SHARP]);
// Demandée après `welcome`, avant l'offre.
// Requested after `welcome`, before the offer.
const kinds = ws.sent.map((message) => message.type);
expect(kinds).toEqual(['hello', 'quality_request', 'offer']);
}
// La réponse de l'hôte (son réglage par défaut) n'écrase pas le choix.
// The host reply (its default setting) does not overwrite the choice.
expect(session.requestedQuality).toEqual(SHARP);
expect(session.requestedQuality).not.toEqual(SAVER);
session.stop();
});
it('le dernier choix de l’utilisateur survit aux coupures', async () => {
it('the user last choice survives dropouts', async () => {
const states: ViewerState[] = [];
const session = newSession(states);
session.start();
@@ -487,7 +487,7 @@ describe('qualité stable après reconnexions', () => {
session.stop();
});
it('sans choix, aucune demande de qualité: l’hôte garde son réglage', async () => {
it('without a choice, no quality request: the host keeps its setting', async () => {
const states: ViewerState[] = [];
const session = newSession(states);
session.start();
+67 -9
View File
@@ -1,9 +1,15 @@
import { describe, expect, it } from 'vitest';
import { parseRoomLocation, signalingUrl } from './room';
import {
isCompleteCode,
normalizeCode,
parseRoomLocation,
sessionFromScan,
signalingUrl,
} from './room';
describe('parseRoomLocation', () => {
it('extrait la room et le jeton', () => {
it('extracts the room and the token', () => {
const result = parseRoomLocation('/r/abc234', '?t=0123456789abcdef0123456789abcdef');
expect(result).toEqual({
ok: true,
@@ -11,11 +17,11 @@ describe('parseRoomLocation', () => {
});
});
it('refuse une adresse sans room', () => {
it('rejects an address without a room', () => {
expect(parseRoomLocation('/', '')).toEqual({ ok: false, reason: 'missing_room' });
});
it('distingue un jeton absent d’un jeton mal formé', () => {
it('tells a missing token from a malformed one', () => {
expect(parseRoomLocation('/r/abc234', '')).toEqual({
ok: false,
reason: 'missing_token',
@@ -26,14 +32,14 @@ describe('parseRoomLocation', () => {
});
});
it('refuse une room avec un caractère ambigu', () => {
it('rejects a room with an ambiguous character', () => {
expect(parseRoomLocation('/r/abc0o1', '?t=0123456789abcdef0123456789abcdef')).toEqual({
ok: false,
reason: 'malformed',
});
});
it('normalise une room en majuscules', () => {
it('normalises an upper case room', () => {
const result = parseRoomLocation('/r/ABC234', '?t=0123456789ABCDEF0123456789ABCDEF');
expect(result).toEqual({
ok: true,
@@ -41,17 +47,69 @@ describe('parseRoomLocation', () => {
});
});
it('ignore les segments supplémentaires', () => {
it('ignores extra segments', () => {
const result = parseRoomLocation('/r/abc234/extra', '?t=0123456789abcdef0123456789abcdef');
expect(result.ok).toBe(true);
});
});
describe('versioned link (#19)', () => {
const token = '0123456789abcdef0123456789abcdef';
it('reads a version 1 link and its fingerprint', () => {
const fp = 'ab'.repeat(32);
const result = parseRoomLocation('/r/abc234', `?t=${token}&v=1`, `#fp=${fp}`);
expect(result).toEqual({
ok: true,
value: { room: 'abc234', token, fingerprint: Array(32).fill('AB').join(':') },
});
});
it('accepts a link without version, the one of earlier releases', () => {
expect(parseRoomLocation('/r/abc234', `?t=${token}`).ok).toBe(true);
});
it('says a link comes from a newer version', () => {
expect(parseRoomLocation('/r/abc234', `?t=${token}&v=2`)).toEqual({
ok: false,
reason: 'newer_link',
});
});
it('ignores a malformed fingerprint', () => {
const result = parseRoomLocation('/r/abc234', `?t=${token}&v=1`, '#fp=zz');
expect(result).toEqual({ ok: true, value: { room: 'abc234', token } });
});
});
describe('scanned QR code', () => {
it('follows a session URL', () => {
const url = 'http://192.168.1.20:8099/r/abc234?t=0123456789abcdef0123456789abcdef&v=1';
expect(sessionFromScan(url)).toBe(url);
});
it('rejects what is not a session', () => {
expect(sessionFromScan('hello')).toBeNull();
expect(sessionFromScan('javascript:alert(1)')).toBeNull();
expect(sessionFromScan('https://example.com/')).toBeNull();
});
});
describe('short code', () => {
it('is typed as it is shown', () => {
expect(normalizeCode(' K7M 4PQ ')).toBe('k7m4pq');
expect(normalizeCode('k7m-4pq')).toBe('k7m4pq');
expect(isCompleteCode('k7m4pq')).toBe(true);
expect(isCompleteCode('k7m4p')).toBe(false);
expect(isCompleteCode('k7m4p0')).toBe(false);
});
});
describe('signalingUrl', () => {
it('suit le schéma de la page', () => {
it('follows the page scheme', () => {
expect(signalingUrl({ protocol: 'http:', host: '127.0.0.1:8099' })).toBe(
'ws://127.0.0.1:8099/ws',
);
expect(signalingUrl({ protocol: 'https:', host: 'hote.local' })).toBe('wss://hote.local/ws');
expect(signalingUrl({ protocol: 'https:', host: 'host.local' })).toBe('wss://host.local/ws');
});
});
+64 -15
View File
@@ -1,47 +1,96 @@
/**
* Lecture de la session dans l'URL.
* Reading the session from the URL.
*
* Forme attendue: `/r/<room>?t=<jeton>`. Les deux valeurs sont validées ici
* plutôt que dans les composants, pour qu'un test puisse les couvrir et qu'une
* URL mal formée produise un message clair au lieu d'une session vide.
* Expected form: `/r/<room>?t=<token>&v=<version>`, followed over HTTPS by
* `#fp=<fingerprint>` (#19). Values are validated here rather than in the
* components, so that a test can cover them and a malformed URL gives a clear
* message instead of an empty session.
*/
import { LINK_VERSION } from '../proto';
export type RoomLocation = {
room: string;
token: string;
/** SHA-256 fingerprint of the certificate, as hex pairs, over HTTPS. */
fingerprint?: string;
};
export type RoomLocationResult =
| { ok: true; value: RoomLocation }
| { ok: false; reason: 'missing_room' | 'missing_token' | 'malformed' };
| { ok: false; reason: 'missing_room' | 'missing_token' | 'malformed' | 'newer_link' };
/** Six caractères, alphabet sans ambiguïté, aligné sur `RoomId` côté Rust. */
/** Six characters, unambiguous alphabet, aligned with `RoomId` on the Rust side. */
const ROOM_PATTERN = /^[2-9a-hjkmnp-z]{6}$/;
/** Jeton hexadécimal de 128 bits. */
/** 128-bit hex token. */
const TOKEN_PATTERN = /^[0-9a-f]{32}$/;
export function parseRoomLocation(pathname: string, search: string): RoomLocationResult {
/** SHA-256 fingerprint: 64 hex digits. */
const FINGERPRINT_PATTERN = /^[0-9a-f]{64}$/;
export function parseRoomLocation(pathname: string, search: string, hash = ''): RoomLocationResult {
const segments = pathname.split('/').filter(Boolean);
// Deux formes acceptées: `/r/<room>` et `/<room>`. Le préfixe `r` évite de
// confondre une room avec un chemin d'asset servi par le même serveur.
// Two accepted forms: `/r/<room>` and `/<room>`. The `r` prefix avoids
// mistaking a room for an asset path served by the same server.
const raw = segments[0] === 'r' ? segments[1] : segments[0];
if (!raw) {
return { ok: false, reason: 'missing_room' };
}
// L'hôte normalise en minuscules; on fait pareil pour qu'une URL recopiée à
// la main fonctionne malgré une majuscule.
// The host normalises to lower case; so does this, so that a URL copied by
// hand works despite a capital letter.
const room = raw.toLowerCase();
const token = (new URLSearchParams(search).get('t') ?? '').toLowerCase();
const params = new URLSearchParams(search);
// Without `v`, it is a link from 0.4 or earlier: same format as version
// 1. A newer version says so, instead of being misread.
const version = Number(params.get('v') ?? '1');
if (!Number.isInteger(version) || version < 1) {
return { ok: false, reason: 'malformed' };
}
if (version > LINK_VERSION) {
return { ok: false, reason: 'newer_link' };
}
const token = (params.get('t') ?? '').toLowerCase();
if (!token) {
return { ok: false, reason: 'missing_token' };
}
if (!ROOM_PATTERN.test(room) || !TOKEN_PATTERN.test(token)) {
return { ok: false, reason: 'malformed' };
}
return { ok: true, value: { room, token } };
const fp = new URLSearchParams(hash.replace(/^#/, '')).get('fp')?.toLowerCase();
const value: RoomLocation = { room, token };
if (fp && FINGERPRINT_PATTERN.test(fp)) {
value.fingerprint = fp.match(/../g)?.join(':').toUpperCase();
}
return { ok: true, value };
}
/** URL du canal de signalement, qui suit le schéma de la page. */
/**
* The path to open for a scanned QR code, or `null` if it does not carry a
* rustscreen session. Only `http` and `https` are followed: a QR code can
* contain anything.
*/
export function sessionFromScan(text: string): string | null {
let url: URL;
try {
url = new URL(text.trim());
} catch {
return null;
}
if (url.protocol !== 'http:' && url.protocol !== 'https:') return null;
const parsed = parseRoomLocation(url.pathname, url.search, url.hash);
return parsed.ok ? url.href : null;
}
/** Short code typed by hand: six characters of the room alphabet. */
export function normalizeCode(input: string): string {
return input.replace(/[\s-]/g, '').toLowerCase();
}
export function isCompleteCode(code: string): boolean {
return ROOM_PATTERN.test(code);
}
/** URL of the signalling channel, which follows the page scheme. */
export function signalingUrl(location: { protocol: string; host: string }): string {
const scheme = location.protocol === 'https:' ? 'wss' : 'ws';
return `${scheme}://${location.host}/ws`;
+77
View File
@@ -0,0 +1,77 @@
import { describe, expect, it } from 'vitest';
import {
displayedArea,
nextRotation,
readMirror,
readRotation,
rotatedBox,
saveMirror,
} from './rotation';
function memory(initial: Record<string, string> = {}) {
const values = new Map(Object.entries(initial));
return {
values,
getItem: (k: string) => values.get(k) ?? null,
setItem: (k: string, v: string) => void values.set(k, v),
removeItem: (k: string) => void values.delete(k),
};
}
describe('rotation (#30)', () => {
it('makes a full turn in steps of 90 degrees', () => {
expect(nextRotation(0)).toBe(90);
expect(nextRotation(270)).toBe(0);
});
it('swaps the box width and height on a quarter turn', () => {
expect(rotatedBox(1000, 600, 90)).toMatchObject({ width: 600, height: 1000 });
expect(rotatedBox(1000, 600, 180)).toMatchObject({ width: 1000, height: 600 });
expect(rotatedBox(1000, 600, 270).transform).toContain('rotate(270deg)');
});
it('keeps the whole picture and fills the stage in portrait', () => {
// Tablet in portrait (800×1280), shared screen at 1920×1080.
const stage = { width: 800, height: 1280 };
const video = { width: 1920, height: 1080 };
const upright = displayedArea(stage, video, 0);
const turned = displayedArea(stage, video, 90);
// Without rotation, the picture (800×450) fills barely more than a third of the stage.
expect((upright.width * upright.height) / (800 * 1280)).toBeLessThan(0.36);
// Turned, it fits whole and takes the full available height.
expect(turned.width).toBeLessThanOrEqual(800);
expect(turned.height).toBeLessThanOrEqual(1280);
expect(Math.max(turned.width / 800, turned.height / 1280)).toBeCloseTo(1);
// Turned (720×1280), it fills 90 % of it: the bars stay thin.
expect((turned.width * turned.height) / (800 * 1280)).toBeGreaterThan(0.89);
});
it('ignores an invalid stored value', () => {
expect(readRotation(memory({ 'rustscreen.rotation': '45' }))).toBe(0);
expect(readRotation(memory({ 'rustscreen.rotation': '270' }))).toBe(270);
});
});
describe('mirror (#29)', () => {
it('flips the picture in screen space, after the rotation', () => {
expect(rotatedBox(1000, 600, 90, true).transform).toBe(
'translate(-50%, -50%) scaleX(-1) rotate(90deg)',
);
expect(rotatedBox(1000, 600, 0, false).transform).not.toContain('scaleX');
});
it('is kept by the device', () => {
const storage = memory();
expect(readMirror(storage)).toBe(false);
saveMirror(true, storage);
expect(readMirror(storage)).toBe(true);
});
it('migrates the choice stored before #83', () => {
const storage = memory({ 'rustscreen.miroir': '1' });
expect(readMirror(storage)).toBe(true);
expect(storage.values.get('rustscreen.mirror')).toBe('1');
expect(storage.values.has('rustscreen.miroir')).toBe(false);
});
});
+96
View File
@@ -0,0 +1,96 @@
/**
* Rotation of the stream in the viewer (#30), in steps of 90 degrees.
*
* A video turned a quarter turn swaps its width and height: the element is
* therefore given the box of the turned stage, then rotated.
* `object-fit: contain` keeps the whole picture in that box, cropping nothing
* and with no bars wider than needed. Everything happens in the page: no
* message to the host, no reconnection.
*/
import { browserStorage, type KeyValueStore, readMigrated } from './storage';
export type Rotation = 0 | 90 | 180 | 270;
const KEY = 'rustscreen.rotation';
export function nextRotation(rotation: Rotation): Rotation {
return ((rotation + 90) % 360) as Rotation;
}
/**
* Size and transform of the video element in a `width`×`height` stage.
*
* The mirror (#29) applies in screen space, after the rotation: text reads
* backwards for whoever looks at the screen, and the right way round in a
* teleprompter's reflection, whatever the tablet's orientation.
*/
export function rotatedBox(
width: number,
height: number,
rotation: Rotation,
mirror = false,
): { width: number; height: number; transform: string } {
const quarter = rotation === 90 || rotation === 270;
return {
width: quarter ? height : width,
height: quarter ? width : height,
transform: `translate(-50%, -50%)${mirror ? ' scaleX(-1)' : ''} rotate(${rotation}deg)`,
};
}
const MIRROR_KEY = 'rustscreen.mirror';
/** Key before #83. */
const LEGACY_MIRROR_KEY = 'rustscreen.miroir';
export function readMirror(storage: KeyValueStore | null = browserStorage()): boolean {
try {
return storage !== null && readMigrated(storage, MIRROR_KEY, LEGACY_MIRROR_KEY) === '1';
} catch {
return false;
}
}
export function saveMirror(
mirror: boolean,
storage: KeyValueStore | null = browserStorage(),
): void {
try {
storage?.setItem(MIRROR_KEY, mirror ? '1' : '0');
} catch {
// Private browsing: the choice holds for the page only.
}
}
type Size = { width: number; height: number };
/**
* Part of the stage the picture fills, to check that no rotation wastes
* space: it is what `contain` shows in the turned box.
*/
export function displayedArea(stage: Size, video: Size, rotation: Rotation): Size {
const quarter = rotation === 90 || rotation === 270;
const [vw, vh] = quarter ? [video.height, video.width] : [video.width, video.height];
const scale = Math.min(stage.width / vw, stage.height / vh);
return { width: vw * scale, height: vh * scale };
}
export function readRotation(storage: KeyValueStore | null = browserStorage()): Rotation {
try {
const value = Number(storage?.getItem(KEY));
if (value === 90 || value === 180 || value === 270) return value;
} catch {
// Storage denied: no rotation.
}
return 0;
}
export function saveRotation(
rotation: Rotation,
storage: KeyValueStore | null = browserStorage(),
): void {
try {
storage?.setItem(KEY, String(rotation));
} catch {
// Same.
}
}
+21 -15
View File
@@ -1,29 +1,30 @@
import { describe, expect, it } from 'vitest';
import { createTranslator } from './i18n';
import { backoffDelay, isRetryable, isTerminal, messageFor } from './session';
describe('backoffDelay', () => {
it('double à chaque tentative puis plafonne', () => {
it('doubles at each attempt then caps', () => {
expect(backoffDelay(1)).toBe(1000);
expect(backoffDelay(2)).toBe(2000);
expect(backoffDelay(3)).toBe(4000);
expect(backoffDelay(10)).toBe(15_000);
});
it('ne produit jamais de délai absurde sur une entrée nulle', () => {
it('never gives an absurd delay on a zero input', () => {
expect(backoffDelay(0)).toBe(1000);
expect(backoffDelay(-5)).toBe(1000);
});
});
describe('isTerminal', () => {
it('reconnaît les refus définitifs', () => {
it('recognises final refusals', () => {
for (const code of ['bad_token', 'bad_version', 'room_full']) {
expect(isTerminal(code)).toBe(true);
}
});
it('laisse une chance aux erreurs transitoires', () => {
it('gives transient errors a chance', () => {
for (const code of ['network', 'internal', 'protocol_violation']) {
expect(isTerminal(code)).toBe(false);
}
@@ -31,12 +32,12 @@ describe('isTerminal', () => {
});
describe('isRetryable', () => {
it('propose une nouvelle série après un abandon réseau ou une erreur passagère', () => {
it('offers a new series after a network give-up or a passing error', () => {
expect(isRetryable('network')).toBe(true);
expect(isRetryable('internal')).toBe(true);
});
it('ne relance ni un refus de principe ni une erreur de protocole', () => {
it('restarts neither a refusal on principle nor a protocol error', () => {
for (const code of [
'bad_token',
'bad_version',
@@ -50,16 +51,21 @@ describe('isRetryable', () => {
});
describe('messageFor', () => {
it('après abandon, dit de rescanner le QR code si l’hôte a redémarré', () => {
expect(messageFor('network')).toContain('redémarré');
expect(messageFor('network')).toContain('QR code');
const t = createTranslator('fr', 'viewer', [
{
viewer: {
networkFallback: 'Connexion perdue.',
errors: { bad_token: 'Jeton refusé.', token_expired: 'Jeton expiré.' },
},
},
]);
it('translates a known code', () => {
expect(messageFor('bad_token', t)).toBe('Jeton refusé.');
expect(messageFor('token_expired', t)).not.toBe(messageFor('bad_token', t));
});
it('traduit un code connu', () => {
expect(messageFor('bad_token')).toContain('jeton');
});
it('retombe sur un message réseau pour un code inconnu', () => {
expect(messageFor('quelque_chose_de_nouveau')).toContain('Connexion perdue');
it('falls back to the network message for an unknown code (newer host)', () => {
expect(messageFor('something_new', t)).toBe('Connexion perdue.');
});
});
+77 -71
View File
@@ -1,20 +1,21 @@
/**
* Cycle de vie d'une session spectateur: WebSocket de signalement, offre
* WebRTC, affichage, reconnexion.
* Lifecycle of a viewer session: signalling WebSocket, WebRTC offer, display,
* reconnection.
*
* Le composant React ne connaît que deux choses: un état à afficher et un flux
* à poser dans une balise vidéo. Toute la mécanique vit ici, ce qui la rend
* testable et évite les états incohérents du genre « connecté sans image ».
* The React component knows only two things: a state to show and a stream to
* put in a video element. All the machinery lives here, which makes it
* testable and avoids inconsistent states such as "connected without picture".
*/
import { PROTOCOL_VERSION } from '../proto';
import type { ClientMessage, DeviceInfo, ServerMessage, StreamSettings } from '../proto';
import { errorMessages, strings } from '../strings';
import type { Translate } from './i18n';
import { deviceId } from './device';
import { type WakeReason, watchLifecycle } from './lifecycle';
export type ViewerErrorCode =
| 'bad_token'
| 'token_expired'
| 'bad_version'
| 'room_full'
| 'protocol_violation'
@@ -29,7 +30,7 @@ export type ViewerState =
| { kind: 'negotiating' }
| { kind: 'streaming' }
| { kind: 'reconnecting'; attempt: number; delayMs: number }
| { kind: 'failed'; code: ViewerErrorCode; message: string }
| { kind: 'failed'; code: ViewerErrorCode }
| { kind: 'ended'; reason: string };
export type SessionOptions = {
@@ -39,19 +40,20 @@ export type SessionOptions = {
deviceName?: string;
maxAttempts?: number;
/**
* Qualité demandée par le spectateur. Elle est renvoyée après chaque
* `welcome`, reprises comprises: une coupure ne la dégrade jamais.
* Quality requested by the viewer. It is sent again after every
* `welcome`, resumes included: a dropout never degrades it.
*/
quality?: StreamSettings;
/** Écoute réseau, visibilité et `pageshow` (défaut: oui). */
/** Listens to network, visibility and `pageshow` (default: yes). */
watchLifecycle?: boolean;
onState: (state: ViewerState) => void;
onStream: (stream: MediaStream | null) => void;
};
/** Codes après lesquels réessayer ne sert à rien: l'hôte refuse par principe. */
/** Codes after which retrying is useless: the host refuses on principle. */
const TERMINAL_CODES: ReadonlySet<string> = new Set([
'bad_token',
'token_expired',
'bad_version',
'room_full',
'kicked',
@@ -59,8 +61,8 @@ const TERMINAL_CODES: ReadonlySet<string> = new Set([
]);
/**
* Codes après lesquels une nouvelle série de tentatives peut aider: le réseau
* ou l'hôte ont pu revenir. Le bouton « Réessayer » et le réveil s'en servent.
* Codes after which a new series of attempts can help: the network or the
* host may have come back. The "Retry" button and wake-ups use them.
*/
const RETRYABLE_CODES: ReadonlySet<string> = new Set(['network', 'internal']);
@@ -68,30 +70,34 @@ const DEFAULT_MAX_ATTEMPTS = 6;
const MAX_BACKOFF_MS = 15_000;
/**
* Écart minimal entre deux relances provoquées par le système. Un passage du
* Wi-Fi à l'Ethernet émet `online` et `change` presque ensemble, un réveil
* émet `visibilitychange` et parfois `pageshow`: une seule relance suffit.
* Minimum gap between two restarts triggered by the system. Switching from
* Wi-Fi to Ethernet fires `online` and `change` almost together, a wake-up
* fires `visibilitychange` and sometimes `pageshow`: one restart is enough.
*/
export const WAKE_MIN_INTERVAL_MS = 2000;
/** Délai avant la n-ième tentative, plafonné. Fonction pure, testée. */
/** Delay before the n-th attempt, capped. Pure function, tested. */
export function backoffDelay(attempt: number): number {
const safe = Math.max(1, attempt);
return Math.min(1000 * 2 ** (safe - 1), MAX_BACKOFF_MS);
}
/** Un code d'erreur d'hôte est-il définitif ? Fonction pure, testée. */
/** Is a host error code final? Pure function, tested. */
export function isTerminal(code: string): boolean {
return TERMINAL_CODES.has(code);
}
/** Une nouvelle série de tentatives peut-elle aider ? Fonction pure, testée. */
/** Can a new series of attempts help? Pure function, tested. */
export function isRetryable(code: string): boolean {
return RETRYABLE_CODES.has(code);
}
export function messageFor(code: string): string {
return errorMessages[code] ?? strings.networkFallback;
/**
* The message for an error code, in the language of `t`. A code this viewer
* does not know (newer host) becomes the generic network message.
*/
export function messageFor(code: string, t: Translate): string {
return t(`errors.${code}`) || t('networkFallback');
}
export class ViewerSession {
@@ -99,11 +105,11 @@ export class ViewerSession {
private pc: RTCPeerConnection | null = null;
private retryTimer: ReturnType<typeof setTimeout> | null = null;
private attempt = 0;
/** Arrêt définitif: démontage, refus de principe, fin de session. */
/** Final stop: unmount, refusal on principle, end of session. */
private stopped = false;
/**
* Abandon provisoire: tentatives épuisées ou erreur transitoire de l'hôte.
* Le bouton « Réessayer » ou un réveil du système relance une série.
* Temporary give-up: attempts exhausted or transient host error. The
* "Retry" button or a system wake-up starts a new series.
*/
private halted = false;
private streaming = false;
@@ -123,11 +129,7 @@ export class ViewerSession {
this.started = true;
if (typeof RTCPeerConnection === 'undefined') {
this.stopped = true;
this.options.onState({
kind: 'failed',
code: 'unsupported',
message: strings.unsupported,
});
this.options.onState({ kind: 'failed', code: 'unsupported' });
return;
}
if (this.options.watchLifecycle !== false) {
@@ -136,7 +138,7 @@ export class ViewerSession {
this.connect();
}
/** Idempotent: appelable depuis un nettoyage React, un unmount, un bouton. */
/** Idempotent: callable from a React cleanup, an unmount, a button. */
stop(): void {
this.stopped = true;
this.unwatch?.();
@@ -147,9 +149,9 @@ export class ViewerSession {
}
/**
* Bouton « Réessayer »: après un abandon, relance une série complète de
* tentatives, sans recharger la page. Renvoie `false` si la session est
* arrêtée pour de bon (refus de principe, fin): il faut alors en créer une.
* "Retry" button: after a give-up, starts a full series of attempts again,
* without reloading the page. Returns `false` if the session is stopped for
* good (refusal on principle, end): a new one must then be created.
*/
retry(): boolean {
if (this.stopped || !this.started) return false;
@@ -158,16 +160,16 @@ export class ViewerSession {
}
/**
* Le système signale que le réseau ou l'appareil est revenu. Relance tout
* de suite si la session attend (minuterie de reprise), a abandonné, ou
* tient un transport déjà mort; ne touche pas à une session qui marche.
* The system signals that the network or the device is back. Restarts at
* once if the session is waiting (retry timer), has given up, or holds an
* already dead transport; leaves a working session alone.
*
* Garde-fous contre une boucle: au plus une relance par
* `WAKE_MIN_INTERVAL_MS`, une relance pendant l'attente compte comme une
* tentative, et après un abandon une relance ouvre UNE série, qui finit de
* nouveau sur l'état d'échec si l'hôte reste absent.
* Guards against a loop: at most one restart per `WAKE_MIN_INTERVAL_MS`, a
* restart while waiting counts as an attempt, and after a give-up a restart
* opens ONE series, which ends again in the failed state if the host stays
* away.
*
* Renvoie `true` si une connexion a été relancée.
* Returns `true` if a connection was restarted.
*/
wake(_reason?: WakeReason): boolean {
if (this.stopped || !this.started) return false;
@@ -198,15 +200,15 @@ export class ViewerSession {
}
/**
* Change la qualité demandée. Elle est envoyée tout de suite si le
* signalement est ouvert, et renvoyée à chaque reprise.
* Changes the requested quality. It is sent at once if signalling is open,
* and sent again at every resume.
*/
setQuality(settings: StreamSettings): void {
this.quality = settings;
this.send({ type: 'quality_request', settings } as ClientMessage);
}
/** Qualité que le spectateur demande, telle qu'il l'a choisie. */
/** Quality the viewer requests, as they chose it. */
get requestedQuality(): StreamSettings | null {
return this.quality;
}
@@ -225,7 +227,7 @@ export class ViewerSession {
}
}
/** Un signalement fermé ou une connexion WebRTC tombée, sans reprise prévue. */
/** Closed signalling or a dropped WebRTC connection, with no resume planned. */
private transportDead(): boolean {
const ws = this.ws;
if (!ws || ws.readyState === WebSocket.CLOSING || ws.readyState === WebSocket.CLOSED) {
@@ -249,9 +251,9 @@ export class ViewerSession {
}
this.ws = ws;
// Chaque écouteur vérifie qu'il parle encore à la socket courante: la
// fermeture d'une ancienne socket arrive après coup, et sans ce garde
// elle couperait la connexion neuve qui vient de la remplacer.
// Each listener checks it still talks to the current socket: the close
// of an old socket arrives afterwards, and without this guard it would
// cut the new connection that just replaced it.
const current = () => !this.stopped && this.ws === ws;
ws.addEventListener('open', () => {
if (!current()) return;
@@ -266,7 +268,7 @@ export class ViewerSession {
this.onTransportLost();
});
ws.addEventListener('error', () => {
// `close` suit toujours: on y traite la reconnexion.
// `close` always follows: reconnection is handled there.
});
}
@@ -292,14 +294,14 @@ export class ViewerSession {
try {
message = JSON.parse(raw) as ServerMessage;
} catch {
this.fail('protocol_violation', messageFor('protocol_violation'));
this.fail('protocol_violation');
return;
}
switch (message.type) {
case 'welcome':
// La qualité choisie survit aux reprises: l'hôte repart de son
// réglage par défaut à chaque session, on la lui redemande.
// The chosen quality survives resumes: the host starts again from
// its default setting at every session, so it is asked again.
if (this.quality) {
this.send({ type: 'quality_request', settings: this.quality } as ClientMessage);
}
@@ -310,14 +312,14 @@ export class ViewerSession {
try {
await this.pc.setRemoteDescription({ type: 'answer', sdp: message.sdp });
} catch {
this.fail('protocol_violation', messageFor('protocol_violation'));
this.fail('protocol_violation');
}
break;
case 'error':
if (isTerminal(message.code)) {
this.fail(message.code as ViewerErrorCode, messageFor(message.code));
this.fail(message.code as ViewerErrorCode);
} else {
this.fail('internal', messageFor(message.code));
this.fail('internal');
}
break;
case 'bye':
@@ -325,14 +327,14 @@ export class ViewerSession {
this.options.onState({ kind: 'ended', reason: message.reason });
break;
case 'settings_applied':
// Ce que l'hôte applique ne remplace pas ce que le spectateur
// demande: sinon le réglage par défaut renvoyé après une reprise
// écraserait le choix de l'utilisateur.
// What the host applies does not replace what the viewer
// requests: otherwise the default setting sent back after a
// resume would overwrite the user's choice.
break;
case 'source_changed':
case 'ice_candidate':
// Le flux est remplacé côté hôte; rien à faire ici avant l'issue
// du changement de source à chaud.
// The stream is replaced on the host side; nothing to do here
// before the issue on hot source switching.
break;
default:
break;
@@ -369,7 +371,7 @@ export class ViewerSession {
if (!current()) return;
const sdp = pc.localDescription?.sdp;
if (!sdp) {
this.fail('protocol_violation', messageFor('protocol_violation'));
this.fail('protocol_violation');
return;
}
this.send({ type: 'offer', sdp } as ClientMessage);
@@ -397,7 +399,7 @@ export class ViewerSession {
private scheduleRetry(): void {
if (this.stopped) return;
if (this.attempt >= this.maxAttempts) {
this.fail('network', messageFor('network'));
this.fail('network');
return;
}
const delayMs = backoffDelay(this.attempt);
@@ -408,32 +410,32 @@ export class ViewerSession {
}, delayMs);
}
private fail(code: ViewerErrorCode, message: string): void {
private fail(code: ViewerErrorCode): void {
if (isRetryable(code)) {
// Abandon provisoire: les écouteurs de réveil restent branchés pour
// relancer une série quand le réseau ou l'appareil revient.
// Temporary give-up: the wake listeners stay attached to start a
// new series when the network or the device comes back.
this.halted = true;
this.streaming = false;
this.clearRetryTimer();
this.teardown();
this.options.onStream(null);
this.emit({ kind: 'failed', code, message });
this.emit({ kind: 'failed', code });
return;
}
this.stop();
this.options.onState({ kind: 'failed', code, message });
this.options.onState({ kind: 'failed', code });
}
private teardown(): void {
if (this.ws) {
const ws = this.ws;
// Remis à zéro avant `close()`: les écouteurs voient alors une
// socket qui n'est plus la courante et ignorent sa fermeture.
// Reset before `close()`: the listeners then see a socket that is no
// longer the current one and ignore its close.
this.ws = null;
try {
ws.close();
} catch {
// Une socket déjà fermée n'est pas une erreur.
// An already closed socket is not an error.
}
}
if (this.pc) {
@@ -447,7 +449,7 @@ export class ViewerSession {
if (!this.stopped) this.options.onState(state);
}
/** Statistiques de la piste entrante, pour l'affichage. */
/** Statistics of the incoming track, for display. */
async stats(): Promise<VideoStats | null> {
const pc = this.pc;
if (!pc) return null;
@@ -480,6 +482,10 @@ export type VideoStats = {
height: number;
};
/**
* Name shown to the host for this device. The values are data sent in the
* `hello` and displayed by the host, kept as they were.
*/
function defaultDeviceName(): string {
const ua = navigator.userAgent;
if (/iPad|Tablet/i.test(ua)) return 'Tablette';
+51
View File
@@ -0,0 +1,51 @@
/**
* Choices kept by the browser in `localStorage`.
*
* Storage may be denied (private browsing): every caller then falls back to
* a value that lasts for the page only.
*
* Keys used to be French (`rustscreen.appareil`, `rustscreen.miroir`...).
* They were renamed to English, and a device that visited before keeps its
* choices: `readMigrated` reads the old key once, writes the new one and
* removes the old one. This matters most for the device id, which the host
* uses to recognise a device it already admitted or banned.
*/
export type KeyValueStore = Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>;
/** `window.localStorage`, or `null` when the browser denies it. */
export function browserStorage(): Storage | null {
try {
return window.localStorage;
} catch {
return null;
}
}
/**
* The value under `key`, or else the one under `legacyKey`, moved to `key`.
*
* `translate` maps an old value to the new one, `null` dropping it. The old
* key is removed only once the new one is written: a failed write keeps the
* old value for the next visit. May throw if reading is denied.
*/
export function readMigrated(
storage: KeyValueStore,
key: string,
legacyKey: string,
translate: (legacy: string) => string | null = (legacy) => legacy,
): string | null {
const current = storage.getItem(key);
if (current !== null) return current;
const legacy = storage.getItem(legacyKey);
if (legacy === null) return null;
const value = translate(legacy);
if (value === null) return null;
try {
storage.setItem(key, value);
storage.removeItem(legacyKey);
} catch {
// Write denied: the value still holds for this page.
}
return value;
}
+68
View File
@@ -0,0 +1,68 @@
import { describe, expect, it } from 'vitest';
import type { KeyValueStore } from './storage';
import { nextTheme, readTheme, saveTheme } from './theme';
function memory(): KeyValueStore {
const values = new Map<string, string>();
return {
getItem: (key) => values.get(key) ?? null,
setItem: (key, value) => {
values.set(key, value);
},
removeItem: (key) => {
values.delete(key);
},
};
}
describe('theme (#28)', () => {
it('follows the system on first visit', () => {
expect(readTheme(memory())).toBe('system');
expect(readTheme(null)).toBe('system');
});
it('keeps the device choice', () => {
const storage = memory();
saveTheme('dark', storage);
expect(readTheme(storage)).toBe('dark');
});
it('ignores an unknown value or a denied storage', () => {
const storage = memory();
storage.setItem('rustscreen.theme', 'violet');
expect(readTheme(storage)).toBe('system');
const denied = {
getItem: () => {
throw new Error('denied');
},
setItem: () => {
throw new Error('denied');
},
removeItem: () => {
throw new Error('denied');
},
};
expect(readTheme(denied)).toBe('system');
expect(() => saveTheme('light', denied)).not.toThrow();
});
it('cycles through the three values', () => {
expect(nextTheme('system')).toBe('light');
expect(nextTheme('light')).toBe('dark');
expect(nextTheme('dark')).toBe('system');
});
it('translates and rewrites a value stored before #83', () => {
for (const [legacy, theme] of [
['systeme', 'system'],
['clair', 'light'],
['sombre', 'dark'],
] as const) {
const storage = memory();
storage.setItem('rustscreen.theme', legacy);
expect(readTheme(storage)).toBe(theme);
expect(storage.getItem('rustscreen.theme')).toBe(theme);
}
});
});
+53
View File
@@ -0,0 +1,53 @@
/**
* Viewer theme (#28): the device's by default, light or dark on request. The
* choice is kept by the device, not by the host: two tablets may prefer
* opposite themes.
*
* The value is also the `data-theme` attribute of the root element, which
* the style sheet reads.
*/
import { browserStorage, type KeyValueStore } from './storage';
export type Theme = 'system' | 'light' | 'dark';
const KEY = 'rustscreen.theme';
const ORDER: readonly Theme[] = ['system', 'light', 'dark'];
/** Values stored before #83, under the same key. */
const LEGACY_VALUES: Readonly<Record<string, Theme>> = {
systeme: 'system',
clair: 'light',
sombre: 'dark',
};
export function readTheme(storage: KeyValueStore | null = browserStorage()): Theme {
try {
const raw = storage?.getItem(KEY);
if (raw && (ORDER as readonly string[]).includes(raw)) return raw as Theme;
const migrated = raw ? LEGACY_VALUES[raw] : undefined;
if (migrated) {
saveTheme(migrated, storage);
return migrated;
}
} catch {
// Storage denied (private browsing): the system theme.
}
return 'system';
}
export function saveTheme(theme: Theme, storage: KeyValueStore | null = browserStorage()): void {
try {
storage?.setItem(KEY, theme);
} catch {
// Same: the choice holds for the page only.
}
}
/** The next theme, for a single button that cycles through all three. */
export function nextTheme(theme: Theme): Theme {
return ORDER[(ORDER.indexOf(theme) + 1) % ORDER.length] ?? 'system';
}
/** Sets the theme on the root element: the style sheet does the rest. */
export function applyTheme(theme: Theme, root: HTMLElement = document.documentElement): void {
root.dataset.theme = theme;
}
+26
View File
@@ -0,0 +1,26 @@
import { useEffect, useState } from 'react';
/**
* True for `delayMs` after the last mouse move, touch or key press. The timer
* is restarted only when needed: a moving mouse does not cause one render per
* pixel.
*/
export function useActivity(delayMs: number, activeInitially = true): boolean {
const [active, setActive] = useState(activeInitially);
useEffect(() => {
let timer: ReturnType<typeof setTimeout> | undefined;
const wake = () => {
setActive(true);
clearTimeout(timer);
timer = setTimeout(() => setActive(false), delayMs);
};
const events = ['pointermove', 'pointerdown', 'keydown', 'touchstart'] as const;
for (const e of events) window.addEventListener(e, wake, { passive: true });
timer = setTimeout(() => setActive(false), delayMs);
return () => {
clearTimeout(timer);
for (const e of events) window.removeEventListener(e, wake);
};
}, [delayMs]);
return active;
}
+29 -7
View File
@@ -1,13 +1,35 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { App } from './App';
import { I18nProvider, initialLanguage, loadCatalogs, loadLanguages } from './i18n';
import { applyTheme, readTheme } from './lib/theme';
import './styles.css';
const root = document.getElementById('root');
if (!root) throw new Error('élément racine absent');
// Before the first render: no white flash on a device set to dark.
applyTheme(readTheme());
createRoot(root).render(
<StrictMode>
<App />
</StrictMode>,
);
const root = document.getElementById('root');
if (!root) throw new Error('root element missing');
async function start(element: HTMLElement) {
const languages = await loadLanguages();
const language = initialLanguage(languages);
const catalogs = await loadCatalogs(language);
if (catalogs.length === 0) {
// Without texts, the interface cannot say anything: this one message
// stays hard-coded, in both complete languages, for lack of better.
element.textContent =
'rustscreen: textes de l’interface introuvables, rechargez la page. / Interface texts not found, reload the page.';
return;
}
document.documentElement.lang = language;
createRoot(element).render(
<StrictMode>
<I18nProvider initial={{ language, catalogs }} languages={languages}>
<App />
</I18nProvider>
</StrictMode>,
);
}
void start(root);
+1 -1
View File
@@ -5,6 +5,6 @@ import type { SessionToken } from "./SessionToken";
import type { StreamSettings } from "./StreamSettings";
/**
* Ce que le spectateur envoie à l'hôte.
* What the viewer sends to the host.
*/
export type ClientMessage = { "type": "hello", version: number, room: RoomId, token: SessionToken, device: DeviceInfo, } | { "type": "offer", sdp: string, } | { "type": "ice_candidate", candidate: string, sdp_mid: string | null, sdp_mline_index: number | null, } | { "type": "quality_request", settings: StreamSettings, } | { "type": "bye" };
+1 -1
View File
@@ -3,6 +3,6 @@ import type { DeviceId } from "./DeviceId";
export type DeviceInfo = { id: DeviceId,
/**
* Nom affiché côté hôte, modifiable par l'un ou l'autre.
* Name shown on the host side, editable by either side.
*/
name: string, user_agent: string | null, platform: string | null, };
+1 -1
View File
@@ -1,3 +1,3 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type ErrorCode = "bad_version" | "bad_token" | "room_full" | "source_unavailable" | "protocol_violation" | "internal" | "kicked" | "share_ended";
export type ErrorCode = "bad_version" | "bad_token" | "token_expired" | "room_full" | "source_unavailable" | "protocol_violation" | "internal" | "kicked" | "share_ended";
Loaded 100 of 211 files, more files were not shown because too many files have changed in this diff. Show more