refactor: code en anglais, rustscreen ouvre l'application de bureau
CI / Formatting, tests and builds (push) Successful in 3m19s
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>
This commit is contained in:
1 parent
73d1ef905a
commit
0c24b2b5d2
206 files changed
+11903
-10839
No files matched your search
+62
-63
@@ -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@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,87 +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
|
||||
# Les tests `export_bindings` écrivent les types TypeScript: ils
|
||||
# tournent ici, avec le reste, et l'étape « types à jour » ne fait
|
||||
# plus que comparer. Une seconde invocation de cargo, aux features
|
||||
# différentes, recompilait la moitié du workspace (34 s, #78).
|
||||
# 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: Le binaire démarre
|
||||
- name: The binary starts
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# La chaîne ne se contente pas de tester : elle vérifie que le binaire
|
||||
# démarre, parce qu'un produit qui ne démarre pas passe tous les tests
|
||||
# unitaires. Les tests d'intégration l'ont déjà compilé.
|
||||
"$CARGO_TARGET_DIR/debug/rustscreen" --version
|
||||
# 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: Binaire de publication
|
||||
# Sur main seulement: toute la pile en release coûte plus d'une minute,
|
||||
# et la release la refait de toute façon (#78).
|
||||
- name: Release binary
|
||||
# On main only: the whole stack in release costs more than a minute,
|
||||
# and the release workflow rebuilds it anyway (#78).
|
||||
if: github.event_name == 'push'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cargo build --release -p rs-session --bin rustscreen
|
||||
"$CARGO_TARGET_DIR/release/rustscreen" --version
|
||||
cargo build --release -p rs-session --bin rustscreen-cli
|
||||
"$CARGO_TARGET_DIR/release/rustscreen-cli" --version
|
||||
|
||||
- name: Le protocole TypeScript est à jour
|
||||
- name: The TypeScript protocol is up to date
|
||||
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.
|
||||
# Écrits par l'étape « Tests »: il ne reste qu'à comparer. `status`
|
||||
# plutôt que `diff`: un type nouveau, jamais commité, compte aussi.
|
||||
ecarts=$(git status --porcelain -- apps/viewer/src/proto apps/desktop/src/bindings)
|
||||
if [ -n "$ecarts" ]; then
|
||||
echo "$ecarts" >&2
|
||||
echo "types TypeScript générés pas à jour : lancer make proto et commiter" >&2
|
||||
# The protocol types are generated from Rust. A gap between the
|
||||
# repository and the generated output means the viewer compiles
|
||||
# against a stale protocol, which only shows in production.
|
||||
# Written by the "Tests" step: all that is left is to compare.
|
||||
# `status` rather than `diff`: a new type, never committed, counts too.
|
||||
drift=$(git status --porcelain -- apps/viewer/src/proto apps/desktop/src/bindings)
|
||||
if [ -n "$drift" ]; then
|
||||
echo "$drift" >&2
|
||||
echo "generated TypeScript types are out of date: run make proto and commit" >&2
|
||||
exit 1
|
||||
fi
|
||||
@@ -1,14 +1,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@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"
|
||||
@@ -19,15 +19,27 @@ une coupure ou une veille, tourne l'image et suit le thème, coque desktop Tauri
|
||||
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), encore en français.
|
||||
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
|
||||
@@ -51,7 +63,7 @@ capture ni le serveur.
|
||||
- **Aucun texte en dur dans un composant.** Les textes vivent dans `locales/<langue>.json`, une
|
||||
section par application, et passent par `t('clé')`. L'anglais est la langue de repli et doit
|
||||
être complet, le français aussi. `npm run lint` (viewer) et `pnpm lint` (coque) lancent
|
||||
`scripts/verifier-i18n.mjs`, qui refuse une clé absente de l'anglais et un texte en dur. Ajouter
|
||||
`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.
|
||||
@@ -105,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
|
||||
@@ -126,27 +138,28 @@ 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 -- --codec vp9 --une-fenetre
|
||||
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).
|
||||
@@ -157,13 +170,14 @@ Pour essayer la coque ou un navigateur sans rien ouvrir sur le bureau, préfére
|
||||
apparaît dans la vraie barre. Elle se vérifie par D-Bus (`org.kde.StatusNotifierWatcher`, menu
|
||||
`com.canonical.dbusmenu`), et son menu se pilote par `Event`.
|
||||
|
||||
Le journal JSON (`~/.local/state/rustscreen/logs`) nomme les étapes d'une session: `portail_accorde`,
|
||||
`format_capture`, `session_ouverte`, `candidat_ice_retenu`, `premiere_image`, `changement_qualite`,
|
||||
`deconnexion` (avec `cause`), `capture_revoquee`, et côté hôte `partage_demarre`, `partage_termine`,
|
||||
`partage_interrompu`, `spectateur_deconnecte`, `changement_resolution`, `veille_inhibee`,
|
||||
`veille_relachee`, `reveil_detecte`, `capture_relancee`, `adresse_changee`, `reglages_modifies`,
|
||||
`acces_regenere`, `code_accepte`, `code_refuse`. Ne jamais y écrire un titre de fenêtre ni une
|
||||
image (ADR 0008).
|
||||
Le 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:
|
||||
|
||||
@@ -209,9 +223,9 @@ session a révélés. Le détail est dans `docs/capture-wayland.md`; l'essentiel
|
||||
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 (`lire_memfd`). Les ignorer donnait un écran
|
||||
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`).
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -89,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,11 +4,11 @@
|
||||
"version": "0.4.0",
|
||||
"type": "module",
|
||||
"packageManager": "pnpm@12.15.0",
|
||||
"description": "Coque desktop de rustscreen: choisir la source, voir les spectateurs, couper.",
|
||||
"description": "rustscreen desktop shell: pick the source, see the viewers, stop.",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc --noEmit && vite build",
|
||||
"lint": "biome lint src && node ../../scripts/verifier-i18n.mjs apps/desktop/src desktop",
|
||||
"lint": "biome lint src && node ../../scripts/check-i18n.mjs apps/desktop/src desktop",
|
||||
"format": "biome format --write src",
|
||||
"test": "vitest run"
|
||||
},
|
||||
|
||||
@@ -1,37 +1,43 @@
|
||||
[package]
|
||||
name = "rustscreen-desktop"
|
||||
description = "Coque desktop de rustscreen: choisir ce qu'on partage, voir qui regarde, couper."
|
||||
description = "rustscreen desktop shell: choose what to share, see who is watching, stop."
|
||||
version = "0.4.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" }
|
||||
# `tray-icon`: icône de barre système (#22); `image-png`: ses icônes.
|
||||
# `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]
|
||||
# Essai de chargement de libayatana-appindicator avant de créer l'icône (#22).
|
||||
# Trial load of libayatana-appindicator before creating the icon (#22).
|
||||
libloading = "0.8.9"
|
||||
|
||||
[build-dependencies]
|
||||
|
||||
@@ -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"]
|
||||
}
|
||||
@@ -1,308 +0,0 @@
|
||||
//! Icône de barre système et menu de session (#22).
|
||||
//!
|
||||
//! L'icône dit l'état réel: elle suit le même `etat` que la fenêtre, au même
|
||||
//! moment, donc en bien moins d'une seconde. Le menu permet de démarrer (la
|
||||
//! dernière source choisie), d'arrêter, d'ouvrir la fenêtre et de quitter, sans
|
||||
//! que la fenêtre soit ouverte.
|
||||
//!
|
||||
//! Sous Linux, l'icône passe par StatusNotifierItem (libayatana-appindicator,
|
||||
//! chargée à l'exécution). GNOME sans l'extension AppIndicator n'affiche rien:
|
||||
//! [`disponible`] le détecte, et la fermeture de la fenêtre se replie alors sur
|
||||
//! une simple réduction, pour ne jamais cacher un partage sans moyen de le
|
||||
//! retrouver.
|
||||
//!
|
||||
//! Les textes viennent de l'interface (`traduire_barre`), dans sa langue
|
||||
//! (#21): les traductions vivent dans `locales/`, pas ici. Le français
|
||||
//! ci-dessous ne sert qu'avant le premier envoi.
|
||||
|
||||
use std::sync::Mutex;
|
||||
|
||||
use rs_session::{Etat, Phase};
|
||||
use serde::Deserialize;
|
||||
use tauri::image::Image;
|
||||
use tauri::menu::{Menu, MenuItem, PredefinedMenuItem};
|
||||
use tauri::tray::{MouseButton, MouseButtonState, TrayIcon, TrayIconBuilder, TrayIconEvent};
|
||||
use tauri::{AppHandle, Manager, Runtime};
|
||||
|
||||
const ICONE: &[u8] = include_bytes!("../icons/icon.png");
|
||||
|
||||
/// Ce que le menu propose; l'identifiant revient dans l'événement de clic.
|
||||
pub const OUVRIR: &str = "ouvrir";
|
||||
pub const DEMARRER: &str = "demarrer";
|
||||
pub const ARRETER: &str = "arreter";
|
||||
pub const QUITTER: &str = "quitter";
|
||||
|
||||
/// Les formes du statut en direct: Rust ne connaît pas les règles de pluriel
|
||||
/// de chaque langue, l'interface lui donne celles de 0, de 1 et du reste.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct Formes {
|
||||
pub zero: String,
|
||||
pub one: String,
|
||||
/// Avec `{count}` à remplacer.
|
||||
pub other: String,
|
||||
}
|
||||
|
||||
/// Les textes du menu, traduits par l'interface.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct TextesBarre {
|
||||
pub aucun: String,
|
||||
pub demarrage: String,
|
||||
pub direct: Formes,
|
||||
pub ouvrir: String,
|
||||
pub demarrer: String,
|
||||
pub reprendre: String,
|
||||
pub arreter: String,
|
||||
pub quitter: String,
|
||||
}
|
||||
|
||||
impl Default for TextesBarre {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
aucun: "Aucun partage".into(),
|
||||
demarrage: "Démarrage du partage…".into(),
|
||||
direct: Formes {
|
||||
zero: "En direct, personne ne regarde".into(),
|
||||
one: "En direct, 1 spectateur".into(),
|
||||
other: "En direct, {count} spectateurs".into(),
|
||||
},
|
||||
ouvrir: "Ouvrir rustscreen".into(),
|
||||
demarrer: "Démarrer le partage…".into(),
|
||||
reprendre: "Reprendre le dernier partage".into(),
|
||||
arreter: "Arrêter le partage".into(),
|
||||
quitter: "Quitter".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TextesBarre {
|
||||
fn statut(&self, etat: &Etat) -> String {
|
||||
match etat.phase {
|
||||
Phase::Arrete => self.aucun.clone(),
|
||||
Phase::Demarrage => self.demarrage.clone(),
|
||||
Phase::EnCours => match etat.partage.as_ref().map_or(0, |p| p.appareils.len()) {
|
||||
0 => self.direct.zero.clone(),
|
||||
1 => self.direct.one.clone(),
|
||||
n => self.direct.other.replace("{count}", &n.to_string()),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Barre<R: Runtime> {
|
||||
icone: TrayIcon<R>,
|
||||
statut: MenuItem<R>,
|
||||
ouvrir: MenuItem<R>,
|
||||
demarrer: MenuItem<R>,
|
||||
arreter: MenuItem<R>,
|
||||
quitter: MenuItem<R>,
|
||||
repos: Image<'static>,
|
||||
direct: Image<'static>,
|
||||
textes: Mutex<TextesBarre>,
|
||||
}
|
||||
|
||||
impl<R: Runtime> Barre<R> {
|
||||
/// Crée l'icône et son menu. `None` quand ce bureau n'a pas de barre
|
||||
/// système: l'application vit alors dans sa fenêtre seulement.
|
||||
pub fn creer(
|
||||
app: &AppHandle<R>,
|
||||
au_clic: impl Fn(&AppHandle<R>, &str) + Send + Sync + 'static,
|
||||
) -> Option<Self> {
|
||||
if !disponible() {
|
||||
tracing::info!("pas de barre système sur ce bureau: fenêtre seule");
|
||||
return None;
|
||||
}
|
||||
let construire = || -> tauri::Result<Self> {
|
||||
let repos = Image::from_bytes(ICONE)?.to_owned();
|
||||
let direct = avec_pastille(&repos);
|
||||
let textes = TextesBarre::default();
|
||||
let statut = MenuItem::with_id(app, "statut", &textes.aucun, false, None::<&str>)?;
|
||||
let ouvrir = MenuItem::with_id(app, OUVRIR, &textes.ouvrir, true, None::<&str>)?;
|
||||
let demarrer = MenuItem::with_id(app, DEMARRER, &textes.demarrer, true, None::<&str>)?;
|
||||
let arreter = MenuItem::with_id(app, ARRETER, &textes.arreter, false, None::<&str>)?;
|
||||
let quitter = MenuItem::with_id(app, QUITTER, &textes.quitter, true, None::<&str>)?;
|
||||
let menu = Menu::with_items(
|
||||
app,
|
||||
&[
|
||||
&statut,
|
||||
&PredefinedMenuItem::separator(app)?,
|
||||
&ouvrir,
|
||||
&demarrer,
|
||||
&arreter,
|
||||
&PredefinedMenuItem::separator(app)?,
|
||||
&quitter,
|
||||
],
|
||||
)?;
|
||||
let icone = TrayIconBuilder::with_id("rustscreen")
|
||||
.icon(repos.clone())
|
||||
.tooltip(format!("rustscreen: {}", textes.aucun))
|
||||
.menu(&menu)
|
||||
.show_menu_on_left_click(false)
|
||||
.on_menu_event(move |app, evenement| au_clic(app, evenement.id().as_ref()))
|
||||
.on_tray_icon_event(|icone, evenement| {
|
||||
// Windows et macOS: un clic gauche rouvre la fenêtre. Sous
|
||||
// Linux, StatusNotifierItem n'envoie que le menu.
|
||||
if let TrayIconEvent::Click {
|
||||
button: MouseButton::Left,
|
||||
button_state: MouseButtonState::Up,
|
||||
..
|
||||
} = evenement
|
||||
{
|
||||
montrer(icone.app_handle());
|
||||
}
|
||||
})
|
||||
.build(app)?;
|
||||
Ok(Self {
|
||||
icone,
|
||||
statut,
|
||||
ouvrir,
|
||||
demarrer,
|
||||
arreter,
|
||||
quitter,
|
||||
repos,
|
||||
direct,
|
||||
textes: Mutex::new(textes),
|
||||
})
|
||||
};
|
||||
match construire() {
|
||||
Ok(barre) => Some(barre),
|
||||
Err(erreur) => {
|
||||
tracing::warn!(%erreur, "icône de barre système impossible");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Change la langue du menu; l'appelant redessine avec [`Barre::suivre`].
|
||||
pub fn traduire(&self, textes: TextesBarre) {
|
||||
let resultat = (|| -> tauri::Result<()> {
|
||||
self.ouvrir.set_text(&textes.ouvrir)?;
|
||||
self.arreter.set_text(&textes.arreter)?;
|
||||
self.quitter.set_text(&textes.quitter)?;
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(erreur) = resultat {
|
||||
tracing::warn!(%erreur, "menu de la barre système non traduit");
|
||||
}
|
||||
*self.textes.lock().unwrap_or_else(|e| e.into_inner()) = textes;
|
||||
}
|
||||
|
||||
/// Met l'icône, l'infobulle et le menu à l'image de l'état.
|
||||
pub fn suivre(&self, etat: &Etat, derniere_source: bool) {
|
||||
let textes = self
|
||||
.textes
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.clone();
|
||||
let texte = textes.statut(etat);
|
||||
let icone = if etat.phase == Phase::EnCours {
|
||||
&self.direct
|
||||
} else {
|
||||
&self.repos
|
||||
};
|
||||
let resultat = (|| -> tauri::Result<()> {
|
||||
self.icone.set_icon(Some(icone.clone()))?;
|
||||
self.icone
|
||||
.set_tooltip(Some(format!("rustscreen: {texte}")))?;
|
||||
self.statut.set_text(&texte)?;
|
||||
// Démarrer depuis le menu relance la dernière source; sans elle,
|
||||
// le menu ouvre la fenêtre pour en choisir une.
|
||||
self.demarrer.set_text(if derniere_source {
|
||||
&textes.reprendre
|
||||
} else {
|
||||
&textes.demarrer
|
||||
})?;
|
||||
self.demarrer.set_enabled(etat.phase == Phase::Arrete)?;
|
||||
self.arreter.set_enabled(etat.phase != Phase::Arrete)?;
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(erreur) = resultat {
|
||||
tracing::warn!(%erreur, "barre système non mise à jour");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Rouvre la fenêtre principale, cachée ou réduite.
|
||||
pub fn montrer<R: Runtime>(app: &AppHandle<R>) {
|
||||
if let Some(fenetre) = app.get_webview_window("main") {
|
||||
let _ = fenetre.unminimize();
|
||||
let _ = fenetre.show();
|
||||
let _ = fenetre.set_focus();
|
||||
}
|
||||
}
|
||||
|
||||
/// Une barre système existe-t-elle? Sous Linux, il faut un hôte
|
||||
/// StatusNotifierItem sur le bus de session et la bibliothèque qui y parle.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn disponible() -> bool {
|
||||
let bibliotheque = ["libayatana-appindicator3.so.1", "libappindicator3.so.1"]
|
||||
.iter()
|
||||
.any(|nom| bibliotheque_presente(nom));
|
||||
bibliotheque && hote_status_notifier()
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
fn disponible() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Le chargeur dynamique sait-il ouvrir cette bibliothèque? tray-icon panique
|
||||
/// sinon, au lieu de rendre une erreur. Chercher le fichier ne suffit pas: un
|
||||
/// binaire construit par Nix ne lit pas le cache du système, il faut essayer
|
||||
/// le même chargement que lui.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn bibliotheque_presente(nom: &str) -> bool {
|
||||
// SAFETY: c'est la bibliothèque que tray-icon chargera de toute façon
|
||||
// juste après, par le même chemin de recherche; ses constructeurs
|
||||
// (enregistrement de types GObject) sont faits pour être exécutés une
|
||||
// fois chargée, et la garder chargée évite un second passage.
|
||||
match unsafe { libloading::Library::new(nom) } {
|
||||
Ok(bibliotheque) => {
|
||||
std::mem::forget(bibliotheque);
|
||||
true
|
||||
}
|
||||
Err(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// `org.kde.StatusNotifierWatcher` a-t-il un propriétaire sur le bus de
|
||||
/// session? C'est lui qui affiche les icônes (KDE, Ubuntu, GNOME avec
|
||||
/// l'extension AppIndicator).
|
||||
#[cfg(target_os = "linux")]
|
||||
fn hote_status_notifier() -> bool {
|
||||
std::process::Command::new("busctl")
|
||||
.args([
|
||||
"--user",
|
||||
"call",
|
||||
"org.freedesktop.DBus",
|
||||
"/org/freedesktop/DBus",
|
||||
"org.freedesktop.DBus",
|
||||
"NameHasOwner",
|
||||
"s",
|
||||
"org.kde.StatusNotifierWatcher",
|
||||
])
|
||||
.output()
|
||||
.is_ok_and(|sortie| String::from_utf8_lossy(&sortie.stdout).trim() == "b true")
|
||||
}
|
||||
|
||||
/// L'icône « en direct »: la même, avec une pastille rouge en bas à droite,
|
||||
/// lisible même à 16 pixels.
|
||||
fn avec_pastille(base: &Image<'_>) -> Image<'static> {
|
||||
let (w, h) = (base.width(), base.height());
|
||||
let mut rgba = base.rgba().to_vec();
|
||||
let rayon = w.min(h) as f32 * 0.22;
|
||||
let (cx, cy) = (w as f32 - rayon - 1.0, h as f32 - rayon - 1.0);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let d = ((x as f32 + 0.5 - cx).powi(2) + (y as f32 + 0.5 - cy).powi(2)).sqrt();
|
||||
let i = ((y * w + x) * 4) as usize;
|
||||
if d <= rayon {
|
||||
rgba[i..i + 4].copy_from_slice(&[0xdc, 0x26, 0x26, 0xff]);
|
||||
} else if d <= rayon + w as f32 * 0.03 {
|
||||
// Liseré blanc: la pastille se détache sur une barre sombre
|
||||
// comme sur une claire.
|
||||
rgba[i..i + 4].copy_from_slice(&[0xff, 0xff, 0xff, 0xff]);
|
||||
}
|
||||
}
|
||||
}
|
||||
Image::new_owned(rgba, w, h)
|
||||
}
|
||||
+198
-142
@@ -1,269 +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 barre;
|
||||
mod tray;
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use rs_session::{
|
||||
Application, Config, Etat, Hote, InterfaceProposee, Phase, SourceChoisie, SourceProposee,
|
||||
Surcharges,
|
||||
Config, Host, HostState, InterfaceOption, Overrides, Phase, SettingsOutcome, SourceChoice,
|
||||
SourceOption,
|
||||
};
|
||||
use rs_store::{Fermeture, Refus, Reglages};
|
||||
use rs_store::{CloseAction, Rejection, Settings};
|
||||
use tauri::{Emitter, Manager, RunEvent, State, WindowEvent};
|
||||
|
||||
/// La dernière source démarrée, pour que le menu de la barre système puisse
|
||||
/// relancer un partage sans ouvrir la fenêtre.
|
||||
/// The last started source, so that the system tray menu can restart a share
|
||||
/// without opening the window.
|
||||
#[derive(Default)]
|
||||
struct Derniere(Mutex<Option<SourceChoisie>>);
|
||||
struct LastSource(Mutex<Option<SourceChoice>>);
|
||||
|
||||
/// L'icône de barre système, si ce bureau en a une: sans elle, cacher la
|
||||
/// fenêtre rendrait l'application introuvable.
|
||||
struct AvecBarre(Option<Arc<barre::Barre<tauri::Wry>>>);
|
||||
/// 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 AvecBarre {
|
||||
fn presente(&self) -> bool {
|
||||
impl MaybeTray {
|
||||
fn present(&self) -> bool {
|
||||
self.0.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
fn derniere_connue(app: &tauri::AppHandle) -> bool {
|
||||
app.state::<Derniere>()
|
||||
fn last_source_known(app: &tauri::AppHandle) -> bool {
|
||||
app.state::<LastSource>()
|
||||
.0
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.is_some()
|
||||
}
|
||||
|
||||
const FILTRE: &str = "rustscreen_desktop=info,rs_session=info,rs_signaling=info,rs_rtc=info,\
|
||||
// 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>,
|
||||
derniere: State<'_, Derniere>,
|
||||
choix: SourceChoisie,
|
||||
async fn start(
|
||||
host: State<'_, Host>,
|
||||
last: State<'_, LastSource>,
|
||||
choice: SourceChoice,
|
||||
) -> Result<(), String> {
|
||||
*derniere.0.lock().unwrap_or_else(|e| e.into_inner()) = Some(choix.clone());
|
||||
hote.demarrer(choix).await
|
||||
*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 regenerer_acces(hote: State<'_, Hote>) -> bool {
|
||||
hote.regenerer_acces()
|
||||
fn regenerate_access(host: State<'_, Host>) -> bool {
|
||||
host.regenerate_access()
|
||||
}
|
||||
|
||||
/// Les textes du menu de la barre système, dans la langue de l'interface.
|
||||
/// The texts of the system tray menu, in the language of the interface.
|
||||
#[tauri::command]
|
||||
fn traduire_barre(
|
||||
fn translate_tray(
|
||||
app: tauri::AppHandle,
|
||||
hote: State<'_, Hote>,
|
||||
barre: State<'_, AvecBarre>,
|
||||
textes: barre::TextesBarre,
|
||||
host: State<'_, Host>,
|
||||
tray: State<'_, MaybeTray>,
|
||||
texts: tray::TrayTexts,
|
||||
) {
|
||||
if let Some(barre) = &barre.0 {
|
||||
barre.traduire(textes);
|
||||
barre.suivre(&hote.etat(), derniere_connue(&app));
|
||||
if let Some(tray) = &tray.0 {
|
||||
tray.translate(texts);
|
||||
tray.follow(&host.state(), last_source_known(&app));
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn reglages(hote: State<'_, Hote>) -> Reglages {
|
||||
hote.reglages()
|
||||
fn settings(host: State<'_, Host>) -> Settings {
|
||||
host.settings()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn modifier_reglages(
|
||||
hote: State<'_, Hote>,
|
||||
reglages: Reglages,
|
||||
) -> Result<Application, Vec<Refus>> {
|
||||
hote.modifier_reglages(reglages).await
|
||||
async fn update_settings(
|
||||
host: State<'_, Host>,
|
||||
settings: Settings,
|
||||
) -> Result<SettingsOutcome, Vec<Rejection>> {
|
||||
host.update_settings(settings).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn interfaces(hote: State<'_, Hote>) -> Vec<InterfaceProposee> {
|
||||
hote.interfaces()
|
||||
fn interfaces(host: State<'_, Host>) -> Vec<InterfaceOption> {
|
||||
host.interfaces()
|
||||
}
|
||||
|
||||
/// É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).
|
||||
/// Writes the diagnostics archive to the download folder and returns its
|
||||
/// path: the user sends it themselves (ADR 0008).
|
||||
#[tauri::command]
|
||||
async fn exporter_diagnostics(hote: State<'_, Hote>) -> Result<String, String> {
|
||||
let hote = hote.inner().clone();
|
||||
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)
|
||||
}
|
||||
|
||||
/// Un clic dans le menu de la barre système.
|
||||
fn au_clic_barre(app: &tauri::AppHandle, id: &str) {
|
||||
let hote = app.state::<Hote>().inner().clone();
|
||||
/// 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 {
|
||||
barre::OUVRIR => barre::montrer(app),
|
||||
barre::DEMARRER => {
|
||||
let derniere = app
|
||||
.state::<Derniere>()
|
||||
tray::OPEN => tray::show(app),
|
||||
tray::START => {
|
||||
let last = app
|
||||
.state::<LastSource>()
|
||||
.0
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.clone();
|
||||
match derniere {
|
||||
Some(choix) => {
|
||||
match last {
|
||||
Some(choice) => {
|
||||
tauri::async_runtime::spawn(async move {
|
||||
// L'échec s'affiche dans la fenêtre, par l'état.
|
||||
let _ = hote.demarrer(choix).await;
|
||||
// The failure shows in the window, through the state.
|
||||
let _ = host.start(choice).await;
|
||||
});
|
||||
}
|
||||
None => barre::montrer(app),
|
||||
None => tray::show(app),
|
||||
}
|
||||
}
|
||||
barre::ARRETER => {
|
||||
tauri::async_runtime::spawn(async move { hote.arreter().await });
|
||||
tray::STOP => {
|
||||
tauri::async_runtime::spawn(async move { host.stop().await });
|
||||
}
|
||||
barre::QUITTER => app.exit(0),
|
||||
tray::QUIT => request_quit(app),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let journal = rs_diag::initialiser(rs_diag::dossier_journaux().as_deref(), FILTRE);
|
||||
let executable = std::env::current_exe().ok();
|
||||
/// 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";
|
||||
|
||||
let hote = tauri::async_runtime::block_on(Hote::nouveau(Config {
|
||||
/// Quit, or ask first if a share is running (#43): a reflex gesture must not
|
||||
/// cut a presentation short. The window comes back and asks the question; the
|
||||
/// `quit` command concludes.
|
||||
fn request_quit(app: &tauri::AppHandle) {
|
||||
let host = app.state::<Host>();
|
||||
if host.state().phase == Phase::Stopped || !host.settings().confirm_quit {
|
||||
app.exit(0);
|
||||
return;
|
||||
}
|
||||
tray::show(app);
|
||||
if let Err(error) = app.emit("confirm-quit", ()) {
|
||||
tracing::warn!(%error, "quit confirmation not requested: quitting");
|
||||
app.exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Answer to the confirmation: quit, and stop asking if so wished.
|
||||
#[tauri::command]
|
||||
async fn quit(
|
||||
app: tauri::AppHandle,
|
||||
host: State<'_, Host>,
|
||||
dont_ask_again: bool,
|
||||
) -> Result<(), Vec<Rejection>> {
|
||||
if dont_ask_again {
|
||||
let mut settings = host.settings();
|
||||
settings.confirm_quit = false;
|
||||
host.update_settings(settings).await?;
|
||||
}
|
||||
app.exit(0);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let log = rs_diag::init(rs_diag::log_dir().as_deref(), FILTER);
|
||||
// Autostart relaunches this binary. An AppImage runs from a temporary
|
||||
// mount: its file is what must be relaunched.
|
||||
let executable = std::env::var_os("APPIMAGE")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| std::env::current_exe().ok());
|
||||
let autostarted = std::env::args().any(|a| a == AUTOSTARTED || a == AUTOSTARTED_LEGACY);
|
||||
|
||||
let host = tauri::async_runtime::block_on(Host::new(Config {
|
||||
version: env!("CARGO_PKG_VERSION").into(),
|
||||
viewer_dir: std::env::var_os("RUSTSCREEN_VIEWER").map(PathBuf::from),
|
||||
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(Derniere::default())
|
||||
.manage(host.clone())
|
||||
.manage(LastSource::default())
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
etat,
|
||||
state,
|
||||
sources,
|
||||
demarrer,
|
||||
arreter,
|
||||
deconnecter,
|
||||
regenerer_acces,
|
||||
traduire_barre,
|
||||
reglages,
|
||||
modifier_reglages,
|
||||
start,
|
||||
stop,
|
||||
disconnect,
|
||||
regenerate_access,
|
||||
translate_tray,
|
||||
quit,
|
||||
settings,
|
||||
update_settings,
|
||||
interfaces,
|
||||
exporter_diagnostics,
|
||||
export_diagnostics,
|
||||
])
|
||||
.setup(move |app| {
|
||||
let barre = barre::Barre::creer(app.handle(), au_clic_barre).map(Arc::new);
|
||||
app.manage(AvecBarre(barre.clone()));
|
||||
// L'état part vers l'interface et vers l'icône à chaque changement,
|
||||
// complet: l'icône suit l'état réel au même instant que la fenêtre.
|
||||
let poignee = app.handle().clone();
|
||||
let mut abonne = hote.abonner();
|
||||
if let Some(barre) = &barre {
|
||||
barre.suivre(&abonne.borrow(), false);
|
||||
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 Some(barre) = &barre {
|
||||
barre.suivre(&etat, derniere_connue(&poignee));
|
||||
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(erreur) = poignee.emit("etat", etat) {
|
||||
tracing::warn!(%erreur, "état non transmis à l'interface");
|
||||
if let Err(error) = handle.emit("state", state) {
|
||||
tracing::warn!(%error, "state not sent to the interface");
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
})
|
||||
.on_window_event(|fenetre, evenement| {
|
||||
if let WindowEvent::CloseRequested { api, .. } = evenement {
|
||||
let app = fenetre.app_handle();
|
||||
let hote = app.state::<Hote>();
|
||||
if hote.reglages().fermeture == Fermeture::Quitter {
|
||||
.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;
|
||||
}
|
||||
// Fermer ne coupe pas un partage (#22): la fenêtre se cache
|
||||
// dans la barre système. Sans barre, elle se réduit pendant un
|
||||
// partage, et ferme l'application sinon.
|
||||
if app.state::<AvecBarre>().presente() {
|
||||
// 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 _ = fenetre.hide();
|
||||
} else if hote.etat().phase != Phase::Arrete {
|
||||
let _ = window.hide();
|
||||
} else if host.state().phase != Phase::Stopped {
|
||||
api.prevent_close();
|
||||
let _ = fenetre.minimize();
|
||||
let _ = window.minimize();
|
||||
}
|
||||
}
|
||||
})
|
||||
.build(tauri::generate_context!())
|
||||
.expect("application Tauri");
|
||||
.expect("Tauri application");
|
||||
|
||||
application.run(move |app, evenement| {
|
||||
// Quitter arrête le partage proprement: session portail fermée, veille
|
||||
// relâchée, spectateurs prévenus.
|
||||
if let RunEvent::Exit = evenement {
|
||||
let hote = app.state::<Hote>().inner().clone();
|
||||
tauri::async_runtime::block_on(hote.arreter());
|
||||
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);
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -15,7 +15,8 @@
|
||||
"width": 1100,
|
||||
"height": 760,
|
||||
"minWidth": 800,
|
||||
"minHeight": 560
|
||||
"minHeight": 560,
|
||||
"visible": false
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
|
||||
+149
-127
@@ -1,190 +1,212 @@
|
||||
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 { I18nProvider, langueEffective, useI18n } from './i18n';
|
||||
import type { Hote } from './lib/hote';
|
||||
import { actions, cle, statut, textesBarre } from './lib/vue';
|
||||
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';
|
||||
|
||||
/**
|
||||
* La langue vient des réglages de l'hôte, ou du bureau. La changer retraduit
|
||||
* l'interface et le menu de la barre système au rendu suivant (#21).
|
||||
* 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({ hote }: { hote: Hote }) {
|
||||
const [reglage, setReglage] = useState<string | null>(null);
|
||||
export function App({ host }: { host: Host }) {
|
||||
const [setting, setSetting] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
hote.reglages().then((r) => setReglage(r.langue));
|
||||
}, [hote]);
|
||||
const langue = langueEffective(reglage, navigator.languages ?? [navigator.language]);
|
||||
host.settings().then((s) => setSetting(s.language));
|
||||
}, [host]);
|
||||
const language = effectiveLanguage(setting, navigator.languages ?? [navigator.language]);
|
||||
return (
|
||||
<I18nProvider langue={langue}>
|
||||
<Interface hote={hote} onLangue={setReglage} />
|
||||
<I18nProvider language={language}>
|
||||
<Shell host={host} onLanguage={setSetting} />
|
||||
</I18nProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function Interface({ hote, onLangue }: { hote: Hote; onLangue: (code: string | null) => void }) {
|
||||
const { t, langue } = useI18n();
|
||||
const [etat, setEtat] = useState<Etat | null>(null);
|
||||
const [sources, setSources] = useState<SourceProposee[] | null>(null);
|
||||
const [selection, setSelection] = useState<SourceChoisie | null>(null);
|
||||
const [envoi, setEnvoi] = useState(false);
|
||||
const [reglagesOuverts, setReglagesOuverts] = useState(false);
|
||||
const [theme, setTheme] = useState<Theme>('systeme');
|
||||
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');
|
||||
|
||||
// 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 state comes from the host, always complete: subscribe before reading,
|
||||
// so as not to miss a change in between.
|
||||
useEffect(() => {
|
||||
let arreter: (() => void) | undefined;
|
||||
let fini = false;
|
||||
hote.ecouter(setEtat).then((stop) => {
|
||||
if (fini) stop();
|
||||
else arreter = stop;
|
||||
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]);
|
||||
|
||||
// Le menu de la barre système est dessiné par Rust: il reçoit ses textes
|
||||
// dans la langue de l'interface.
|
||||
// The system tray menu is drawn by Rust: it receives its texts in the
|
||||
// language of the interface.
|
||||
useEffect(() => {
|
||||
document.documentElement.lang = langue;
|
||||
hote.traduireBarre(textesBarre(t)).catch(() => undefined);
|
||||
}, [hote, t, langue]);
|
||||
document.documentElement.lang = language;
|
||||
host.translateTray(trayTexts(t)).catch(() => undefined);
|
||||
}, [host, t, language]);
|
||||
|
||||
const actualiser = useCallback(() => {
|
||||
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'>{t('titre')}</div>;
|
||||
if (!state) {
|
||||
return <div className='loading'>{t('title')}</div>;
|
||||
}
|
||||
|
||||
const boutons = actions(etat, selection, envoi);
|
||||
const etiquette = statut(etat, t);
|
||||
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>{t('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 ? t('veille') : t('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)}>
|
||||
{t('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))}
|
||||
onNouveauCode={() => envoyer(() => hote.regenererAcces())}
|
||||
{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 ? t('attenteBureau') : t('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))}
|
||||
>
|
||||
{t('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()}
|
||||
>
|
||||
{t('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())}
|
||||
>
|
||||
{t('arreter')}
|
||||
{t('stop')}
|
||||
</button>
|
||||
)}
|
||||
</footer>
|
||||
|
||||
{reglagesOuverts && (
|
||||
<Reglages
|
||||
hote={hote}
|
||||
demarrageAuto={etat.capacites.demarrage_auto}
|
||||
onFermer={() => setReglagesOuverts(false)}
|
||||
onEnregistre={(r) => {
|
||||
setTheme(r.theme);
|
||||
onLangue(r.langue);
|
||||
{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);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
@@ -192,29 +214,29 @@ function Interface({ hote, onLangue }: { hote: Hote; onLangue: (code: string | n
|
||||
);
|
||||
}
|
||||
|
||||
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>{t('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>{t('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>{t('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, };
|
||||
@@ -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, };
|
||||
@@ -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>, };
|
||||
@@ -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, };
|
||||
@@ -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, };
|
||||
@@ -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, };
|
||||
@@ -0,0 +1,6 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
/**
|
||||
* What closing the desktop application window does (#22).
|
||||
*/
|
||||
export type CloseAction = "tray" | "quit";
|
||||
@@ -1,7 +1,7 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
/**
|
||||
* Codec vidéo des partages (#67). VP9 garde la même qualité pour moins de
|
||||
* débit, mais coûte 1,6x le calcul de VP8 (`docs/perf.md`).
|
||||
* 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";
|
||||
@@ -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, };
|
||||
@@ -1,6 +0,0 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
/**
|
||||
* Ce que fait la fermeture de la fenêtre de l'application de bureau (#22).
|
||||
*/
|
||||
export type Fermeture = "barre_systeme" | "quitter";
|
||||
@@ -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, };
|
||||
+2
-2
@@ -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, };
|
||||
@@ -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" };
|
||||
@@ -1,7 +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'interface affiche comme nom d'une source, dans sa langue (#21).
|
||||
* Seul un titre de fenêtre ou un nom de sortie vient tel quel du système.
|
||||
*/
|
||||
export type Libelle = { "type": "titre", texte: string, } | { "type": "moniteur", sortie: string, principal: boolean, } | { "type": "ecran" } | { "type": "fenetre" } | { "type": "ecran_virtuel" } | { "type": "mire" } | { "type": "mire_enregistree" } | { "type": "tous_les_ecrans" } | { "type": "ecran_entier" } | { "type": "ecran_choisi" } | { "type": "fenetre_choisie" };
|
||||
@@ -1,7 +0,0 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
/**
|
||||
* Ce qu'il faut savoir d'une source avant de la choisir, traduit par
|
||||
* l'interface.
|
||||
*/
|
||||
export type NoteSource = "portail_ecran" | "portail_fenetre" | "portail_sans_fenetre" | "ecran_virtuel" | "mire" | "sans_pipewire" | "reduite";
|
||||
@@ -1,42 +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,
|
||||
/**
|
||||
* Code court à taper sans caméra, en minuscules: l'interface le groupe.
|
||||
*/
|
||||
code: string,
|
||||
/**
|
||||
* Échéance du jeton et du code, en millisecondes Unix. `None`: sans
|
||||
* limite.
|
||||
*/
|
||||
expire_ms: number | null,
|
||||
/**
|
||||
* L'échéance est passée: plus aucun nouvel appareil n'entre tant que
|
||||
* l'hôte n'a pas tiré un nouveau code.
|
||||
*/
|
||||
acces_expire: boolean,
|
||||
/**
|
||||
* Empreinte SHA-256 du certificat, en HTTPS seulement.
|
||||
*/
|
||||
empreinte: string | null,
|
||||
/**
|
||||
* Adresse et port d'écoute réels (`0.0.0.0:8099`, `192.168.1.20:9000`).
|
||||
*/
|
||||
ecoute: string,
|
||||
/**
|
||||
* Interface choisie, `None` si l'hôte écoute partout.
|
||||
*/
|
||||
interface: string | null, appareils: Array<AppareilVu>, limite: number, demarre_ms: number, };
|
||||
@@ -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";
|
||||
@@ -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, };
|
||||
@@ -1,47 +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 { Codec } from "./Codec";
|
||||
import type { Fermeture } from "./Fermeture";
|
||||
import type { Theme } from "./Theme";
|
||||
|
||||
/**
|
||||
* Tout ce qui est réglable, en un seul endroit.
|
||||
*
|
||||
* `#[serde(default)]`: un fichier écrit par une version qui ignorait un champ
|
||||
* se lit quand même, le champ prend sa valeur par défaut.
|
||||
*/
|
||||
export type Reglages = { version: number,
|
||||
/**
|
||||
* Port d'écoute du serveur (viewer et signalement).
|
||||
*/
|
||||
port: number,
|
||||
/**
|
||||
* Nom de l'interface réseau sur laquelle écouter (`wlp2s0`, `enp3s0`).
|
||||
* `None`: toutes les interfaces.
|
||||
*/
|
||||
interface: string | null, theme: Theme,
|
||||
/**
|
||||
* Code de langue de l'interface (`fr`, `en`, `pt-BR`), parmi les
|
||||
* fichiers de `locales/` (#21). `None`: celle du bureau. Un code, pas une
|
||||
* liste fermée: ajouter une langue ne change pas ce format.
|
||||
*/
|
||||
langue: string | null,
|
||||
/**
|
||||
* Spectateurs simultanés.
|
||||
*/
|
||||
limite: number,
|
||||
/**
|
||||
* Qualité proposée au démarrage d'un partage.
|
||||
*/
|
||||
qualite: QualityPreset, codec: Codec,
|
||||
/**
|
||||
* Minutes pendant lesquelles le QR code et le code court font entrer un
|
||||
* nouvel appareil (#19). `0`: sans limite. Les appareils déjà admis
|
||||
* reviennent après l'échéance.
|
||||
*/
|
||||
validite_code_min: number,
|
||||
/**
|
||||
* Lancer l'hôte à l'ouverture de session (#32).
|
||||
*/
|
||||
demarrage_auto: boolean, fermeture: Fermeture, appareils_confiance: Array<AppareilConfiance>, };
|
||||
@@ -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, };
|
||||
@@ -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>, };
|
||||
@@ -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, };
|
||||
@@ -0,0 +1,16 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { SourceKind } from "../../../viewer/src/proto/SourceKind";
|
||||
import type { Label } from "./Label";
|
||||
|
||||
/**
|
||||
* The source being shared.
|
||||
*/
|
||||
export type SharedSource = { kind: SourceKind, name: string, label: Label,
|
||||
/**
|
||||
* `portal`, `x11`, `synthetic` or `ivf`.
|
||||
*/
|
||||
backend: string,
|
||||
/**
|
||||
* Current encoded size: it follows a resolution change.
|
||||
*/
|
||||
width: number, height: number, };
|
||||
@@ -0,0 +1,15 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
/**
|
||||
* What the user chooses to share. The interface sends back the `choice` of a
|
||||
* [`SourceOption`] as is.
|
||||
*/
|
||||
export type SourceChoice = { "type": "synthetic", width: number, height: number, } | { "type": "x11", id: string, } | { "type": "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,15 +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,
|
||||
/**
|
||||
* Une fenêtre plutôt qu'un écran (#17), si le portail le permet.
|
||||
*/
|
||||
fenetre: boolean,
|
||||
/**
|
||||
* Taille d'un écran virtuel. Ignorée pour un écran existant.
|
||||
*/
|
||||
taille: [number, number] | null, } | { "type": "mire", chemin: string, };
|
||||
@@ -0,0 +1,7 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
/**
|
||||
* What to know about a source before choosing it, translated by the
|
||||
* interface.
|
||||
*/
|
||||
export type SourceNote = "portal_screen" | "portal_window" | "portal_no_window" | "virtual_screen" | "test_pattern" | "no_pipewire" | "minimized";
|
||||
@@ -0,0 +1,35 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { SourceKind } from "../../../viewer/src/proto/SourceKind";
|
||||
import type { Label } from "./Label";
|
||||
import type { SourceChoice } from "./SourceChoice";
|
||||
import type { SourceNote } from "./SourceNote";
|
||||
|
||||
/**
|
||||
* A source offered in the list.
|
||||
*/
|
||||
export type SourceOption = { choice: SourceChoice, kind: SourceKind,
|
||||
/**
|
||||
* English name, for the command line. A window title may be in it: it
|
||||
* stays in the local interface, never in the log (ADR 0008).
|
||||
*/
|
||||
name: string,
|
||||
/**
|
||||
* The name to display, which the interface translates.
|
||||
*/
|
||||
label: Label, width: number, height: number,
|
||||
/**
|
||||
* Thumbnail as a `data:image/png` URL, when the platform allows taking
|
||||
* one without consent (X11). Never under Wayland: the portal shows
|
||||
* nothing before the user agrees.
|
||||
*/
|
||||
thumbnail: string | null,
|
||||
/**
|
||||
* What to know before choosing ("the desktop will ask which one").
|
||||
*/
|
||||
note: SourceNote | null,
|
||||
/**
|
||||
* False for a source that is listed but not shareable right now
|
||||
* (minimized window, desktop that cannot share a window): the note says
|
||||
* why, before starting and not after (#17).
|
||||
*/
|
||||
available: boolean, };
|
||||
@@ -1,16 +0,0 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { SourceKind } from "../../../viewer/src/proto/SourceKind";
|
||||
import type { Libelle } from "./Libelle";
|
||||
|
||||
/**
|
||||
* La source en cours de partage.
|
||||
*/
|
||||
export type SourcePartagee = { genre: SourceKind, nom: string, libelle: Libelle,
|
||||
/**
|
||||
* `portail`, `x11`, `synthetique` ou `ivf`.
|
||||
*/
|
||||
chemin: string,
|
||||
/**
|
||||
* Taille encodée courante: elle suit un changement de résolution.
|
||||
*/
|
||||
largeur: number, hauteur: number, };
|
||||
@@ -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 { SourceKind } from "../../../viewer/src/proto/SourceKind";
|
||||
import type { Libelle } from "./Libelle";
|
||||
import type { NoteSource } from "./NoteSource";
|
||||
import type { SourceChoisie } from "./SourceChoisie";
|
||||
|
||||
/**
|
||||
* Une source proposée dans la liste.
|
||||
*/
|
||||
export type SourceProposee = { choix: SourceChoisie, genre: SourceKind,
|
||||
/**
|
||||
* Nom en français, pour la ligne de commande. Un titre de fenêtre peut
|
||||
* s'y trouver: il reste dans l'interface locale, jamais dans le journal
|
||||
* (ADR 0008).
|
||||
*/
|
||||
nom: string,
|
||||
/**
|
||||
* Le nom à afficher, que l'interface traduit.
|
||||
*/
|
||||
libelle: Libelle, largeur: number, hauteur: number,
|
||||
/**
|
||||
* Vignette en `data:image/png`, quand la plateforme permet d'en prendre
|
||||
* une sans consentement (X11). Jamais sous Wayland: le portail ne montre
|
||||
* rien avant l'accord de l'utilisateur.
|
||||
*/
|
||||
vignette: string | null,
|
||||
/**
|
||||
* Ce qu'il faut savoir avant de choisir (« le bureau demandera lequel »).
|
||||
*/
|
||||
note: NoteSource | null,
|
||||
/**
|
||||
* Faux pour une source listée mais pas partageable maintenant (fenêtre
|
||||
* réduite, bureau qui ne sait pas partager une fenêtre): la note dit
|
||||
* pourquoi, avant le démarrage et pas après (#17).
|
||||
*/
|
||||
disponible: boolean, };
|
||||
@@ -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, };
|
||||
@@ -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, };
|
||||
@@ -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,83 +0,0 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import type { SourceChoisie } from '../bindings/SourceChoisie';
|
||||
import type { SourceProposee } from '../bindings/SourceProposee';
|
||||
import { useI18n } from '../i18n';
|
||||
import { cle, filtrer, nomAffiche } from '../lib/vue';
|
||||
|
||||
type Props = {
|
||||
sources: SourceProposee[] | null;
|
||||
selection: SourceChoisie | null;
|
||||
actif: boolean;
|
||||
onChoisir: (choix: SourceChoisie) => void;
|
||||
onActualiser: () => void;
|
||||
};
|
||||
|
||||
/** Au-delà, la liste devient longue à parcourir: la recherche apparaît. */
|
||||
const SEUIL_RECHERCHE = 6;
|
||||
|
||||
export function ChoixSource({ sources, selection, actif, onChoisir, onActualiser }: Props) {
|
||||
const { t } = useI18n();
|
||||
const [recherche, setRecherche] = useState('');
|
||||
const visibles = useMemo(() => filtrer(sources ?? [], recherche, t), [sources, recherche, t]);
|
||||
const choisie = selection ? cle(selection) : null;
|
||||
|
||||
return (
|
||||
<section className='choix' aria-labelledby='choix-titre'>
|
||||
<div className='choix-entete'>
|
||||
<h2 id='choix-titre'>{t('choisirTitre')}</h2>
|
||||
{sources && sources.length > SEUIL_RECHERCHE && (
|
||||
<input
|
||||
type='search'
|
||||
className='recherche'
|
||||
placeholder={t('recherche')}
|
||||
aria-label={t('recherche')}
|
||||
value={recherche}
|
||||
onChange={(e) => setRecherche(e.target.value)}
|
||||
/>
|
||||
)}
|
||||
<button type='button' className='bouton discret' onClick={onActualiser} disabled={!actif}>
|
||||
{t('actualiser')}
|
||||
</button>
|
||||
</div>
|
||||
{sources === null && <p className='aide'>{t('chargementSources')}</p>}
|
||||
{sources !== null && visibles.length === 0 && <p className='aide'>{t('aucuneSource')}</p>}
|
||||
<ul className='sources'>
|
||||
{visibles.map((source) => {
|
||||
const id = cle(source.choix);
|
||||
const nom = nomAffiche(source.libelle, t);
|
||||
const selectionnee = id === choisie;
|
||||
return (
|
||||
<li key={id}>
|
||||
<button
|
||||
type='button'
|
||||
className={`source${selectionnee ? ' selectionnee' : ''}${source.disponible ? '' : ' indisponible'}`}
|
||||
aria-pressed={selectionnee}
|
||||
disabled={!actif || !source.disponible}
|
||||
onClick={() => onChoisir(source.choix)}
|
||||
>
|
||||
<span className='vignette'>
|
||||
{source.vignette ? (
|
||||
<img src={source.vignette} alt='' />
|
||||
) : (
|
||||
<span className='vignette-vide' aria-hidden='true'>
|
||||
{source.genre === 'window' ? '▭' : '▣'}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<span className='source-nom' title={nom}>
|
||||
{nom}
|
||||
</span>
|
||||
{source.largeur > 0 && (
|
||||
<span className='source-taille'>
|
||||
{source.largeur} × {source.hauteur}
|
||||
</span>
|
||||
)}
|
||||
{source.note && <span className='source-note'>{t(`notes.${source.note}`)}</span>}
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -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,142 +0,0 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import type { Partage } from '../bindings/Partage';
|
||||
import { useI18n } from '../i18n';
|
||||
import { codeAffiche, duree, echeance, nomAffiche } from '../lib/vue';
|
||||
|
||||
type Props = {
|
||||
partage: Partage;
|
||||
onDeconnecter: (connexion: number) => void;
|
||||
onNouveauCode: () => void;
|
||||
};
|
||||
|
||||
export function PanneauPartage({ partage, onDeconnecter, onNouveauCode }: Props) {
|
||||
const { t } = useI18n();
|
||||
const maintenant = useMaintenant();
|
||||
const [copie, setCopie] = useState(false);
|
||||
|
||||
const copier = async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(partage.url);
|
||||
setCopie(true);
|
||||
setTimeout(() => setCopie(false), 1500);
|
||||
} catch {
|
||||
setCopie(false);
|
||||
}
|
||||
};
|
||||
|
||||
const [hote] = partage.ecoute.split(':');
|
||||
const accueil = partage.url.split('/r/')[0] ?? partage.url;
|
||||
const reste = echeance(partage.expire_ms, maintenant, t);
|
||||
return (
|
||||
<section className='partage'>
|
||||
<div className='carte qr-carte'>
|
||||
<h2>{t('scanner')}</h2>
|
||||
{/* SVG produit par l'hôte (rs-signaling::qr), jamais par une entrée extérieure. */}
|
||||
<div
|
||||
className='qr'
|
||||
role='img'
|
||||
aria-label={partage.url}
|
||||
// biome-ignore lint/security/noDangerouslySetInnerHtml: SVG généré par l'hôte local
|
||||
dangerouslySetInnerHTML={{ __html: partage.qr_svg }}
|
||||
/>
|
||||
<label className='lien'>
|
||||
<span>{t('lien')}</span>
|
||||
<span className='lien-ligne'>
|
||||
<input readOnly value={partage.url} onFocus={(e) => e.target.select()} />
|
||||
<button type='button' className='bouton' onClick={copier}>
|
||||
{copie ? t('copie') : t('copier')}
|
||||
</button>
|
||||
</span>
|
||||
</label>
|
||||
<div className={`code-court ${partage.acces_expire ? 'code-expire' : ''}`}>
|
||||
<span className='discret'>
|
||||
{t('code')} {t('codeAide', { accueil })}
|
||||
</span>
|
||||
<strong className='code-valeur' aria-live='polite'>
|
||||
{codeAffiche(partage.code)}
|
||||
</strong>
|
||||
{reste && (
|
||||
<span className={partage.acces_expire ? 'alerte-texte' : 'discret'}>{reste}</span>
|
||||
)}
|
||||
<button
|
||||
type='button'
|
||||
className='bouton discret code-nouveau'
|
||||
title={t('nouveauCodeAide')}
|
||||
onClick={onNouveauCode}
|
||||
>
|
||||
{t('nouveauCode')}
|
||||
</button>
|
||||
</div>
|
||||
{partage.empreinte && (
|
||||
<p className='empreinte'>
|
||||
{t('empreinte')}: <code>{partage.empreinte}</code>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className='carte'>
|
||||
<dl className='faits'>
|
||||
<dt>{t('source')}</dt>
|
||||
<dd>
|
||||
{nomAffiche(partage.source.libelle, t)}
|
||||
<span className='discret'>
|
||||
{' '}
|
||||
{partage.source.largeur} × {partage.source.hauteur}
|
||||
</span>
|
||||
</dd>
|
||||
<dt>{t('ecoute')}</dt>
|
||||
<dd>
|
||||
{partage.interface ? `${partage.interface} (${hote})` : t('toutesInterfaces')}
|
||||
<span className='discret'>
|
||||
{' '}
|
||||
{t('port', { port: partage.ecoute.split(':').pop() ?? '' })}
|
||||
</span>
|
||||
</dd>
|
||||
<dt>{t('depuis')}</dt>
|
||||
<dd>{duree(partage.demarre_ms, maintenant)}</dd>
|
||||
</dl>
|
||||
|
||||
<h2 className='spectateurs-titre'>
|
||||
{t('spectateurs')}
|
||||
<span className='compteur'>
|
||||
{t('places', { n: partage.appareils.length, limite: partage.limite })}
|
||||
</span>
|
||||
</h2>
|
||||
{partage.appareils.length === 0 ? (
|
||||
<p className='aide'>{t('personne')}</p>
|
||||
) : (
|
||||
<ul className='appareils'>
|
||||
{partage.appareils.map((appareil) => (
|
||||
<li key={appareil.connexion}>
|
||||
<span className='appareil-nom'>{appareil.nom}</span>
|
||||
<span className='discret'>
|
||||
{[appareil.plateforme, appareil.adresse].filter(Boolean).join(' · ')}
|
||||
{' · '}
|
||||
{duree(appareil.depuis_ms, maintenant)}
|
||||
</span>
|
||||
<button
|
||||
type='button'
|
||||
className='bouton discret danger'
|
||||
title={t('deconnecterAide')}
|
||||
onClick={() => onDeconnecter(appareil.connexion)}
|
||||
>
|
||||
{t('deconnecter')}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/** L'heure courante, rafraîchie chaque seconde pour les durées affichées. */
|
||||
function useMaintenant(): number {
|
||||
const [maintenant, setMaintenant] = useState(() => Date.now());
|
||||
useEffect(() => {
|
||||
const minuterie = setInterval(() => setMaintenant(Date.now()), 1000);
|
||||
return () => clearInterval(minuterie);
|
||||
}, []);
|
||||
return maintenant;
|
||||
}
|
||||
@@ -1,304 +0,0 @@
|
||||
import { useEffect, useId, useState } from 'react';
|
||||
import type { QualityPreset } from '../../../viewer/src/proto/QualityPreset';
|
||||
import type { Application } from '../bindings/Application';
|
||||
import type { Codec } from '../bindings/Codec';
|
||||
import type { Fermeture } from '../bindings/Fermeture';
|
||||
import type { InterfaceProposee } from '../bindings/InterfaceProposee';
|
||||
import type { Refus } from '../bindings/Refus';
|
||||
import type { Reglages as ReglagesHote } from '../bindings/Reglages';
|
||||
import type { Theme } from '../bindings/Theme';
|
||||
import { LANGUES, useI18n } from '../i18n';
|
||||
import { type Hote, refusDe } from '../lib/hote';
|
||||
import { resumeApplication } from '../lib/vue';
|
||||
|
||||
const QUALITES: QualityPreset[] = ['saver', 'balanced', 'sharp'];
|
||||
const CODECS: Codec[] = ['vp8', 'vp9'];
|
||||
const THEMES: Theme[] = ['systeme', 'clair', 'sombre'];
|
||||
const FERMETURES: Fermeture[] = ['barre_systeme', 'quitter'];
|
||||
|
||||
type Props = {
|
||||
hote: Hote;
|
||||
demarrageAuto: boolean;
|
||||
onFermer: () => void;
|
||||
onEnregistre: (reglages: ReglagesHote) => void;
|
||||
};
|
||||
|
||||
export function Reglages({ hote, demarrageAuto, onFermer, onEnregistre }: Props) {
|
||||
const { t } = useI18n();
|
||||
const [reglages, setReglages] = useState<ReglagesHote | null>(null);
|
||||
const [interfaces, setInterfaces] = useState<InterfaceProposee[]>([]);
|
||||
const [refus, setRefus] = useState<Refus[]>([]);
|
||||
// Ce qu'on garde est le fait, pas sa phrase: changer de langue en
|
||||
// enregistrant retraduit aussi la confirmation.
|
||||
const [message, setMessage] = useState<
|
||||
| { type: 'application'; application: Application }
|
||||
| { type: 'diagnostics'; chemin: string }
|
||||
| null
|
||||
>(null);
|
||||
const [envoi, setEnvoi] = useState(false);
|
||||
const id = useId();
|
||||
|
||||
useEffect(() => {
|
||||
hote.reglages().then(setReglages);
|
||||
hote.interfaces().then(setInterfaces);
|
||||
}, [hote]);
|
||||
|
||||
if (!reglages) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const changer = <K extends keyof ReglagesHote>(champ: K, valeur: ReglagesHote[K]) => {
|
||||
setReglages({ ...reglages, [champ]: valeur });
|
||||
setRefus((r) => r.filter((x) => x.champ !== champ));
|
||||
setMessage(null);
|
||||
};
|
||||
const erreur = (champ: string) => refus.find((r) => r.champ === champ)?.message;
|
||||
|
||||
const enregistrer = async () => {
|
||||
setEnvoi(true);
|
||||
try {
|
||||
const application = await hote.modifierReglages(reglages);
|
||||
setRefus([]);
|
||||
setMessage({ type: 'application', application });
|
||||
onEnregistre(reglages);
|
||||
} catch (e) {
|
||||
setRefus(refusDe(e));
|
||||
setMessage(null);
|
||||
} finally {
|
||||
setEnvoi(false);
|
||||
}
|
||||
};
|
||||
|
||||
const exporter = async () => {
|
||||
try {
|
||||
setMessage({ type: 'diagnostics', chemin: await hote.exporterDiagnostics() });
|
||||
} catch (e) {
|
||||
setRefus([{ champ: 'diagnostics', message: String(e) }]);
|
||||
}
|
||||
};
|
||||
|
||||
// Une interface choisie mais absente de la liste (débranchée) reste
|
||||
// affichée, pour que le réglage enregistré ne disparaisse pas en silence.
|
||||
const absente =
|
||||
reglages.interface !== null && !interfaces.some((i) => i.nom === reglages.interface);
|
||||
|
||||
return (
|
||||
<div className='voile'>
|
||||
<div
|
||||
className='dialogue'
|
||||
role='dialog'
|
||||
aria-modal='true'
|
||||
aria-labelledby={`${id}-titre`}
|
||||
onKeyDown={(e) => e.key === 'Escape' && onFermer()}
|
||||
>
|
||||
<h2 id={`${id}-titre`}>{t('reglages')}</h2>
|
||||
<form
|
||||
className='formulaire'
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
enregistrer();
|
||||
}}
|
||||
>
|
||||
<Champ
|
||||
id={`${id}-port`}
|
||||
libelle={t('portChamp')}
|
||||
aide={t('portAide')}
|
||||
erreur={erreur('port')}
|
||||
>
|
||||
<input
|
||||
id={`${id}-port`}
|
||||
type='number'
|
||||
min={1024}
|
||||
max={65535}
|
||||
value={reglages.port}
|
||||
onChange={(e) => changer('port', Number(e.target.value))}
|
||||
/>
|
||||
</Champ>
|
||||
<Champ
|
||||
id={`${id}-interface`}
|
||||
libelle={t('interface')}
|
||||
aide={t('interfaceAide')}
|
||||
erreur={erreur('interface')}
|
||||
>
|
||||
<select
|
||||
id={`${id}-interface`}
|
||||
value={reglages.interface ?? ''}
|
||||
onChange={(e) => changer('interface', e.target.value === '' ? null : e.target.value)}
|
||||
>
|
||||
<option value=''>{t('toutesInterfaces')}</option>
|
||||
{interfaces.map((i) => (
|
||||
<option key={i.nom} value={i.nom}>
|
||||
{i.nom} ({i.adresses.join(', ')}){i.active ? '' : `, ${t('interfaceInactive')}`}
|
||||
</option>
|
||||
))}
|
||||
{absente && reglages.interface && (
|
||||
<option value={reglages.interface}>
|
||||
{reglages.interface}, {t('interfaceInactive')}
|
||||
</option>
|
||||
)}
|
||||
</select>
|
||||
</Champ>
|
||||
<Champ id={`${id}-limite`} libelle={t('limite')} erreur={erreur('limite')}>
|
||||
<input
|
||||
id={`${id}-limite`}
|
||||
type='number'
|
||||
min={1}
|
||||
max={20}
|
||||
value={reglages.limite}
|
||||
onChange={(e) => changer('limite', Number(e.target.value))}
|
||||
/>
|
||||
</Champ>
|
||||
<Champ
|
||||
id={`${id}-validite`}
|
||||
libelle={t('validite')}
|
||||
aide={t('validiteAide')}
|
||||
erreur={erreur('validite_code_min')}
|
||||
>
|
||||
<input
|
||||
id={`${id}-validite`}
|
||||
type='number'
|
||||
min={0}
|
||||
max={1440}
|
||||
value={reglages.validite_code_min}
|
||||
onChange={(e) => changer('validite_code_min', Number(e.target.value))}
|
||||
/>
|
||||
</Champ>
|
||||
<Champ id={`${id}-qualite`} libelle={t('qualite')} erreur={erreur('qualite')}>
|
||||
<select
|
||||
id={`${id}-qualite`}
|
||||
value={reglages.qualite}
|
||||
onChange={(e) => changer('qualite', e.target.value as QualityPreset)}
|
||||
>
|
||||
{QUALITES.map((q) => (
|
||||
<option key={q} value={q}>
|
||||
{t(`qualites.${q}`)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Champ>
|
||||
<Champ
|
||||
id={`${id}-codec`}
|
||||
libelle={t('codec')}
|
||||
aide={t('codecAide')}
|
||||
erreur={erreur('codec')}
|
||||
>
|
||||
<select
|
||||
id={`${id}-codec`}
|
||||
value={reglages.codec}
|
||||
onChange={(e) => changer('codec', e.target.value as Codec)}
|
||||
>
|
||||
{CODECS.map((c) => (
|
||||
<option key={c} value={c}>
|
||||
{t(`codecs.${c}`)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Champ>
|
||||
<Champ id={`${id}-theme`} libelle={t('theme')}>
|
||||
<select
|
||||
id={`${id}-theme`}
|
||||
value={reglages.theme}
|
||||
onChange={(e) => changer('theme', e.target.value as Theme)}
|
||||
>
|
||||
{THEMES.map((theme) => (
|
||||
<option key={theme} value={theme}>
|
||||
{t(`themes.${theme}`)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Champ>
|
||||
<Champ id={`${id}-langue`} libelle={t('langue')}>
|
||||
<select
|
||||
id={`${id}-langue`}
|
||||
value={reglages.langue ?? ''}
|
||||
onChange={(e) => changer('langue', e.target.value === '' ? null : e.target.value)}
|
||||
>
|
||||
<option value=''>{t('langueSysteme')}</option>
|
||||
{LANGUES.map((l) => (
|
||||
<option key={l.code} value={l.code} lang={l.code}>
|
||||
{l.nom}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Champ>
|
||||
<Champ id={`${id}-fermeture`} libelle={t('fermeture')} aide={t('fermetureAide')}>
|
||||
<select
|
||||
id={`${id}-fermeture`}
|
||||
value={reglages.fermeture}
|
||||
onChange={(e) => changer('fermeture', e.target.value as Fermeture)}
|
||||
>
|
||||
{FERMETURES.map((f) => (
|
||||
<option key={f} value={f}>
|
||||
{t(`fermetures.${f}`)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Champ>
|
||||
{demarrageAuto && (
|
||||
<label className='case'>
|
||||
<input
|
||||
type='checkbox'
|
||||
checked={reglages.demarrage_auto}
|
||||
onChange={(e) => changer('demarrage_auto', e.target.checked)}
|
||||
/>
|
||||
{t('demarrageAuto')}
|
||||
{erreur('demarrage_auto') && (
|
||||
<span className='erreur-champ'>{erreur('demarrage_auto')}</span>
|
||||
)}
|
||||
</label>
|
||||
)}
|
||||
{erreur('fichier') && <p className='erreur-champ'>{erreur('fichier')}</p>}
|
||||
{message && (
|
||||
<p className='confirmation' role='status'>
|
||||
{message.type === 'application'
|
||||
? resumeApplication(message.application, t)
|
||||
: t('diagnosticsEcrits', { chemin: message.chemin })}
|
||||
</p>
|
||||
)}
|
||||
<div className='pied'>
|
||||
<button type='button' className='bouton discret' onClick={exporter}>
|
||||
{t('diagnostics')}
|
||||
</button>
|
||||
<span className='espace' />
|
||||
<button type='button' className='bouton discret' onClick={onFermer}>
|
||||
{t('fermer')}
|
||||
</button>
|
||||
<button type='submit' className='bouton principal' disabled={envoi}>
|
||||
{t('enregistrer')}
|
||||
</button>
|
||||
</div>
|
||||
<p className='aide'>{t('diagnosticsAide')}</p>
|
||||
{erreur('diagnostics') && <p className='erreur-champ'>{erreur('diagnostics')}</p>}
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Champ({
|
||||
id,
|
||||
libelle,
|
||||
aide,
|
||||
erreur,
|
||||
children,
|
||||
}: {
|
||||
id: string;
|
||||
libelle: string;
|
||||
aide?: string;
|
||||
erreur?: string | undefined;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className={`champ${erreur ? ' en-erreur' : ''}`}>
|
||||
<label htmlFor={id}>{libelle}</label>
|
||||
{children}
|
||||
{erreur ? (
|
||||
<span className='erreur-champ' role='alert'>
|
||||
{erreur}
|
||||
</span>
|
||||
) : (
|
||||
aide && <span className='aide'>{aide}</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
+39
-39
@@ -1,66 +1,66 @@
|
||||
import { createContext, type ReactNode, useContext, useMemo } from 'react';
|
||||
|
||||
import {
|
||||
type Catalogue,
|
||||
choisirLangue,
|
||||
LANGUE_DE_REPLI,
|
||||
type LangueDisponible,
|
||||
type Traduire,
|
||||
traduction,
|
||||
type AvailableLanguage,
|
||||
type Catalog,
|
||||
createTranslator,
|
||||
FALLBACK_LANGUAGE,
|
||||
pickLanguage,
|
||||
type Translate,
|
||||
} from '../../viewer/src/lib/i18n';
|
||||
|
||||
/**
|
||||
* Textes de la coque (#21). Les mêmes fichiers que le viewer
|
||||
* (`locales/*.json`), embarqués à la compilation: la coque n'a pas de serveur
|
||||
* à interroger quand aucun partage ne tourne. Un fichier ajouté au dossier est
|
||||
* une langue de plus, sans code à changer.
|
||||
* 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 Fichier = Catalogue & { _langue: LangueDisponible };
|
||||
type LocaleFile = Catalog & { _language: AvailableLanguage };
|
||||
|
||||
const FICHIERS = Object.values(
|
||||
import.meta.glob<Fichier>('../../../locales/*.json', { eager: true, import: 'default' }),
|
||||
const FILES = Object.values(
|
||||
import.meta.glob<LocaleFile>('../../../locales/*.json', { eager: true, import: 'default' }),
|
||||
);
|
||||
|
||||
/** Les langues embarquées, par code. */
|
||||
export const LANGUES: LangueDisponible[] = FICHIERS.map((f) => f._langue).sort((a, b) =>
|
||||
a.nom.localeCompare(b.nom),
|
||||
/** The embedded languages, by code. */
|
||||
export const LANGUAGES: AvailableLanguage[] = FILES.map((f) => f._language).sort((a, b) =>
|
||||
a.name.localeCompare(b.name),
|
||||
);
|
||||
|
||||
function catalogue(code: string): Catalogue | undefined {
|
||||
return FICHIERS.find((f) => f._langue.code === code);
|
||||
function catalog(code: string): Catalog | undefined {
|
||||
return FILES.find((f) => f._language.code === code);
|
||||
}
|
||||
|
||||
/**
|
||||
* La langue à afficher: le réglage s'il désigne une langue embarquée, sinon
|
||||
* celle du bureau (`navigator.languages` reflète la locale de la session).
|
||||
* The language to display: the setting if it names an embedded language,
|
||||
* otherwise the desktop's (`navigator.languages` reflects the session locale).
|
||||
*/
|
||||
export function langueEffective(reglage: string | null, preferences: readonly string[]): string {
|
||||
const codes = LANGUES.map((l) => l.code);
|
||||
if (reglage && codes.includes(reglage)) return reglage;
|
||||
return choisirLangue(preferences, codes);
|
||||
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);
|
||||
}
|
||||
|
||||
/** La traduction de la coque dans `code`, l'anglais en repli. */
|
||||
export function traductionPour(code: string): Traduire {
|
||||
const catalogues = [catalogue(code), catalogue(LANGUE_DE_REPLI)].filter(
|
||||
(c): c is Catalogue => c !== undefined,
|
||||
/** 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 traduction(code, 'desktop', catalogues);
|
||||
return createTranslator(code, 'desktop', catalogs);
|
||||
}
|
||||
|
||||
type Contexte = { t: Traduire; langue: string };
|
||||
type Context = { t: Translate; language: string };
|
||||
|
||||
const I18n = createContext<Contexte | null>(null);
|
||||
const I18n = createContext<Context | null>(null);
|
||||
|
||||
export function useI18n(): Contexte {
|
||||
const contexte = useContext(I18n);
|
||||
if (!contexte) throw new Error('useI18n hors de I18nProvider');
|
||||
return contexte;
|
||||
export function useI18n(): Context {
|
||||
const context = useContext(I18n);
|
||||
if (!context) throw new Error('useI18n outside of I18nProvider');
|
||||
return context;
|
||||
}
|
||||
|
||||
/** Changer `langue` retraduit tout au rendu suivant, sans redémarrer. */
|
||||
export function I18nProvider({ langue, children }: { langue: string; children: ReactNode }) {
|
||||
const valeur = useMemo(() => ({ t: traductionPour(langue), langue }), [langue]);
|
||||
return <I18n.Provider value={valeur}>{children}</I18n.Provider>;
|
||||
/** Changing `language` retranslates everything at the next render, without a restart. */
|
||||
export function I18nProvider({ language, children }: { language: string; children: ReactNode }) {
|
||||
const value = useMemo(() => ({ t: translatorFor(language), language }), [language]);
|
||||
return <I18n.Provider value={value}>{children}</I18n.Provider>;
|
||||
}
|
||||
@@ -0,0 +1,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) }];
|
||||
}
|
||||
@@ -1,57 +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';
|
||||
import type { TextesBarre } from './vue';
|
||||
|
||||
/**
|
||||
* Ce que l'interface peut demander à l'hôte. Une seule implémentation réelle,
|
||||
* par les commandes Tauri; les tests en fournissent une fausse.
|
||||
*/
|
||||
export type Hote = {
|
||||
etat(): Promise<Etat>;
|
||||
/** Rend la fonction qui arrête l'écoute. */
|
||||
ecouter(rappel: (etat: Etat) => void): Promise<() => void>;
|
||||
sources(): Promise<SourceProposee[]>;
|
||||
demarrer(choix: SourceChoisie): Promise<void>;
|
||||
arreter(): Promise<void>;
|
||||
deconnecter(connexion: number): Promise<boolean>;
|
||||
/** Nouveau QR code et nouveau code court (#19). */
|
||||
regenererAcces(): Promise<boolean>;
|
||||
reglages(): Promise<Reglages>;
|
||||
/** Rejette avec la liste des valeurs refusées. */
|
||||
modifierReglages(reglages: Reglages): Promise<Application>;
|
||||
interfaces(): Promise<InterfaceProposee[]>;
|
||||
/** Rend le chemin de l'archive écrite. */
|
||||
exporterDiagnostics(): Promise<string>;
|
||||
/** Les textes du menu de la barre système, dans la langue de l'interface. */
|
||||
traduireBarre(textes: TextesBarre): Promise<void>;
|
||||
};
|
||||
|
||||
export const hoteTauri: Hote = {
|
||||
etat: () => invoke<Etat>('etat'),
|
||||
ecouter: (rappel) => listen<Etat>('etat', (evenement) => rappel(evenement.payload)),
|
||||
sources: () => invoke<SourceProposee[]>('sources'),
|
||||
demarrer: (choix) => invoke<void>('demarrer', { choix }),
|
||||
arreter: () => invoke<void>('arreter'),
|
||||
deconnecter: (connexion) => invoke<boolean>('deconnecter', { connexion }),
|
||||
regenererAcces: () => invoke<boolean>('regenerer_acces'),
|
||||
reglages: () => invoke<Reglages>('reglages'),
|
||||
modifierReglages: (reglages) => invoke<Application>('modifier_reglages', { reglages }),
|
||||
interfaces: () => invoke<InterfaceProposee[]>('interfaces'),
|
||||
exporterDiagnostics: () => invoke<string>('exporter_diagnostics'),
|
||||
traduireBarre: (textes) => invoke<void>('traduire_barre', { textes }),
|
||||
};
|
||||
|
||||
/** Les refus du Rust arrivent tels quels; tout autre rejet devient un refus global. */
|
||||
export function refusDe(erreur: unknown): Refus[] {
|
||||
if (Array.isArray(erreur)) {
|
||||
return erreur as Refus[];
|
||||
}
|
||||
return [{ champ: 'fichier', message: String(erreur) }];
|
||||
}
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -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'),
|
||||
};
|
||||
}
|
||||
@@ -1,176 +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 { LANGUES, langueEffective, traductionPour } from '../i18n';
|
||||
import {
|
||||
actions,
|
||||
cle,
|
||||
codeAffiche,
|
||||
duree,
|
||||
echeance,
|
||||
filtrer,
|
||||
resumeApplication,
|
||||
nomAffiche,
|
||||
statut,
|
||||
textesBarre,
|
||||
} from './vue';
|
||||
|
||||
const t = traductionPour('fr');
|
||||
|
||||
function etat(phase: Etat['phase'], partage: Partage | null = null): Etat {
|
||||
return {
|
||||
phase,
|
||||
partage,
|
||||
erreur: null,
|
||||
arret: null,
|
||||
avertissements: [],
|
||||
veille_inhibee: [],
|
||||
reglages_en_attente: [],
|
||||
reglages_recuperes: null,
|
||||
capacites: {
|
||||
session: 'wayland',
|
||||
bureau: 'Gnome',
|
||||
portail: true,
|
||||
ecran_virtuel: true,
|
||||
pipewire: true,
|
||||
demarrage_auto: true,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const mire = { type: 'synthetique', largeur: 1280, hauteur: 720 } as const;
|
||||
|
||||
describe('les boutons suivent l’état de l’hôte (#15, pas de bouton qui ment)', () => {
|
||||
it('arrêté: démarrer seulement avec une source choisie', () => {
|
||||
expect(actions(etat('arrete'), null, false).demarrer).toEqual({ visible: true, actif: false });
|
||||
expect(actions(etat('arrete'), mire, false).demarrer).toEqual({ visible: true, actif: true });
|
||||
expect(actions(etat('arrete'), mire, false).arreter.visible).toBe(false);
|
||||
});
|
||||
|
||||
it('une commande en vol ne s’envoie pas deux fois', () => {
|
||||
const a = actions(etat('arrete'), mire, true);
|
||||
expect(a.demarrer.actif).toBe(false);
|
||||
expect(a.choisir).toBe(false);
|
||||
});
|
||||
|
||||
it('pendant le démarrage: ni démarrer ni changer de source, annuler possible', () => {
|
||||
const a = actions(etat('demarrage'), mire, true);
|
||||
expect(a.demarrer.visible).toBe(false);
|
||||
expect(a.choisir).toBe(false);
|
||||
expect(a.annuler).toEqual({ visible: true, actif: true });
|
||||
});
|
||||
|
||||
it('en cours: arrêter seulement', () => {
|
||||
const a = actions(etat('en_cours'), mire, false);
|
||||
expect(a.arreter).toEqual({ visible: true, actif: true });
|
||||
expect(a.demarrer.visible).toBe(false);
|
||||
expect(a.annuler.visible).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('statut', () => {
|
||||
it('compte les spectateurs', () => {
|
||||
const partage = { appareils: [{}, {}] } as unknown as Partage;
|
||||
expect(statut(etat('en_cours', partage), t).texte).toBe('En direct, 2 spectateurs');
|
||||
const personne = statut(etat('en_cours', { appareils: [] } as unknown as Partage), t);
|
||||
expect(personne).toEqual({ texte: 'En direct, personne ne regarde', ton: 'direct' });
|
||||
expect(statut(etat('demarrage'), t).ton).toBe('attente');
|
||||
const en = traductionPour('en');
|
||||
expect(statut(etat('en_cours', partage), en).texte).toBe('Live, 2 viewers');
|
||||
});
|
||||
});
|
||||
|
||||
describe('sources', () => {
|
||||
const source = (nom: string, id: string): SourceProposee => ({
|
||||
choix: { type: 'x11', id },
|
||||
genre: 'window',
|
||||
nom,
|
||||
libelle: { type: 'titre', texte: nom },
|
||||
largeur: 800,
|
||||
hauteur: 600,
|
||||
vignette: null,
|
||||
note: null,
|
||||
disponible: true,
|
||||
});
|
||||
|
||||
it('la recherche ignore accents et casse', () => {
|
||||
const liste = [source('Présentation.odp', 'a'), source('Terminal', 'b')];
|
||||
expect(filtrer(liste, 'presen', t).map((s) => s.nom)).toEqual(['Présentation.odp']);
|
||||
expect(filtrer(liste, ' ', t)).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('on cherche le nom affiché, dans la langue de l’interface (#21)', () => {
|
||||
const mire: SourceProposee = {
|
||||
...source('Mire de test', 'm'),
|
||||
choix: { type: 'synthetique', largeur: 64, hauteur: 64 },
|
||||
libelle: { type: 'mire' },
|
||||
};
|
||||
expect(filtrer([mire], 'test pattern', traductionPour('en'))).toHaveLength(1);
|
||||
expect(nomAffiche({ type: 'moniteur', sortie: 'HDMI-1', principal: true }, t)).toBe(
|
||||
'HDMI-1 (principal)',
|
||||
);
|
||||
});
|
||||
|
||||
it('la clé distingue écran existant et virtuel', () => {
|
||||
expect(cle({ type: 'portail', virtuel: false, fenetre: true, taille: null })).not.toBe(
|
||||
cle({ type: 'portail', virtuel: false, fenetre: false, taille: null }),
|
||||
);
|
||||
expect(cle({ type: 'portail', virtuel: true, fenetre: false, taille: null })).not.toBe(
|
||||
cle({ type: 'portail', virtuel: false, fenetre: false, taille: null }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('textes', () => {
|
||||
it('les durées restent courtes', () => {
|
||||
expect(duree(0, 42_000)).toBe('42 s');
|
||||
expect(duree(0, 5 * 60_000)).toBe('5 min');
|
||||
expect(duree(0, 65 * 60_000)).toBe('1 h 05');
|
||||
expect(duree(10_000, 0)).toBe('0 s');
|
||||
});
|
||||
|
||||
it('un réglage en attente est dit', () => {
|
||||
expect(resumeApplication({ immediats: ['limite'], au_prochain_partage: [] }, t)).toContain(
|
||||
'appliqués',
|
||||
);
|
||||
expect(
|
||||
resumeApplication({ immediats: [], au_prochain_partage: ['port: couperait'] }, t),
|
||||
).toContain('prochain partage');
|
||||
});
|
||||
});
|
||||
|
||||
describe('code court (#19)', () => {
|
||||
it('s’affiche en deux groupes de trois', () => {
|
||||
expect(codeAffiche('k7m4pq')).toBe('K7M 4PQ');
|
||||
});
|
||||
|
||||
it('dit ce qu’il reste, en secondes sur la dernière minute', () => {
|
||||
expect(echeance(null, 0, t)).toBeNull();
|
||||
expect(echeance(10 * 60_000, 0, t)).toContain('10 min');
|
||||
expect(echeance(30_000, 0, t)).toContain('30 s');
|
||||
expect(echeance(0, 1, t)).toBe(t('codeExpire'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('langue (#21)', () => {
|
||||
it('le français et l’anglais sont embarqués', () => {
|
||||
const codes = LANGUES.map((l) => l.code);
|
||||
expect(codes).toContain('fr');
|
||||
expect(codes).toContain('en');
|
||||
});
|
||||
|
||||
it('le réglage prime, sinon la langue du bureau, sinon l’anglais', () => {
|
||||
expect(langueEffective('fr', ['en-US'])).toBe('fr');
|
||||
expect(langueEffective(null, ['fr-FR'])).toBe('fr');
|
||||
expect(langueEffective(null, ['de-DE'])).toBe('en');
|
||||
expect(langueEffective('xx', ['fr-BE'])).toBe('fr');
|
||||
});
|
||||
|
||||
it('la barre système reçoit les trois formes, {count} à remplacer', () => {
|
||||
const barre = textesBarre(t);
|
||||
expect(barre.direct.zero).toBe('En direct, personne ne regarde');
|
||||
expect(barre.direct.one).toBe('En direct, 1 spectateur');
|
||||
expect(barre.direct.other).toBe('En direct, {count} spectateurs');
|
||||
});
|
||||
});
|
||||
@@ -1,209 +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 type { Libelle } from '../bindings/Libelle';
|
||||
import type { Traduire } from '../../../viewer/src/lib/i18n';
|
||||
|
||||
/**
|
||||
* Ce que montrent les boutons, déduit de l'état de l'hôte et de rien d'autre.
|
||||
*
|
||||
* C'est le critère de #15, « pas de bouton qui ment »: un bouton n'a pas
|
||||
* d'état à lui. `envoi` dit seulement qu'une commande est partie et que sa
|
||||
* réponse n'est pas revenue, pour ne pas l'envoyer deux fois.
|
||||
*/
|
||||
export type Actions = {
|
||||
/** La liste des sources est cliquable. */
|
||||
choisir: boolean;
|
||||
demarrer: { visible: boolean; actif: boolean };
|
||||
annuler: { visible: boolean; actif: boolean };
|
||||
arreter: { visible: boolean; actif: boolean };
|
||||
};
|
||||
|
||||
export function actions(etat: Etat, selection: SourceChoisie | null, envoi: boolean): Actions {
|
||||
switch (etat.phase) {
|
||||
case 'arrete':
|
||||
return {
|
||||
choisir: !envoi,
|
||||
demarrer: { visible: true, actif: selection !== null && !envoi },
|
||||
annuler: { visible: false, actif: false },
|
||||
arreter: { visible: false, actif: false },
|
||||
};
|
||||
case 'demarrage':
|
||||
return {
|
||||
choisir: false,
|
||||
demarrer: { visible: false, actif: false },
|
||||
annuler: { visible: true, actif: true },
|
||||
arreter: { visible: false, actif: false },
|
||||
};
|
||||
case 'en_cours':
|
||||
return {
|
||||
choisir: false,
|
||||
demarrer: { visible: false, actif: false },
|
||||
annuler: { visible: false, actif: false },
|
||||
arreter: { visible: true, actif: !envoi },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export type Statut = { texte: string; ton: 'repos' | 'attente' | 'direct' };
|
||||
|
||||
export function statut(etat: Etat, t: Traduire): Statut {
|
||||
switch (etat.phase) {
|
||||
case 'arrete':
|
||||
return { texte: t('statutArrete'), ton: 'repos' };
|
||||
case 'demarrage':
|
||||
return { texte: t('statutDemarrage'), ton: 'attente' };
|
||||
case 'en_cours': {
|
||||
const n = etat.partage?.appareils.length ?? 0;
|
||||
return { texte: t('statutEnCours', { count: n }), ton: 'direct' };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Identité stable d'un choix, pour la sélection et les clés React. */
|
||||
export function cle(choix: SourceChoisie): string {
|
||||
switch (choix.type) {
|
||||
case 'x11':
|
||||
return `x11:${choix.id}`;
|
||||
case 'portail':
|
||||
if (choix.virtuel) return 'portail:virtuel';
|
||||
return choix.fenetre ? 'portail:fenetre' : 'portail:ecran';
|
||||
case 'synthetique':
|
||||
return 'synthetique';
|
||||
case 'mire':
|
||||
return `mire:${choix.chemin}`;
|
||||
}
|
||||
}
|
||||
|
||||
function normaliser(texte: string): string {
|
||||
return texte
|
||||
.normalize('NFD')
|
||||
.replace(/\p{Diacritic}/gu, '')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Recherche par nom affiché, sans tenir compte des accents ni de la casse:
|
||||
* on cherche ce qu'on lit, dans la langue de l'interface.
|
||||
*/
|
||||
export function filtrer(
|
||||
sources: SourceProposee[],
|
||||
recherche: string,
|
||||
t: Traduire,
|
||||
): SourceProposee[] {
|
||||
const cherche = normaliser(recherche.trim());
|
||||
if (cherche === '') {
|
||||
return sources;
|
||||
}
|
||||
return sources.filter((s) => normaliser(nomAffiche(s.libelle, t)).includes(cherche));
|
||||
}
|
||||
|
||||
/** Le nom d'une source dans la langue de l'interface (#21). */
|
||||
export function nomAffiche(libelle: Libelle, t: Traduire): string {
|
||||
switch (libelle.type) {
|
||||
case 'titre':
|
||||
return libelle.texte;
|
||||
case 'moniteur':
|
||||
return libelle.principal
|
||||
? t('sources.principal', { sortie: libelle.sortie })
|
||||
: libelle.sortie;
|
||||
case 'ecran':
|
||||
return t('sources.ecran');
|
||||
case 'fenetre':
|
||||
return t('sources.fenetre');
|
||||
case 'ecran_virtuel':
|
||||
return t('sources.ecranVirtuel');
|
||||
case 'mire':
|
||||
return t('sources.mire');
|
||||
case 'mire_enregistree':
|
||||
return t('sources.mireEnregistree');
|
||||
case 'tous_les_ecrans':
|
||||
return t('sources.tousLesEcrans');
|
||||
case 'ecran_entier':
|
||||
return t('sources.ecranX11');
|
||||
case 'ecran_choisi':
|
||||
return t('sources.ecranChoisi');
|
||||
case 'fenetre_choisie':
|
||||
return t('sources.fenetreChoisie');
|
||||
}
|
||||
}
|
||||
|
||||
/** Durée lisible depuis une date Unix en millisecondes. */
|
||||
export function duree(depuisMs: number, maintenantMs: number): string {
|
||||
const secondes = Math.max(0, Math.floor((maintenantMs - depuisMs) / 1000));
|
||||
if (secondes < 60) {
|
||||
return `${secondes} s`;
|
||||
}
|
||||
const minutes = Math.floor(secondes / 60);
|
||||
if (minutes < 60) {
|
||||
return `${minutes} min`;
|
||||
}
|
||||
const heures = Math.floor(minutes / 60);
|
||||
return `${heures} h ${String(minutes % 60).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
/** Ce qu'on dit après un enregistrement de réglages. */
|
||||
export function resumeApplication(application: Application, t: Traduire): string {
|
||||
if (application.au_prochain_partage.length > 0) {
|
||||
return t('reglagesEnAttente', { champs: application.au_prochain_partage.join('; ') });
|
||||
}
|
||||
if (application.immediats.length > 0) {
|
||||
return t('reglagesAppliques');
|
||||
}
|
||||
return t('reglagesInchanges');
|
||||
}
|
||||
|
||||
/** Le code court tel qu'on le lit et le dicte: `K7M 4PQ`. */
|
||||
export function codeAffiche(code: string): string {
|
||||
const haut = code.toUpperCase();
|
||||
return haut.length === 6 ? `${haut.slice(0, 3)} ${haut.slice(3)}` : haut;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ce qu'il reste au code d'accès, en clair, ou `null` s'il n'expire pas.
|
||||
* Au-dessous d'une minute, on compte en secondes: c'est le moment où l'hôte
|
||||
* doit savoir qu'un nouveau venu va être refusé.
|
||||
*/
|
||||
export function echeance(expireMs: number | null, maintenant: number, t: Traduire): string | null {
|
||||
if (expireMs === null) return null;
|
||||
const restant = expireMs - maintenant;
|
||||
if (restant <= 0) return t('codeExpire');
|
||||
if (restant < 60_000) return t('codeExpireDans', { duree: `${Math.ceil(restant / 1000)} s` });
|
||||
return t('codeExpireDans', { duree: `${Math.ceil(restant / 60_000)} min` });
|
||||
}
|
||||
|
||||
/** Ce que le menu de la barre système affiche, traduit (#21, #22). */
|
||||
export type TextesBarre = {
|
||||
aucun: string;
|
||||
demarrage: string;
|
||||
/** Formes du statut en direct, par nombre exact puis catégorie. */
|
||||
direct: { zero: string; one: string; other: string };
|
||||
ouvrir: string;
|
||||
demarrer: string;
|
||||
reprendre: string;
|
||||
arreter: string;
|
||||
quitter: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Les textes de la barre système. Rust ne connaît pas les règles de pluriel
|
||||
* de chaque langue: on lui donne les formes de 0, 1 et du reste, avec
|
||||
* `{count}` à remplacer.
|
||||
*/
|
||||
export function textesBarre(t: Traduire): TextesBarre {
|
||||
return {
|
||||
aucun: t('barre.aucun'),
|
||||
demarrage: t('barre.demarrage'),
|
||||
direct: {
|
||||
zero: t('barre.direct', { count: 0 }),
|
||||
one: t('barre.direct', { count: 1 }),
|
||||
other: t('barre.direct', { count: '{count}' }),
|
||||
},
|
||||
ouvrir: t('barre.ouvrir'),
|
||||
demarrer: t('barre.demarrer'),
|
||||
reprendre: t('barre.reprendre'),
|
||||
arreter: t('barre.arreter'),
|
||||
quitter: t('barre.quitter'),
|
||||
};
|
||||
}
|
||||
@@ -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>,
|
||||
);
|
||||
+155
-155
@@ -1,60 +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;
|
||||
/* Assez sombres pour un texte sur fond clair: contraste AA (4,5:1) vérifié
|
||||
pour chaque paire texte et fond (#28). */
|
||||
--direct: #15803d;
|
||||
--attente: #b45309;
|
||||
--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;
|
||||
--alerte-fond: #fff7e6;
|
||||
--erreur-fond: #fdecec;
|
||||
--info-fond: #eaf1ff;
|
||||
--rayon: 10px;
|
||||
--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;
|
||||
}
|
||||
}
|
||||
@@ -71,8 +71,8 @@ body,
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--fond);
|
||||
color: var(--texte);
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
@@ -90,11 +90,11 @@ h2 {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.chargement {
|
||||
.loading {
|
||||
display: grid;
|
||||
height: 100%;
|
||||
place-items: center;
|
||||
color: var(--discret);
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.app {
|
||||
@@ -103,8 +103,8 @@ h2 {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.entete,
|
||||
.barre {
|
||||
.header,
|
||||
.action-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
@@ -112,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;
|
||||
@@ -150,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;
|
||||
}
|
||||
|
||||
@@ -271,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;
|
||||
@@ -284,7 +284,7 @@ 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);
|
||||
}
|
||||
@@ -293,55 +293,55 @@ h2 {
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.source.indisponible {
|
||||
.source.unavailable {
|
||||
border-style: dashed;
|
||||
}
|
||||
|
||||
.vignette {
|
||||
.thumbnail {
|
||||
display: grid;
|
||||
aspect-ratio: 16 / 9;
|
||||
place-items: center;
|
||||
overflow: hidden;
|
||||
border-radius: 6px;
|
||||
background: var(--fond);
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
/* Le texte garde son contraste: seule l'image s'efface. La note dit pourquoi
|
||||
la source n'est pas partageable (#17). */
|
||||
.source:disabled .vignette {
|
||||
/* 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;
|
||||
}
|
||||
|
||||
.vignette img {
|
||||
.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;
|
||||
@@ -349,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;
|
||||
@@ -379,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;
|
||||
@@ -468,61 +468,61 @@ 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;
|
||||
}
|
||||
|
||||
/* Code court (#19): lisible de loin, dictable. */
|
||||
.code-court {
|
||||
/* Short code (#19): readable from afar, easy to dictate. */
|
||||
.short-code {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.35rem 0.75rem;
|
||||
@@ -530,30 +530,30 @@ h2 {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.code-court > .discret:first-child {
|
||||
.short-code > .muted:first-child {
|
||||
flex-basis: 100%;
|
||||
}
|
||||
|
||||
.code-valeur {
|
||||
.code-value {
|
||||
font:
|
||||
700 1.6rem / 1.1 ui-monospace,
|
||||
"SF Mono",
|
||||
Menlo,
|
||||
monospace;
|
||||
letter-spacing: 0.12em;
|
||||
color: var(--texte);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.code-expire .code-valeur {
|
||||
color: var(--discret);
|
||||
.code-expired .code-value {
|
||||
color: var(--muted);
|
||||
text-decoration: line-through;
|
||||
}
|
||||
|
||||
.code-nouveau {
|
||||
.code-new {
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.alerte-texte {
|
||||
color: var(--attente);
|
||||
.warning-text {
|
||||
color: var(--waiting);
|
||||
font-weight: 600;
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -3,12 +3,12 @@
|
||||
"private": true,
|
||||
"version": "0.4.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 && node ../../scripts/verifier-i18n.mjs apps/viewer/src viewer",
|
||||
"lint": "biome lint src && node ../../scripts/check-i18n.mjs apps/viewer/src viewer",
|
||||
"format": "biome format --write src",
|
||||
"test": "vitest run"
|
||||
},
|
||||
|
||||
+106
-35
@@ -1,16 +1,25 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
|
||||
import { ErrorPanel } from './components/ErrorPanel';
|
||||
import { ChoixLangue } from './components/ChoixLangue';
|
||||
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 { parseRoomLocation, signalingUrl } from './lib/room';
|
||||
import { type VideoStats, ViewerSession, type ViewerState } from './lib/session';
|
||||
import { garderRotation, lireRotation, type Rotation, rotationSuivante } from './lib/rotation';
|
||||
import { appliquerTheme, garderTheme, lireTheme, type Theme, themeSuivant } from './lib/theme';
|
||||
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 { applyTheme, nextTheme, readTheme, saveTheme, type Theme } from './lib/theme';
|
||||
import { useActivity } from './lib/useActivity';
|
||||
|
||||
export function App() {
|
||||
const { t } = useI18n();
|
||||
@@ -23,14 +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>(() => lireTheme());
|
||||
const [rotation, setRotation] = useState<Rotation>(() => lireRotation());
|
||||
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({
|
||||
@@ -81,26 +94,40 @@ export function App() {
|
||||
}
|
||||
}, []);
|
||||
|
||||
const changerTheme = useCallback(() => {
|
||||
setTheme((courant) => {
|
||||
const suivant = themeSuivant(courant);
|
||||
appliquerTheme(suivant);
|
||||
garderTheme(suivant);
|
||||
return suivant;
|
||||
const cycleTheme = useCallback(() => {
|
||||
setTheme((current) => {
|
||||
const next = nextTheme(current);
|
||||
applyTheme(next);
|
||||
saveTheme(next);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const tourner = useCallback(() => {
|
||||
setRotation((courante) => {
|
||||
const suivante = rotationSuivante(courante);
|
||||
garderRotation(suivante);
|
||||
return suivante;
|
||||
const rotate = useCallback(() => {
|
||||
setRotation((current) => {
|
||||
const next = nextRotation(current);
|
||||
saveRotation(next);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
// 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 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;
|
||||
@@ -109,8 +136,8 @@ export function App() {
|
||||
}, []);
|
||||
|
||||
if (!location.ok) {
|
||||
// Sans session dans l'adresse, on propose le code court (#19). La page
|
||||
// d'accueil nue n'est pas une erreur: c'est l'entrée sans caméra.
|
||||
// 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'),
|
||||
@@ -121,16 +148,35 @@ export function App() {
|
||||
}
|
||||
|
||||
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'>
|
||||
<div className={classes} ref={containerRef}>
|
||||
<header className='topbar' {...hold}>
|
||||
<span className='brand'>{t('appName')}</span>
|
||||
<StatusBadge state={state} />
|
||||
{location.value.fingerprint && (
|
||||
@@ -146,23 +192,47 @@ export function App() {
|
||||
<button
|
||||
type='button'
|
||||
className='button button-ghost button-theme'
|
||||
onClick={changerTheme}
|
||||
onClick={cycleTheme}
|
||||
aria-label={t('themeButton', { current: t(`themes.${theme}`) })}
|
||||
title={t('themeButton', { current: t(`themes.${theme}`) })}
|
||||
>
|
||||
{theme === 'sombre' ? '☾' : theme === 'clair' ? '☀' : '◐'}
|
||||
{theme === 'dark' ? '☾' : theme === 'light' ? '☀' : '◐'}
|
||||
</button>
|
||||
{live && (
|
||||
<button
|
||||
type='button'
|
||||
className='button button-ghost'
|
||||
onClick={tourner}
|
||||
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'
|
||||
@@ -182,13 +252,14 @@ export function App() {
|
||||
live={live}
|
||||
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} />
|
||||
<ChoixLangue />
|
||||
<LanguagePicker />
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
import { useId } from 'react';
|
||||
|
||||
import { useI18n } from '../i18n';
|
||||
|
||||
/**
|
||||
* Choix de la langue (#21), parmi celles que sert l'hôte. Chacune s'affiche
|
||||
* dans sa propre langue: qui ne lit pas la langue courante retrouve la sienne.
|
||||
*/
|
||||
export function ChoixLangue() {
|
||||
const { t, langue, langues, changerLangue } = useI18n();
|
||||
const id = useId();
|
||||
if (langues.length < 2) return null;
|
||||
return (
|
||||
<span className='langue'>
|
||||
<label htmlFor={id} className='visually-hidden'>
|
||||
{t('language')}
|
||||
</label>
|
||||
<select id={id} value={langue} onChange={(e) => changerLangue(e.target.value)}>
|
||||
{langues.map((l) => (
|
||||
<option key={l.code} value={l.code} lang={l.code}>
|
||||
{l.nom}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -7,9 +7,9 @@ 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();
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -3,19 +3,19 @@ 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 { ChoixLangue } from './ChoixLangue';
|
||||
import { LanguagePicker } from './LanguagePicker';
|
||||
|
||||
/** Un code d'exemple, dans le format affiché par l'hôte: pas une phrase. */
|
||||
const EXEMPLE_CODE = 'K7M 4PQ';
|
||||
/** A sample code, in the format the host shows: not a sentence. */
|
||||
const SAMPLE_CODE = 'K7M 4PQ';
|
||||
|
||||
type Props = {
|
||||
/** Pourquoi on arrive ici sans session, à dire avant le formulaire. */
|
||||
/** Why we land here without a session, to say before the form. */
|
||||
notice: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Page d'accueil sans session (#19): taper le code court affiché par l'hôte,
|
||||
* ou scanner son QR code quand le navigateur sait le faire.
|
||||
* 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();
|
||||
@@ -73,7 +73,7 @@ export function Pairing({ notice }: Props) {
|
||||
autoCapitalize='characters'
|
||||
spellCheck={false}
|
||||
maxLength={8}
|
||||
placeholder={EXEMPLE_CODE}
|
||||
placeholder={SAMPLE_CODE}
|
||||
aria-describedby={error ? 'code-error' : undefined}
|
||||
aria-invalid={error !== null}
|
||||
/>
|
||||
@@ -93,13 +93,13 @@ export function Pairing({ notice }: Props) {
|
||||
</button>
|
||||
)}
|
||||
{scanning && <Scanner onClose={() => setScanning(false)} onError={setError} />}
|
||||
<ChoixLangue />
|
||||
<LanguagePicker />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Caméra arrière, lecture du QR code quatre fois par seconde. */
|
||||
/** 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);
|
||||
|
||||
@@ -8,12 +8,12 @@ type Props = {
|
||||
};
|
||||
|
||||
/**
|
||||
* 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, langue } = useI18n();
|
||||
const { t, language } = useI18n();
|
||||
const previous = useRef<{ bytes: number; at: number } | null>(null);
|
||||
const [kbps, setKbps] = useState<number | null>(null);
|
||||
|
||||
@@ -57,7 +57,7 @@ export function StatsBar({ stats }: Props) {
|
||||
<dd>
|
||||
{kbps >= 1000
|
||||
? t('mbps', {
|
||||
value: (kbps / 1000).toLocaleString(langue, { maximumFractionDigits: 1 }),
|
||||
value: (kbps / 1000).toLocaleString(language, { maximumFractionDigits: 1 }),
|
||||
})
|
||||
: t('kbps', { value: kbps })}
|
||||
</dd>
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { useI18n } from '../i18n';
|
||||
import type { Traduire } from '../lib/i18n';
|
||||
import type { Translate } from '../lib/i18n';
|
||||
import type { ViewerState } from '../lib/session';
|
||||
|
||||
/** Traduit l'état de session en un libellé court et une couleur. */
|
||||
export function describe(state: ViewerState, t: Traduire): { 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: t('connecting'), tone: 'pending' };
|
||||
|
||||
@@ -1,23 +1,24 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
|
||||
import { boiteTournee, type Rotation } from '../lib/rotation';
|
||||
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. Une
|
||||
* rotation change sa boîte et sa transformation, jamais le flux (#30).
|
||||
* 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, rotation }: Props) {
|
||||
export function VideoStage({ stream, live, label, rotation, mirror }: Props) {
|
||||
const videoRef = useRef<HTMLVideoElement | null>(null);
|
||||
const stageRef = useRef<HTMLDivElement | null>(null);
|
||||
const [taille, setTaille] = useState<{ largeur: number; hauteur: number } | null>(null);
|
||||
const [size, setSize] = useState<{ width: number; height: number } | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const video = videoRef.current;
|
||||
@@ -26,40 +27,45 @@ export function VideoStage({ stream, live, label, rotation }: 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]);
|
||||
|
||||
// La boîte tournée dépend de la taille de la scène: plein écran, passage
|
||||
// en portrait, clavier virtuel la changent.
|
||||
// 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 observateur = new ResizeObserver(([entree]) => {
|
||||
if (!entree) return;
|
||||
const { width, height } = entree.contentRect;
|
||||
setTaille({ largeur: width, hauteur: height });
|
||||
const observer = new ResizeObserver(([entry]) => {
|
||||
if (!entry) return;
|
||||
const { width, height } = entry.contentRect;
|
||||
setSize({ width, height });
|
||||
});
|
||||
observateur.observe(stage);
|
||||
return () => observateur.disconnect();
|
||||
observer.observe(stage);
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
|
||||
// Without rotation, the element keeps its box: the mirror alone flips it.
|
||||
const style =
|
||||
rotation !== 0 && taille
|
||||
? (() => {
|
||||
const boite = boiteTournee(taille.largeur, taille.hauteur, rotation);
|
||||
return {
|
||||
inset: 'auto',
|
||||
left: '50%',
|
||||
top: '50%',
|
||||
width: `${boite.width}px`,
|
||||
height: `${boite.height}px`,
|
||||
transform: boite.transform,
|
||||
};
|
||||
})()
|
||||
: undefined;
|
||||
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' ref={stageRef}>
|
||||
|
||||
+66
-62
@@ -1,120 +1,124 @@
|
||||
import { createContext, type ReactNode, useCallback, useContext, useMemo, useState } from 'react';
|
||||
|
||||
import {
|
||||
type Catalogue,
|
||||
choisirLangue,
|
||||
LANGUE_DE_REPLI,
|
||||
type LangueDisponible,
|
||||
type Traduire,
|
||||
traduction,
|
||||
type AvailableLanguage,
|
||||
type Catalog,
|
||||
createTranslator,
|
||||
FALLBACK_LANGUAGE,
|
||||
pickLanguage,
|
||||
type Translate,
|
||||
} from './lib/i18n';
|
||||
import { browserStorage, readMigrated } from './lib/storage';
|
||||
|
||||
/**
|
||||
* Textes du viewer (#21). Le catalogue vient de l'hôte (`/locales/`): ajouter
|
||||
* une langue à l'hôte la rend disponible ici, sans recompiler le viewer. Le
|
||||
* choix de l'appareil est gardé par lui seul, comme le thème.
|
||||
* 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 CLE = 'rustscreen.langue';
|
||||
const KEY = 'rustscreen.language';
|
||||
/** Key before #83. */
|
||||
const LEGACY_KEY = 'rustscreen.langue';
|
||||
|
||||
type Contexte = {
|
||||
t: Traduire;
|
||||
langue: string;
|
||||
langues: LangueDisponible[];
|
||||
changerLangue: (code: string) => void;
|
||||
type Context = {
|
||||
t: Translate;
|
||||
language: string;
|
||||
languages: AvailableLanguage[];
|
||||
setLanguage: (code: string) => void;
|
||||
};
|
||||
|
||||
const I18n = createContext<Contexte | null>(null);
|
||||
const I18n = createContext<Context | null>(null);
|
||||
|
||||
export function useI18n(): Contexte {
|
||||
const contexte = useContext(I18n);
|
||||
if (!contexte) throw new Error('useI18n hors de I18nProvider');
|
||||
return contexte;
|
||||
export function useI18n(): Context {
|
||||
const context = useContext(I18n);
|
||||
if (!context) throw new Error('useI18n outside of I18nProvider');
|
||||
return context;
|
||||
}
|
||||
|
||||
type Charge = { langue: string; catalogues: Catalogue[] };
|
||||
type Loaded = { language: string; catalogs: Catalog[] };
|
||||
|
||||
export function I18nProvider({
|
||||
initial,
|
||||
langues,
|
||||
languages,
|
||||
children,
|
||||
}: {
|
||||
initial: Charge;
|
||||
langues: LangueDisponible[];
|
||||
initial: Loaded;
|
||||
languages: AvailableLanguage[];
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const [charge, setCharge] = useState(initial);
|
||||
const [loaded, setLoaded] = useState(initial);
|
||||
|
||||
const changerLangue = useCallback((code: string) => {
|
||||
garderLangue(code);
|
||||
// Le changement prend effet au rendu suivant: pas de rechargement, la
|
||||
// session et le flux continuent.
|
||||
void chargerCatalogues(code).then((catalogues) => {
|
||||
if (catalogues.length === 0) return;
|
||||
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;
|
||||
setCharge({ langue: code, catalogues });
|
||||
setLoaded({ language: code, catalogs });
|
||||
});
|
||||
}, []);
|
||||
|
||||
const valeur = useMemo(
|
||||
const value = useMemo(
|
||||
() => ({
|
||||
t: traduction(charge.langue, 'viewer', charge.catalogues),
|
||||
langue: charge.langue,
|
||||
langues,
|
||||
changerLangue,
|
||||
t: createTranslator(loaded.language, 'viewer', loaded.catalogs),
|
||||
language: loaded.language,
|
||||
languages,
|
||||
setLanguage,
|
||||
}),
|
||||
[charge, langues, changerLangue],
|
||||
[loaded, languages, setLanguage],
|
||||
);
|
||||
return <I18n.Provider value={valeur}>{children}</I18n.Provider>;
|
||||
return <I18n.Provider value={value}>{children}</I18n.Provider>;
|
||||
}
|
||||
|
||||
/** Les langues que sert l'hôte, vide s'il ne répond pas. */
|
||||
export async function chargerLangues(): Promise<LangueDisponible[]> {
|
||||
/** The languages the host serves, empty if it does not answer. */
|
||||
export async function loadLanguages(): Promise<AvailableLanguage[]> {
|
||||
try {
|
||||
const reponse = await fetch('/locales/index.json');
|
||||
if (!reponse.ok) return [];
|
||||
return (await reponse.json()) as LangueDisponible[];
|
||||
const response = await fetch('/locales/index.json');
|
||||
if (!response.ok) return [];
|
||||
return (await response.json()) as AvailableLanguage[];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/** La langue voulue puis l'anglais, ce qui existe des deux. */
|
||||
export async function chargerCatalogues(code: string): Promise<Catalogue[]> {
|
||||
const codes = code === LANGUE_DE_REPLI ? [code] : [code, LANGUE_DE_REPLI];
|
||||
const catalogues = await Promise.all(
|
||||
/** 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 reponse = await fetch(`/locales/${encodeURIComponent(c)}.json`);
|
||||
return reponse.ok ? ((await reponse.json()) as Catalogue) : null;
|
||||
const response = await fetch(`/locales/${encodeURIComponent(c)}.json`);
|
||||
return response.ok ? ((await response.json()) as Catalog) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}),
|
||||
);
|
||||
return catalogues.filter((c): c is Catalogue => c !== null);
|
||||
return catalogs.filter((c): c is Catalog => c !== null);
|
||||
}
|
||||
|
||||
/** Le choix gardé par l'appareil, sinon la langue du navigateur. */
|
||||
export function langueDeDepart(disponibles: LangueDisponible[]): string {
|
||||
const codes = disponibles.map((l) => l.code);
|
||||
const gardee = lireLangue();
|
||||
if (gardee && codes.includes(gardee)) return gardee;
|
||||
return choisirLangue(navigator.languages ?? [navigator.language], codes);
|
||||
/** The 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 lireLangue(): string | null {
|
||||
function readLanguage(): string | null {
|
||||
try {
|
||||
return window.localStorage.getItem(CLE);
|
||||
const storage = browserStorage();
|
||||
return storage ? readMigrated(storage, KEY, LEGACY_KEY) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function garderLangue(code: string): void {
|
||||
function saveLanguage(code: string): void {
|
||||
try {
|
||||
window.localStorage.setItem(CLE, code);
|
||||
window.localStorage.setItem(KEY, code);
|
||||
} catch {
|
||||
// Navigation privée: le choix vaut pour la page.
|
||||
// Private browsing: the choice holds for the page only.
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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.
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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('');
|
||||
}
|
||||
@@ -1,55 +1,55 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { type Catalogue, choisirLangue, traduction } from './i18n';
|
||||
import { type Catalog, createTranslator, pickLanguage } from './i18n';
|
||||
|
||||
const fr: Catalogue = {
|
||||
const fr: Catalog = {
|
||||
viewer: {
|
||||
bonjour: 'Bonjour {nom}',
|
||||
spectateurs: { '0': 'personne', one: '{count} spectateur', other: '{count} spectateurs' },
|
||||
greeting: 'Bonjour {name}',
|
||||
viewers: { '0': 'personne', one: '{count} spectateur', other: '{count} spectateurs' },
|
||||
},
|
||||
};
|
||||
const en: Catalogue = {
|
||||
const en: Catalog = {
|
||||
viewer: {
|
||||
bonjour: 'Hello {nom}',
|
||||
seulementEn: 'Only in English',
|
||||
spectateurs: { '0': 'nobody', one: '{count} viewer', other: '{count} viewers' },
|
||||
greeting: 'Hello {name}',
|
||||
onlyInEnglish: 'Only in English',
|
||||
viewers: { '0': 'nobody', one: '{count} viewer', other: '{count} viewers' },
|
||||
},
|
||||
};
|
||||
|
||||
describe('traduction (#21)', () => {
|
||||
it('interpole les paramètres', () => {
|
||||
const t = traduction('fr', 'viewer', [fr, en]);
|
||||
expect(t('bonjour', { nom: 'Ana' })).toBe('Bonjour Ana');
|
||||
describe('createTranslator (#21)', () => {
|
||||
it('interpolates the parameters', () => {
|
||||
const t = createTranslator('fr', 'viewer', [fr, en]);
|
||||
expect(t('greeting', { name: 'Ana' })).toBe('Bonjour Ana');
|
||||
});
|
||||
|
||||
it('choisit la forme plurielle de la langue', () => {
|
||||
const t = traduction('fr', 'viewer', [fr, en]);
|
||||
expect(t('spectateurs', { count: 0 })).toBe('personne');
|
||||
expect(t('spectateurs', { count: 1 })).toBe('1 spectateur');
|
||||
expect(t('spectateurs', { count: 3 })).toBe('3 spectateurs');
|
||||
it('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('retombe sur l’anglais pour une clé manquante, jamais sur la clé brute', () => {
|
||||
const t = traduction('fr', 'viewer', [fr, en]);
|
||||
expect(t('seulementEn')).toBe('Only in English');
|
||||
expect(t('nulle.part')).toBe('');
|
||||
it('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('une langue inconnue de Intl ne casse rien', () => {
|
||||
const t = traduction('xx-invalide-%', 'viewer', [en]);
|
||||
expect(t('spectateurs', { count: 2 })).toBe('2 viewers');
|
||||
it('a language unknown to Intl breaks nothing', () => {
|
||||
const t = createTranslator('xx-invalid-%', 'viewer', [en]);
|
||||
expect(t('viewers', { count: 2 })).toBe('2 viewers');
|
||||
});
|
||||
});
|
||||
|
||||
describe('choisirLangue', () => {
|
||||
it('suit la langue de l’appareil, exactement ou par sa langue principale', () => {
|
||||
expect(choisirLangue(['fr-FR', 'en'], ['en', 'fr'])).toBe('fr');
|
||||
expect(choisirLangue(['fr-CA'], ['en', 'fr'])).toBe('fr');
|
||||
expect(choisirLangue(['pt-BR', 'pt'], ['en', 'pt-BR', 'pt'])).toBe('pt-BR');
|
||||
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('retombe sur l’anglais pour une langue absente', () => {
|
||||
expect(choisirLangue(['de-DE', 'it'], ['en', 'fr'])).toBe('en');
|
||||
expect(choisirLangue([], ['en', 'fr'])).toBe('en');
|
||||
it('falls back to English for a missing language', () => {
|
||||
expect(pickLanguage(['de-DE', 'it'], ['en', 'fr'])).toBe('en');
|
||||
expect(pickLanguage([], ['en', 'fr'])).toBe('en');
|
||||
});
|
||||
});
|
||||
+77
-70
@@ -1,105 +1,112 @@
|
||||
/**
|
||||
* Traduction (#21), sans dépendance: recherche d'une clé, pluriel,
|
||||
* interpolation, retour à l'anglais, choix de la langue.
|
||||
* Translation (#21), without dependencies: key lookup, plurals,
|
||||
* interpolation, English fallback, language choice.
|
||||
*
|
||||
* Les textes vivent dans `locales/<langue>.json`, à la racine du dépôt, un
|
||||
* fichier par langue, une section par application (`viewer`, `desktop`).
|
||||
* Ajouter une langue, c'est ajouter un fichier: aucun code ne change. L'hôte
|
||||
* les embarque et les sert au viewer (`/locales/`), la coque les embarque à la
|
||||
* compilation.
|
||||
* 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.
|
||||
*
|
||||
* Ce module est pur: la coque l'importe tel quel, sans React.
|
||||
* This module is pure: the desktop shell imports it as is, without React.
|
||||
*/
|
||||
|
||||
export type Catalogue = { [cle: string]: string | Catalogue };
|
||||
export type Parametres = Record<string, string | number>;
|
||||
export type Traduire = (cle: string, parametres?: Parametres) => string;
|
||||
|
||||
/** Une langue proposée, par son code et son nom dans cette langue. */
|
||||
export type LangueDisponible = { code: string; nom: string };
|
||||
|
||||
/** La langue de repli: complète par contrat, vérifiée par `verifier-i18n`. */
|
||||
export const LANGUE_DE_REPLI = 'en';
|
||||
export type Catalog = { [key: string]: string | Catalog };
|
||||
export type Params = Record<string, string | number>;
|
||||
export type Translate = (key: string, params?: Params) => string;
|
||||
|
||||
/**
|
||||
* Une fonction de traduction pour `section` (`viewer`, `desktop`), qui
|
||||
* cherche dans `catalogues` dans l'ordre: la langue choisie, puis l'anglais.
|
||||
* Une clé introuvable partout rend une chaîne vide, jamais la clé brute.
|
||||
* 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 function traduction(langue: string, section: string, catalogues: Catalogue[]): Traduire {
|
||||
const regles = pluriels(langue);
|
||||
return (cle, parametres) => {
|
||||
for (const catalogue of catalogues) {
|
||||
const valeur = chercher(catalogue, `${section}.${cle}`);
|
||||
if (valeur === undefined) continue;
|
||||
const texte = typeof valeur === 'string' ? valeur : pluriel(valeur, regles, parametres);
|
||||
if (texte !== undefined) return interpoler(texte, parametres);
|
||||
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 chercher(catalogue: Catalogue, chemin: string): string | Catalogue | undefined {
|
||||
let noeud: string | Catalogue | undefined = catalogue;
|
||||
for (const morceau of chemin.split('.')) {
|
||||
if (noeud === undefined || typeof noeud === 'string') return undefined;
|
||||
noeud = noeud[morceau];
|
||||
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 noeud;
|
||||
return node;
|
||||
}
|
||||
|
||||
/**
|
||||
* Un pluriel est un objet de formes: une valeur exacte (`"0"`), puis la
|
||||
* catégorie de `Intl.PluralRules` (`one`, `few`, `other`...).
|
||||
* A plural is an object of forms: an exact value (`"0"`), then the
|
||||
* `Intl.PluralRules` category (`one`, `few`, `other`...).
|
||||
*/
|
||||
function pluriel(
|
||||
formes: Catalogue,
|
||||
regles: Intl.PluralRules,
|
||||
parametres: Parametres | undefined,
|
||||
function plural(
|
||||
forms: Catalog,
|
||||
rules: Intl.PluralRules,
|
||||
params: Params | undefined,
|
||||
): string | undefined {
|
||||
const nombre = parametres?.count;
|
||||
if (typeof nombre !== 'number') {
|
||||
return typeof formes.other === 'string' ? formes.other : undefined;
|
||||
const count = params?.count;
|
||||
if (typeof count !== 'number') {
|
||||
return typeof forms.other === 'string' ? forms.other : undefined;
|
||||
}
|
||||
const exacte = formes[String(nombre)];
|
||||
if (typeof exacte === 'string') return exacte;
|
||||
const categorie = formes[regles.select(nombre)];
|
||||
if (typeof categorie === 'string') return categorie;
|
||||
return typeof formes.other === 'string' ? formes.other : undefined;
|
||||
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 pluriels(langue: string): Intl.PluralRules {
|
||||
function pluralRules(language: string): Intl.PluralRules {
|
||||
try {
|
||||
return new Intl.PluralRules(langue);
|
||||
return new Intl.PluralRules(language);
|
||||
} catch {
|
||||
return new Intl.PluralRules(LANGUE_DE_REPLI);
|
||||
return new Intl.PluralRules(FALLBACK_LANGUAGE);
|
||||
}
|
||||
}
|
||||
|
||||
function interpoler(texte: string, parametres: Parametres | undefined): string {
|
||||
if (!parametres) return texte;
|
||||
return texte.replace(/\{(\w+)\}/g, (entier, nom: string) =>
|
||||
nom in parametres ? String(parametres[nom]) : entier,
|
||||
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,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* La langue à afficher: la première des préférences de l'appareil qui existe,
|
||||
* exactement (`pt-BR`) ou par sa langue principale (`fr-CA` donne `fr`),
|
||||
* sinon l'anglais.
|
||||
* 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 choisirLangue(
|
||||
preferences: readonly string[],
|
||||
disponibles: readonly string[],
|
||||
): string {
|
||||
const codes = disponibles.map((code) => code.toLowerCase());
|
||||
export function pickLanguage(preferences: readonly string[], available: readonly string[]): string {
|
||||
const codes = available.map((code) => code.toLowerCase());
|
||||
for (const preference of preferences) {
|
||||
const voulue = preference.toLowerCase();
|
||||
const exacte = codes.indexOf(voulue);
|
||||
if (exacte >= 0) return disponibles[exacte] ?? LANGUE_DE_REPLI;
|
||||
const principale = voulue.split('-')[0];
|
||||
const proche = codes.findIndex((code) => code.split('-')[0] === principale);
|
||||
if (proche >= 0) return disponibles[proche] ?? LANGUE_DE_REPLI;
|
||||
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(LANGUE_DE_REPLI) ? LANGUE_DE_REPLI : (disponibles[0] ?? LANGUE_DE_REPLI);
|
||||
return codes.includes(FALLBACK_LANGUAGE)
|
||||
? FALLBACK_LANGUAGE
|
||||
: (available[0] ?? FALLBACK_LANGUAGE);
|
||||
}
|
||||
@@ -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> = [];
|
||||
|
||||
@@ -7,7 +7,7 @@ function respond(status: number, body: unknown): typeof fetch {
|
||||
}
|
||||
|
||||
describe('exchangeCode', () => {
|
||||
it('rend le chemin de la session, versionné', async () => {
|
||||
it('returns the session path, versioned', async () => {
|
||||
const outcome = await exchangeCode(
|
||||
'k7m4pq',
|
||||
respond(200, {
|
||||
@@ -22,7 +22,7 @@ describe('exchangeCode', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('distingue un code inconnu, expiré, et trop d’essais', async () => {
|
||||
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',
|
||||
});
|
||||
@@ -34,16 +34,16 @@ describe('exchangeCode', () => {
|
||||
).toEqual({ kind: 'too_many_attempts', retryAfterS: 42 });
|
||||
});
|
||||
|
||||
it('ne lève pas quand le réseau échoue', async () => {
|
||||
it('does not throw when the network fails', async () => {
|
||||
const broken: typeof fetch = async () => {
|
||||
throw new TypeError('réseau');
|
||||
throw new TypeError('network');
|
||||
};
|
||||
expect(await exchangeCode('x', broken)).toEqual({ kind: 'network' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('qrDetector', () => {
|
||||
it('se retire quand le navigateur n’a pas BarcodeDetector', () => {
|
||||
it('steps aside when the browser has no BarcodeDetector', () => {
|
||||
expect(qrDetector()).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Appairage sans caméra (#19): le code court affiché par l'hôte, échangé
|
||||
* contre la room et le jeton. Et, quand le navigateur le permet, la lecture du
|
||||
* QR code depuis la page elle-même.
|
||||
* 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';
|
||||
@@ -13,7 +13,7 @@ export type CodeOutcome =
|
||||
| { kind: 'too_many_attempts'; retryAfterS: number }
|
||||
| { kind: 'network' };
|
||||
|
||||
/** Échange un code contre le chemin de la session. Ne lève jamais. */
|
||||
/** Exchanges a code for the session path. Never throws. */
|
||||
export async function exchangeCode(
|
||||
code: string,
|
||||
fetchImpl: typeof fetch = fetch,
|
||||
@@ -46,16 +46,16 @@ export async function exchangeCode(
|
||||
}
|
||||
}
|
||||
|
||||
/** Le minimum de l'API BarcodeDetector dont on se sert. */
|
||||
/** The subset of the BarcodeDetector API in use. */
|
||||
type Detector = {
|
||||
detect(source: CanvasImageSource): Promise<Array<{ rawValue: string }>>;
|
||||
};
|
||||
type DetectorConstructor = new (options: { formats: string[] }) => Detector;
|
||||
|
||||
/**
|
||||
* Un lecteur de QR code, si ce navigateur en expose un. Il faut aussi une
|
||||
* caméra, donc un contexte sécurisé: une page servie en HTTP sur le LAN n'y a
|
||||
* pas droit, et le code court prend le relais.
|
||||
* 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 {
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
} 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,
|
||||
@@ -17,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',
|
||||
@@ -32,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,
|
||||
@@ -47,16 +47,16 @@ 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('lien versionné (#19)', () => {
|
||||
describe('versioned link (#19)', () => {
|
||||
const token = '0123456789abcdef0123456789abcdef';
|
||||
|
||||
it('lit un lien de version 1 et son empreinte', () => {
|
||||
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({
|
||||
@@ -65,38 +65,38 @@ describe('lien versionné (#19)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('accepte un lien sans version, celui des versions précédentes', () => {
|
||||
it('accepts a link without version, the one of earlier releases', () => {
|
||||
expect(parseRoomLocation('/r/abc234', `?t=${token}`).ok).toBe(true);
|
||||
});
|
||||
|
||||
it('dit qu’un lien vient d’une version plus récente', () => {
|
||||
it('says a link comes from a newer version', () => {
|
||||
expect(parseRoomLocation('/r/abc234', `?t=${token}&v=2`)).toEqual({
|
||||
ok: false,
|
||||
reason: 'newer_link',
|
||||
});
|
||||
});
|
||||
|
||||
it('ignore une empreinte mal formée', () => {
|
||||
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('QR code scanné', () => {
|
||||
it('suit une URL de session', () => {
|
||||
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('refuse ce qui n’est pas une session', () => {
|
||||
expect(sessionFromScan('bonjour')).toBeNull();
|
||||
it('rejects what is not a session', () => {
|
||||
expect(sessionFromScan('hello')).toBeNull();
|
||||
expect(sessionFromScan('javascript:alert(1)')).toBeNull();
|
||||
expect(sessionFromScan('https://exemple.fr/')).toBeNull();
|
||||
expect(sessionFromScan('https://example.com/')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('code court', () => {
|
||||
it('se tape comme il s’affiche', () => {
|
||||
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);
|
||||
@@ -106,10 +106,10 @@ describe('code court', () => {
|
||||
});
|
||||
|
||||
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');
|
||||
});
|
||||
});
|
||||
+20
-20
@@ -1,10 +1,10 @@
|
||||
/**
|
||||
* Lecture de la session dans l'URL.
|
||||
* Reading the session from the URL.
|
||||
*
|
||||
* Forme attendue: `/r/<room>?t=<jeton>&v=<version>`, suivie en HTTPS de
|
||||
* `#fp=<empreinte>` (#19). Les 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';
|
||||
@@ -12,7 +12,7 @@ import { LINK_VERSION } from '../proto';
|
||||
export type RoomLocation = {
|
||||
room: string;
|
||||
token: string;
|
||||
/** Empreinte SHA-256 du certificat, en paires hexadécimales, en HTTPS. */
|
||||
/** SHA-256 fingerprint of the certificate, as hex pairs, over HTTPS. */
|
||||
fingerprint?: string;
|
||||
};
|
||||
|
||||
@@ -20,28 +20,28 @@ export type RoomLocationResult =
|
||||
| { ok: true; value: RoomLocation }
|
||||
| { 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}$/;
|
||||
|
||||
/** Empreinte SHA-256: 64 chiffres hexadécimaux. */
|
||||
/** 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 params = new URLSearchParams(search);
|
||||
// Sans `v`, c'est un lien de la 0.4 ou d'avant: même format que la
|
||||
// version 1. Une version plus récente se dit, au lieu d'être mal lue.
|
||||
// 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' };
|
||||
@@ -65,9 +65,9 @@ export function parseRoomLocation(pathname: string, search: string, hash = ''):
|
||||
}
|
||||
|
||||
/**
|
||||
* Le chemin à ouvrir pour un QR code scanné, ou `null` s'il ne porte pas une
|
||||
* session rustscreen. Seuls `http` et `https` sont suivis: un QR code peut
|
||||
* contenir n'importe quoi.
|
||||
* 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;
|
||||
@@ -81,7 +81,7 @@ export function sessionFromScan(text: string): string | null {
|
||||
return parsed.ok ? url.href : null;
|
||||
}
|
||||
|
||||
/** Code court tapé à la main: six caractères de l'alphabet des rooms. */
|
||||
/** Short code typed by hand: six characters of the room alphabet. */
|
||||
export function normalizeCode(input: string): string {
|
||||
return input.replace(/[\s-]/g, '').toLowerCase();
|
||||
}
|
||||
@@ -90,7 +90,7 @@ export function isCompleteCode(code: string): boolean {
|
||||
return ROOM_PATTERN.test(code);
|
||||
}
|
||||
|
||||
/** URL du canal de signalement, qui suit le schéma de la page. */
|
||||
/** 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`;
|
||||
|
||||
@@ -1,38 +1,77 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { boiteTournee, lireRotation, rotationSuivante, surfaceAffichee } from './rotation';
|
||||
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('fait un tour complet par pas de 90 degrés', () => {
|
||||
expect(rotationSuivante(0)).toBe(90);
|
||||
expect(rotationSuivante(270)).toBe(0);
|
||||
it('makes a full turn in steps of 90 degrees', () => {
|
||||
expect(nextRotation(0)).toBe(90);
|
||||
expect(nextRotation(270)).toBe(0);
|
||||
});
|
||||
|
||||
it('échange largeur et hauteur de la boîte sur un quart de tour', () => {
|
||||
expect(boiteTournee(1000, 600, 90)).toMatchObject({ width: 600, height: 1000 });
|
||||
expect(boiteTournee(1000, 600, 180)).toMatchObject({ width: 1000, height: 600 });
|
||||
expect(boiteTournee(1000, 600, 270).transform).toContain('rotate(270deg)');
|
||||
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('garde l’image entière et remplit la scène en portrait', () => {
|
||||
// Tablette en portrait (800×1280), écran partagé en 1920×1080.
|
||||
const scene = { largeur: 800, hauteur: 1280 };
|
||||
const video = { largeur: 1920, hauteur: 1080 };
|
||||
const droite = surfaceAffichee(scene, video, 0);
|
||||
const tournee = surfaceAffichee(scene, video, 90);
|
||||
// Sans rotation, l'image (800×450) occupe à peine plus d'un tiers de la scène.
|
||||
expect((droite.largeur * droite.hauteur) / (800 * 1280)).toBeLessThan(0.36);
|
||||
// Tournée, elle tient entière et prend toute la hauteur disponible.
|
||||
expect(tournee.largeur).toBeLessThanOrEqual(800);
|
||||
expect(tournee.hauteur).toBeLessThanOrEqual(1280);
|
||||
expect(Math.max(tournee.largeur / 800, tournee.hauteur / 1280)).toBeCloseTo(1);
|
||||
// Tournée (720×1280), elle en occupe 90 %: les bandes restent minces.
|
||||
expect((tournee.largeur * tournee.hauteur) / (800 * 1280)).toBeGreaterThan(0.89);
|
||||
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('ignore une valeur gardée invalide', () => {
|
||||
const stockage = { getItem: () => '45', setItem: () => undefined };
|
||||
expect(lireRotation(stockage)).toBe(0);
|
||||
expect(lireRotation({ getItem: () => '270', setItem: () => undefined })).toBe(270);
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,74 +1,96 @@
|
||||
/**
|
||||
* Rotation du flux dans le viewer (#30), par pas de 90 degrés.
|
||||
* Rotation of the stream in the viewer (#30), in steps of 90 degrees.
|
||||
*
|
||||
* Une vidéo tournée d'un quart de tour échange sa largeur et sa hauteur: on
|
||||
* donne donc à la balise la boîte de la scène retournée, puis on la tourne.
|
||||
* `object-fit: contain` garde l'image entière dans cette boîte, sans rien
|
||||
* couper et sans bandes plus larges que nécessaire. Tout se passe dans la
|
||||
* page: aucun message vers l'hôte, aucune reconnexion.
|
||||
* 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 CLE = 'rustscreen.rotation';
|
||||
const KEY = 'rustscreen.rotation';
|
||||
|
||||
export function rotationSuivante(rotation: Rotation): Rotation {
|
||||
export function nextRotation(rotation: Rotation): Rotation {
|
||||
return ((rotation + 90) % 360) as Rotation;
|
||||
}
|
||||
|
||||
/** Taille et transformation de la balise vidéo dans une scène `largeur`×`hauteur`. */
|
||||
export function boiteTournee(
|
||||
largeur: number,
|
||||
hauteur: number,
|
||||
/**
|
||||
* 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 quart = rotation === 90 || rotation === 270;
|
||||
const quarter = rotation === 90 || rotation === 270;
|
||||
return {
|
||||
width: quart ? hauteur : largeur,
|
||||
height: quart ? largeur : hauteur,
|
||||
transform: `translate(-50%, -50%) rotate(${rotation}deg)`,
|
||||
width: quarter ? height : width,
|
||||
height: quarter ? width : height,
|
||||
transform: `translate(-50%, -50%)${mirror ? ' scaleX(-1)' : ''} rotate(${rotation}deg)`,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Part de la scène qu'occupe l'image, pour vérifier qu'aucune rotation ne
|
||||
* gâche la place: c'est ce que `contain` affiche dans la boîte tournée.
|
||||
*/
|
||||
export function surfaceAffichee(
|
||||
scene: { largeur: number; hauteur: number },
|
||||
video: { largeur: number; hauteur: number },
|
||||
rotation: Rotation,
|
||||
): { largeur: number; hauteur: number } {
|
||||
const quart = rotation === 90 || rotation === 270;
|
||||
const [vl, vh] = quart ? [video.hauteur, video.largeur] : [video.largeur, video.hauteur];
|
||||
const echelle = Math.min(scene.largeur / vl, scene.hauteur / vh);
|
||||
return { largeur: vl * echelle, hauteur: vh * echelle };
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
type Stockage = Pick<Storage, 'getItem' | 'setItem'> | null;
|
||||
|
||||
export function lireRotation(storage: Stockage = stockage()): Rotation {
|
||||
export function saveMirror(
|
||||
mirror: boolean,
|
||||
storage: KeyValueStore | null = browserStorage(),
|
||||
): void {
|
||||
try {
|
||||
const valeur = Number(storage?.getItem(CLE));
|
||||
if (valeur === 90 || valeur === 180 || valeur === 270) return valeur;
|
||||
storage?.setItem(MIRROR_KEY, mirror ? '1' : '0');
|
||||
} catch {
|
||||
// Stockage refusé: pas de rotation.
|
||||
// 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 garderRotation(rotation: Rotation, storage: Stockage = stockage()): void {
|
||||
export function saveRotation(
|
||||
rotation: Rotation,
|
||||
storage: KeyValueStore | null = browserStorage(),
|
||||
): void {
|
||||
try {
|
||||
storage?.setItem(CLE, String(rotation));
|
||||
storage?.setItem(KEY, String(rotation));
|
||||
} catch {
|
||||
// Idem.
|
||||
}
|
||||
}
|
||||
|
||||
function stockage(): Storage | null {
|
||||
try {
|
||||
return window.localStorage;
|
||||
} catch {
|
||||
return null;
|
||||
// Same.
|
||||
}
|
||||
}
|
||||
@@ -1,30 +1,30 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { traduction } from './i18n';
|
||||
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);
|
||||
}
|
||||
@@ -32,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',
|
||||
@@ -51,7 +51,7 @@ describe('isRetryable', () => {
|
||||
});
|
||||
|
||||
describe('messageFor', () => {
|
||||
const t = traduction('fr', 'viewer', [
|
||||
const t = createTranslator('fr', 'viewer', [
|
||||
{
|
||||
viewer: {
|
||||
networkFallback: 'Connexion perdue.',
|
||||
@@ -60,12 +60,12 @@ describe('messageFor', () => {
|
||||
},
|
||||
]);
|
||||
|
||||
it('traduit un code connu', () => {
|
||||
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('retombe sur le message réseau pour un code inconnu (hôte plus récent)', () => {
|
||||
expect(messageFor('quelque_chose_de_nouveau', t)).toBe('Connexion perdue.');
|
||||
it('falls back to the network message for an unknown code (newer host)', () => {
|
||||
expect(messageFor('something_new', t)).toBe('Connexion perdue.');
|
||||
});
|
||||
});
|
||||
@@ -1,15 +1,15 @@
|
||||
/**
|
||||
* 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 type { Traduire } from './i18n';
|
||||
import type { Translate } from './i18n';
|
||||
import { deviceId } from './device';
|
||||
import { type WakeReason, watchLifecycle } from './lifecycle';
|
||||
|
||||
@@ -40,17 +40,17 @@ 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',
|
||||
@@ -61,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']);
|
||||
|
||||
@@ -70,33 +70,33 @@ 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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Le message d'un code d'erreur, dans la langue de `t`. Un code que ce viewer
|
||||
* ne connaît pas (hôte plus récent) devient le message réseau générique.
|
||||
* 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: Traduire): string {
|
||||
export function messageFor(code: string, t: Translate): string {
|
||||
return t(`errors.${code}`) || t('networkFallback');
|
||||
}
|
||||
|
||||
@@ -105,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;
|
||||
@@ -138,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?.();
|
||||
@@ -149,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;
|
||||
@@ -160,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;
|
||||
@@ -200,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;
|
||||
}
|
||||
@@ -227,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) {
|
||||
@@ -251,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;
|
||||
@@ -268,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.
|
||||
});
|
||||
}
|
||||
|
||||
@@ -300,8 +300,8 @@ export class ViewerSession {
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -327,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;
|
||||
@@ -412,8 +412,8 @@ export class ViewerSession {
|
||||
|
||||
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();
|
||||
@@ -429,13 +429,13 @@ export class ViewerSession {
|
||||
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) {
|
||||
@@ -449,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;
|
||||
@@ -482,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';
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -1,48 +1,68 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { garderTheme, lireTheme, themeSuivant } from './theme';
|
||||
import type { KeyValueStore } from './storage';
|
||||
import { nextTheme, readTheme, saveTheme } from './theme';
|
||||
|
||||
function memoire(): Pick<Storage, 'getItem' | 'setItem'> {
|
||||
const valeurs = new Map<string, string>();
|
||||
function memory(): KeyValueStore {
|
||||
const values = new Map<string, string>();
|
||||
return {
|
||||
getItem: (cle) => valeurs.get(cle) ?? null,
|
||||
setItem: (cle, valeur) => {
|
||||
valeurs.set(cle, valeur);
|
||||
getItem: (key) => values.get(key) ?? null,
|
||||
setItem: (key, value) => {
|
||||
values.set(key, value);
|
||||
},
|
||||
removeItem: (key) => {
|
||||
values.delete(key);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('thème (#28)', () => {
|
||||
it('suit le système au premier accès', () => {
|
||||
expect(lireTheme(memoire())).toBe('systeme');
|
||||
expect(lireTheme(null)).toBe('systeme');
|
||||
describe('theme (#28)', () => {
|
||||
it('follows the system on first visit', () => {
|
||||
expect(readTheme(memory())).toBe('system');
|
||||
expect(readTheme(null)).toBe('system');
|
||||
});
|
||||
|
||||
it('garde le choix de l’appareil', () => {
|
||||
const stockage = memoire();
|
||||
garderTheme('sombre', stockage);
|
||||
expect(lireTheme(stockage)).toBe('sombre');
|
||||
it('keeps the device choice', () => {
|
||||
const storage = memory();
|
||||
saveTheme('dark', storage);
|
||||
expect(readTheme(storage)).toBe('dark');
|
||||
});
|
||||
|
||||
it('ignore une valeur inconnue ou un stockage refusé', () => {
|
||||
const stockage = memoire();
|
||||
stockage.setItem('rustscreen.theme', 'violet');
|
||||
expect(lireTheme(stockage)).toBe('systeme');
|
||||
const refuse = {
|
||||
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('refusé');
|
||||
throw new Error('denied');
|
||||
},
|
||||
setItem: () => {
|
||||
throw new Error('refusé');
|
||||
throw new Error('denied');
|
||||
},
|
||||
removeItem: () => {
|
||||
throw new Error('denied');
|
||||
},
|
||||
};
|
||||
expect(lireTheme(refuse)).toBe('systeme');
|
||||
expect(() => garderTheme('clair', refuse)).not.toThrow();
|
||||
expect(readTheme(denied)).toBe('system');
|
||||
expect(() => saveTheme('light', denied)).not.toThrow();
|
||||
});
|
||||
|
||||
it('fait le tour des trois valeurs', () => {
|
||||
expect(themeSuivant('systeme')).toBe('clair');
|
||||
expect(themeSuivant('clair')).toBe('sombre');
|
||||
expect(themeSuivant('sombre')).toBe('systeme');
|
||||
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);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,51 +1,53 @@
|
||||
/**
|
||||
* Thème du viewer (#28): celui de l'appareil par défaut, clair ou sombre sur
|
||||
* demande. Le choix est gardé par l'appareil, pas par l'hôte: deux tablettes
|
||||
* peuvent préférer l'inverse l'une de l'autre.
|
||||
* 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.
|
||||
*
|
||||
* Mêmes noms de valeurs que le réglage de l'hôte (`rs-store::Theme`), pour que
|
||||
* les feuilles de style des deux applications se lisent pareil.
|
||||
* 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 = 'systeme' | 'clair' | 'sombre';
|
||||
export type Theme = 'system' | 'light' | 'dark';
|
||||
|
||||
const CLE = 'rustscreen.theme';
|
||||
const ORDRE: readonly Theme[] = ['systeme', 'clair', 'sombre'];
|
||||
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',
|
||||
};
|
||||
|
||||
type Stockage = Pick<Storage, 'getItem' | 'setItem'> | null;
|
||||
|
||||
export function lireTheme(storage: Stockage = stockage()): Theme {
|
||||
export function readTheme(storage: KeyValueStore | null = browserStorage()): Theme {
|
||||
try {
|
||||
const valeur = storage?.getItem(CLE);
|
||||
if (valeur && (ORDRE as readonly string[]).includes(valeur)) return valeur as Theme;
|
||||
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 {
|
||||
// Stockage refusé (navigation privée): le thème du système.
|
||||
// Storage denied (private browsing): the system theme.
|
||||
}
|
||||
return 'systeme';
|
||||
return 'system';
|
||||
}
|
||||
|
||||
export function garderTheme(theme: Theme, storage: Stockage = stockage()): void {
|
||||
export function saveTheme(theme: Theme, storage: KeyValueStore | null = browserStorage()): void {
|
||||
try {
|
||||
storage?.setItem(CLE, theme);
|
||||
storage?.setItem(KEY, theme);
|
||||
} catch {
|
||||
// Idem: le choix vaut pour la page seulement.
|
||||
// Same: the choice holds for the page only.
|
||||
}
|
||||
}
|
||||
|
||||
/** Le thème suivant, pour un bouton unique qui fait le tour des trois. */
|
||||
export function themeSuivant(theme: Theme): Theme {
|
||||
return ORDRE[(ORDRE.indexOf(theme) + 1) % ORDRE.length] ?? 'systeme';
|
||||
/** 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';
|
||||
}
|
||||
|
||||
/** Pose le thème sur la racine: la feuille de style fait le reste. */
|
||||
export function appliquerTheme(theme: Theme, racine: HTMLElement = document.documentElement): void {
|
||||
racine.dataset.theme = theme;
|
||||
}
|
||||
|
||||
function stockage(): Storage | null {
|
||||
try {
|
||||
return window.localStorage;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
/** Sets the theme on the root element: the style sheet does the rest. */
|
||||
export function applyTheme(theme: Theme, root: HTMLElement = document.documentElement): void {
|
||||
root.dataset.theme = theme;
|
||||
}
|
||||
@@ -0,0 +1,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;
|
||||
}
|
||||
+15
-15
@@ -1,35 +1,35 @@
|
||||
import { StrictMode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { App } from './App';
|
||||
import { chargerCatalogues, chargerLangues, I18nProvider, langueDeDepart } from './i18n';
|
||||
import { appliquerTheme, lireTheme } from './lib/theme';
|
||||
import { I18nProvider, initialLanguage, loadCatalogs, loadLanguages } from './i18n';
|
||||
import { applyTheme, readTheme } from './lib/theme';
|
||||
import './styles.css';
|
||||
|
||||
// Avant le premier rendu: pas d'éclair blanc sur un appareil réglé en sombre.
|
||||
appliquerTheme(lireTheme());
|
||||
// Before the first render: no white flash on a device set to dark.
|
||||
applyTheme(readTheme());
|
||||
|
||||
const root = document.getElementById('root');
|
||||
if (!root) throw new Error('élément racine absent');
|
||||
if (!root) throw new Error('root element missing');
|
||||
|
||||
async function demarrer(element: HTMLElement) {
|
||||
const langues = await chargerLangues();
|
||||
const langue = langueDeDepart(langues);
|
||||
const catalogues = await chargerCatalogues(langue);
|
||||
if (catalogues.length === 0) {
|
||||
// Sans textes, l'interface ne peut rien dire: ce seul message reste en
|
||||
// dur, dans les deux langues complètes, faute de mieux.
|
||||
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 = langue;
|
||||
document.documentElement.lang = language;
|
||||
createRoot(element).render(
|
||||
<StrictMode>
|
||||
<I18nProvider initial={{ langue, catalogues }} langues={langues}>
|
||||
<I18nProvider initial={{ language, catalogs }} languages={languages}>
|
||||
<App />
|
||||
</I18nProvider>
|
||||
</StrictMode>,
|
||||
);
|
||||
}
|
||||
|
||||
void demarrer(root);
|
||||
void start(root);
|
||||
@@ -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" };
|
||||
@@ -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,6 +1,6 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
/**
|
||||
* Le code court tapé par le spectateur.
|
||||
* The short code typed by the viewer.
|
||||
*/
|
||||
export type PairingRequest = { code: string, };
|
||||
@@ -3,6 +3,6 @@ import type { RoomId } from "./RoomId";
|
||||
import type { SessionToken } from "./SessionToken";
|
||||
|
||||
/**
|
||||
* La réponse de l'hôte à un code court.
|
||||
* The host's answer to a short code.
|
||||
*/
|
||||
export type PairingResponse = { "status": "accepted", room: RoomId, token: SessionToken, } | { "status": "unknown" } | { "status": "expired" } | { "status": "too_many_attempts", retry_after_s: number, };
|
||||
Loaded 100 of 206 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user