From 0c24b2b5d298396532a1f3772200217ac4146c7f Mon Sep 17 00:00:00 2001 From: Guillaume Assier Date: Tue, 27 Oct 2026 11:11:34 +0100 Subject: [PATCH] refactor: code en anglais, rustscreen ouvre l'application de bureau MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- .gitea/workflows/ci.yml | 125 +- .gitea/workflows/release.yml | 82 +- AGENTS.md | 64 +- Makefile | 24 +- README.md | 7 +- apps/desktop/package.json | 4 +- apps/desktop/src-tauri/Cargo.toml | 26 +- .../src-tauri/capabilities/default.json | 2 +- apps/desktop/src-tauri/src/barre.rs | 308 ----- apps/desktop/src-tauri/src/main.rs | 340 +++--- apps/desktop/src-tauri/src/tray.rs | 302 +++++ apps/desktop/src-tauri/tauri.conf.json | 3 +- apps/desktop/src/App.tsx | 276 +++-- .../desktop/src/bindings/AppareilConfiance.ts | 8 - apps/desktop/src/bindings/AppareilVu.ts | 14 - apps/desktop/src/bindings/Application.ts | 14 - apps/desktop/src/bindings/Arret.ts | 11 - apps/desktop/src/bindings/Capabilities.ts | 15 + apps/desktop/src/bindings/Capacites.ts | 15 - apps/desktop/src/bindings/CloseAction.ts | 6 + apps/desktop/src/bindings/Codec.ts | 4 +- apps/desktop/src/bindings/Etat.ts | 36 - apps/desktop/src/bindings/Fermeture.ts | 6 - apps/desktop/src/bindings/HostState.ts | 36 + ...nterfaceProposee.ts => InterfaceOption.ts} | 4 +- apps/desktop/src/bindings/Label.ts | 7 + apps/desktop/src/bindings/Libelle.ts | 7 - apps/desktop/src/bindings/NoteSource.ts | 7 - apps/desktop/src/bindings/Partage.ts | 42 - apps/desktop/src/bindings/Phase.ts | 4 +- apps/desktop/src/bindings/Refus.ts | 7 - apps/desktop/src/bindings/Reglages.ts | 47 - apps/desktop/src/bindings/Rejection.ts | 7 + apps/desktop/src/bindings/Settings.ts | 53 + apps/desktop/src/bindings/SettingsOutcome.ts | 14 + apps/desktop/src/bindings/Share.ts | 42 + apps/desktop/src/bindings/SharedSource.ts | 16 + apps/desktop/src/bindings/SourceChoice.ts | 15 + apps/desktop/src/bindings/SourceChoisie.ts | 15 - apps/desktop/src/bindings/SourceNote.ts | 7 + apps/desktop/src/bindings/SourceOption.ts | 35 + apps/desktop/src/bindings/SourcePartagee.ts | 16 - apps/desktop/src/bindings/SourceProposee.ts | 36 - apps/desktop/src/bindings/Stop.ts | 11 + apps/desktop/src/bindings/Theme.ts | 4 +- apps/desktop/src/bindings/TrustedDevice.ts | 8 + apps/desktop/src/bindings/ViewerDevice.ts | 14 + apps/desktop/src/components/ChoixSource.tsx | 83 -- apps/desktop/src/components/ConfirmQuit.tsx | 52 + .../desktop/src/components/PanneauPartage.tsx | 142 --- apps/desktop/src/components/Reglages.tsx | 304 ----- .../desktop/src/components/SettingsDialog.tsx | 303 +++++ apps/desktop/src/components/SharePanel.tsx | 142 +++ apps/desktop/src/components/SourcePicker.tsx | 83 ++ apps/desktop/src/i18n.tsx | 78 +- apps/desktop/src/lib/host.ts | 62 + apps/desktop/src/lib/hote.ts | 57 - apps/desktop/src/lib/view.test.ts | 196 +++ apps/desktop/src/lib/view.ts | 208 ++++ apps/desktop/src/lib/vue.test.ts | 176 --- apps/desktop/src/lib/vue.ts | 209 ---- apps/desktop/src/main.tsx | 6 +- apps/desktop/src/styles.css | 310 ++--- apps/desktop/vite.config.ts | 2 +- apps/viewer/package.json | 4 +- apps/viewer/src/App.tsx | 141 ++- apps/viewer/src/components/ChoixLangue.tsx | 27 - apps/viewer/src/components/ErrorPanel.tsx | 6 +- apps/viewer/src/components/LanguagePicker.tsx | 27 + apps/viewer/src/components/Pairing.tsx | 18 +- apps/viewer/src/components/StatsBar.tsx | 10 +- apps/viewer/src/components/StatusBadge.tsx | 6 +- apps/viewer/src/components/VideoStage.tsx | 64 +- apps/viewer/src/i18n.tsx | 128 +- apps/viewer/src/lib/controls.test.ts | 52 + apps/viewer/src/lib/controls.ts | 55 + apps/viewer/src/lib/device.test.ts | 76 +- apps/viewer/src/lib/device.ts | 67 +- apps/viewer/src/lib/i18n.test.ts | 64 +- apps/viewer/src/lib/i18n.ts | 147 +-- apps/viewer/src/lib/lifecycle.ts | 17 +- apps/viewer/src/lib/pairing.test.ts | 10 +- apps/viewer/src/lib/pairing.ts | 16 +- apps/viewer/src/lib/reconnect.test.ts | 16 +- apps/viewer/src/lib/resume.test.ts | 78 +- apps/viewer/src/lib/room.test.ts | 40 +- apps/viewer/src/lib/room.ts | 40 +- apps/viewer/src/lib/rotation.test.ts | 91 +- apps/viewer/src/lib/rotation.ts | 114 +- apps/viewer/src/lib/session.test.ts | 22 +- apps/viewer/src/lib/session.ts | 118 +- apps/viewer/src/lib/storage.ts | 51 + apps/viewer/src/lib/theme.test.ts | 74 +- apps/viewer/src/lib/theme.ts | 66 +- apps/viewer/src/lib/useActivity.ts | 26 + apps/viewer/src/main.tsx | 30 +- apps/viewer/src/proto/ClientMessage.ts | 2 +- apps/viewer/src/proto/DeviceInfo.ts | 2 +- apps/viewer/src/proto/PairingRequest.ts | 2 +- apps/viewer/src/proto/PairingResponse.ts | 2 +- apps/viewer/src/proto/QualityPreset.ts | 2 +- apps/viewer/src/proto/RoomId.ts | 4 +- apps/viewer/src/proto/ServerMessage.ts | 4 +- apps/viewer/src/proto/SessionToken.ts | 2 +- apps/viewer/src/proto/SourceInfo.ts | 2 +- apps/viewer/src/proto/SourceKind.ts | 4 +- apps/viewer/src/proto/index.ts | 8 +- apps/viewer/src/styles.css | 65 +- apps/viewer/vite.config.ts | 36 +- assets/rustscreen.desktop | 6 +- crates/rs-capture/Cargo.toml | 10 +- crates/rs-capture/src/backend.rs | 111 +- crates/rs-capture/src/cadence.rs | 22 +- crates/rs-capture/src/frame.rs | 26 +- crates/rs-capture/src/lib.rs | 17 +- crates/rs-capture/src/pipewire.rs | 639 +++++----- crates/rs-capture/src/pixels.rs | 98 +- crates/rs-capture/src/source.rs | 16 +- crates/rs-capture/src/synthetic.rs | 53 +- crates/rs-capture/src/x11.rs | 738 +++++------ crates/rs-codec/Cargo.toml | 6 +- crates/rs-codec/examples/bench_codecs.rs | 154 +-- crates/rs-codec/src/color.rs | 84 +- crates/rs-codec/src/encoder.rs | 229 ++-- crates/rs-codec/src/frame.rs | 58 +- crates/rs-codec/src/ivf.rs | 22 +- crates/rs-codec/src/lib.rs | 16 +- crates/rs-codec/src/pipeline.rs | 245 ++-- crates/rs-codec/src/vpx.rs | 421 ++++--- crates/rs-diag/Cargo.toml | 6 +- crates/rs-diag/src/archive.rs | 356 +++--- crates/rs-diag/src/expurger.rs | 151 --- crates/rs-diag/src/journal.rs | 142 --- crates/rs-diag/src/lib.rs | 31 +- crates/rs-diag/src/log.rs | 140 +++ crates/rs-diag/src/redact.rs | 152 +++ crates/rs-platform/Cargo.toml | 2 +- crates/rs-platform/src/autostart.rs | 89 ++ crates/rs-platform/src/demarrage.rs | 89 -- crates/rs-platform/src/display.rs | 178 ++- crates/rs-platform/src/lib.rs | 44 +- crates/rs-platform/src/network.rs | 131 ++ crates/rs-platform/src/portal.rs | 654 +++++----- crates/rs-platform/src/reseau.rs | 130 -- crates/rs-platform/src/sleep.rs | 392 ++++++ crates/rs-platform/src/veille.rs | 398 ------ crates/rs-proto/Cargo.toml | 2 +- crates/rs-proto/src/appairage.rs | 70 -- crates/rs-proto/src/lib.rs | 20 +- crates/rs-proto/src/messages.rs | 48 +- crates/rs-proto/src/pairing.rs | 70 ++ crates/rs-proto/src/session.rs | 32 +- crates/rs-rtc/Cargo.toml | 2 +- crates/rs-rtc/src/driver.rs | 83 +- crates/rs-rtc/src/lib.rs | 16 +- crates/rs-rtc/src/session.rs | 208 ++-- crates/rs-session/Cargo.toml | 4 +- crates/rs-session/examples/pipewire_local.rs | 34 +- crates/rs-session/src/bin/rustscreen-cli.rs | 551 +++++++++ crates/rs-session/src/bin/rustscreen.rs | 525 -------- crates/rs-session/src/capture.rs | 397 +++--- crates/rs-session/src/diagnostics.rs | 89 +- crates/rs-session/src/etat.rs | 265 ---- crates/rs-session/src/host.rs | 1081 +++++++++++++++++ crates/rs-session/src/hote.rs | 1071 ---------------- crates/rs-session/src/lib.rs | 40 +- crates/rs-session/src/media.rs | 109 +- crates/rs-session/src/sources.rs | 283 +++-- crates/rs-session/src/state.rs | 265 ++++ .../tests/aucune_connexion_sortante.rs | 177 --- crates/rs-session/tests/host.rs | 280 +++++ crates/rs-session/tests/hote.rs | 293 ----- .../tests/no_outbound_connection.rs | 173 +++ crates/rs-signaling/Cargo.toml | 2 +- crates/rs-signaling/assets/demo.html | 38 +- crates/rs-signaling/assets/host.html | 216 ++-- crates/rs-signaling/build.rs | 44 +- crates/rs-signaling/src/lib.rs | 21 +- crates/rs-signaling/src/locales.rs | 51 +- crates/rs-signaling/src/qr.rs | 66 +- crates/rs-signaling/src/room.rs | 617 +++++----- crates/rs-signaling/src/server.rs | 487 ++++---- crates/rs-signaling/src/tls.rs | 42 +- crates/rs-store/Cargo.toml | 5 +- crates/rs-store/src/lib.rs | 910 ++++++++------ docs/ARCHITECTURE.md | 2 +- docs/PACKAGING.md | 18 +- docs/adr/0001-tauri-et-front-typescript.md | 2 +- .../0009-capture-wayland-et-ecran-virtuel.md | 4 +- docs/capture-wayland.md | 8 +- docs/hote.md | 4 +- docs/virtual-display.md | 4 +- flake.nix | 54 +- locales/en.json | 204 ++-- locales/fr.json | 204 ++-- nix/desktop.nix | 225 ++++ nix/libvpx.nix | 25 +- nix/package.nix | 54 +- scripts/__pycache__/make-icon.cpython-312.pyc | Bin 0 -> 5297 bytes .../publish-release.cpython-312.pyc | Bin 0 -> 8551 bytes scripts/build-appimage.sh | 84 +- scripts/build-libvpx.sh | 30 +- scripts/check-i18n.mjs | 192 +++ scripts/make-icon.py | 118 +- scripts/publish-release.py | 182 +-- scripts/verifier-i18n.mjs | 190 --- 206 files changed, 11903 insertions(+), 10839 deletions(-) delete mode 100644 apps/desktop/src-tauri/src/barre.rs create mode 100644 apps/desktop/src-tauri/src/tray.rs delete mode 100644 apps/desktop/src/bindings/AppareilConfiance.ts delete mode 100644 apps/desktop/src/bindings/AppareilVu.ts delete mode 100644 apps/desktop/src/bindings/Application.ts delete mode 100644 apps/desktop/src/bindings/Arret.ts create mode 100644 apps/desktop/src/bindings/Capabilities.ts delete mode 100644 apps/desktop/src/bindings/Capacites.ts create mode 100644 apps/desktop/src/bindings/CloseAction.ts delete mode 100644 apps/desktop/src/bindings/Etat.ts delete mode 100644 apps/desktop/src/bindings/Fermeture.ts create mode 100644 apps/desktop/src/bindings/HostState.ts rename apps/desktop/src/bindings/{InterfaceProposee.ts => InterfaceOption.ts} (55%) create mode 100644 apps/desktop/src/bindings/Label.ts delete mode 100644 apps/desktop/src/bindings/Libelle.ts delete mode 100644 apps/desktop/src/bindings/NoteSource.ts delete mode 100644 apps/desktop/src/bindings/Partage.ts delete mode 100644 apps/desktop/src/bindings/Refus.ts delete mode 100644 apps/desktop/src/bindings/Reglages.ts create mode 100644 apps/desktop/src/bindings/Rejection.ts create mode 100644 apps/desktop/src/bindings/Settings.ts create mode 100644 apps/desktop/src/bindings/SettingsOutcome.ts create mode 100644 apps/desktop/src/bindings/Share.ts create mode 100644 apps/desktop/src/bindings/SharedSource.ts create mode 100644 apps/desktop/src/bindings/SourceChoice.ts delete mode 100644 apps/desktop/src/bindings/SourceChoisie.ts create mode 100644 apps/desktop/src/bindings/SourceNote.ts create mode 100644 apps/desktop/src/bindings/SourceOption.ts delete mode 100644 apps/desktop/src/bindings/SourcePartagee.ts delete mode 100644 apps/desktop/src/bindings/SourceProposee.ts create mode 100644 apps/desktop/src/bindings/Stop.ts create mode 100644 apps/desktop/src/bindings/TrustedDevice.ts create mode 100644 apps/desktop/src/bindings/ViewerDevice.ts delete mode 100644 apps/desktop/src/components/ChoixSource.tsx create mode 100644 apps/desktop/src/components/ConfirmQuit.tsx delete mode 100644 apps/desktop/src/components/PanneauPartage.tsx delete mode 100644 apps/desktop/src/components/Reglages.tsx create mode 100644 apps/desktop/src/components/SettingsDialog.tsx create mode 100644 apps/desktop/src/components/SharePanel.tsx create mode 100644 apps/desktop/src/components/SourcePicker.tsx create mode 100644 apps/desktop/src/lib/host.ts delete mode 100644 apps/desktop/src/lib/hote.ts create mode 100644 apps/desktop/src/lib/view.test.ts create mode 100644 apps/desktop/src/lib/view.ts delete mode 100644 apps/desktop/src/lib/vue.test.ts delete mode 100644 apps/desktop/src/lib/vue.ts delete mode 100644 apps/viewer/src/components/ChoixLangue.tsx create mode 100644 apps/viewer/src/components/LanguagePicker.tsx create mode 100644 apps/viewer/src/lib/controls.test.ts create mode 100644 apps/viewer/src/lib/controls.ts create mode 100644 apps/viewer/src/lib/storage.ts create mode 100644 apps/viewer/src/lib/useActivity.ts delete mode 100644 crates/rs-diag/src/expurger.rs delete mode 100644 crates/rs-diag/src/journal.rs create mode 100644 crates/rs-diag/src/log.rs create mode 100644 crates/rs-diag/src/redact.rs create mode 100644 crates/rs-platform/src/autostart.rs delete mode 100644 crates/rs-platform/src/demarrage.rs create mode 100644 crates/rs-platform/src/network.rs delete mode 100644 crates/rs-platform/src/reseau.rs create mode 100644 crates/rs-platform/src/sleep.rs delete mode 100644 crates/rs-platform/src/veille.rs delete mode 100644 crates/rs-proto/src/appairage.rs create mode 100644 crates/rs-proto/src/pairing.rs create mode 100644 crates/rs-session/src/bin/rustscreen-cli.rs delete mode 100644 crates/rs-session/src/bin/rustscreen.rs delete mode 100644 crates/rs-session/src/etat.rs create mode 100644 crates/rs-session/src/host.rs delete mode 100644 crates/rs-session/src/hote.rs create mode 100644 crates/rs-session/src/state.rs delete mode 100644 crates/rs-session/tests/aucune_connexion_sortante.rs create mode 100644 crates/rs-session/tests/host.rs delete mode 100644 crates/rs-session/tests/hote.rs create mode 100644 crates/rs-session/tests/no_outbound_connection.rs create mode 100644 nix/desktop.nix create mode 100644 scripts/__pycache__/make-icon.cpython-312.pyc create mode 100644 scripts/__pycache__/publish-release.cpython-312.pyc create mode 100644 scripts/check-i18n.mjs delete mode 100644 scripts/verifier-i18n.mjs diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index e0fdb9f..121421c 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -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 diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index fc8d941..12ccb3f 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -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" diff --git a/AGENTS.md b/AGENTS.md index ab2ba73..2572dbc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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/.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`). diff --git a/Makefile b/Makefile index 80dd95d..adcf574 100644 --- a/Makefile +++ b/Makefile @@ -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 diff --git a/README.md b/README.md index 81cf6ff..204f04f 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/apps/desktop/package.json b/apps/desktop/package.json index a4923df..f40fb70 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -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" }, diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 43b19db..2b6d9fc 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -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] diff --git a/apps/desktop/src-tauri/capabilities/default.json b/apps/desktop/src-tauri/capabilities/default.json index 34f82b5..99c8120 100644 --- a/apps/desktop/src-tauri/capabilities/default.json +++ b/apps/desktop/src-tauri/capabilities/default.json @@ -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"] } diff --git a/apps/desktop/src-tauri/src/barre.rs b/apps/desktop/src-tauri/src/barre.rs deleted file mode 100644 index cfa77bf..0000000 --- a/apps/desktop/src-tauri/src/barre.rs +++ /dev/null @@ -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 { - icone: TrayIcon, - statut: MenuItem, - ouvrir: MenuItem, - demarrer: MenuItem, - arreter: MenuItem, - quitter: MenuItem, - repos: Image<'static>, - direct: Image<'static>, - textes: Mutex, -} - -impl Barre { - /// 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, - au_clic: impl Fn(&AppHandle, &str) + Send + Sync + 'static, - ) -> Option { - if !disponible() { - tracing::info!("pas de barre système sur ce bureau: fenêtre seule"); - return None; - } - let construire = || -> tauri::Result { - 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(app: &AppHandle) { - 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) -} diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs index 8d0d77c..f96e607 100644 --- a/apps/desktop/src-tauri/src/main.rs +++ b/apps/desktop/src-tauri/src/main.rs @@ -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>); +struct LastSource(Mutex>); -/// 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>>); +/// The system tray icon, if this desktop has one: without it, hiding the +/// window would make the application impossible to find. +struct MaybeTray(Option>>); -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::() +fn last_source_known(app: &tauri::AppHandle) -> bool { + app.state::() .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, ()> { - Ok(hote.sources().await) +async fn sources(host: State<'_, Host>) -> Result, ()> { + 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> { - hote.modifier_reglages(reglages).await +async fn update_settings( + host: State<'_, Host>, + settings: Settings, +) -> Result> { + host.update_settings(settings).await } #[tauri::command] -fn interfaces(hote: State<'_, Hote>) -> Vec { - hote.interfaces() +fn interfaces(host: State<'_, Host>) -> Vec { + 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 { - let hote = hote.inner().clone(); +async fn export_diagnostics(host: State<'_, Host>) -> Result { + 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::().inner().clone(); +/// A click in the system tray menu. +fn on_tray_click(app: &tauri::AppHandle, id: &str) { + let host = app.state::().inner().clone(); match id { - barre::OUVRIR => barre::montrer(app), - barre::DEMARRER => { - let derniere = app - .state::() + tray::OPEN => tray::show(app), + tray::START => { + let last = app + .state::() .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::(); + 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> { + 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::(); - 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::(); + 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::().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::().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::().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::().inner().clone(); + tauri::async_runtime::block_on(host.stop()); } }); - drop(journal); + drop(log); } diff --git a/apps/desktop/src-tauri/src/tray.rs b/apps/desktop/src-tauri/src/tray.rs new file mode 100644 index 0000000..6fde64b --- /dev/null +++ b/apps/desktop/src-tauri/src/tray.rs @@ -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 { + icon: TrayIcon, + status: MenuItem, + open: MenuItem, + start: MenuItem, + stop: MenuItem, + quit: MenuItem, + idle: Image<'static>, + live: Image<'static>, + texts: Mutex, +} + +impl Tray { + /// 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, + on_click: impl Fn(&AppHandle, &str) + Send + Sync + 'static, + ) -> Option { + if !available() { + tracing::info!("no system tray on this desktop: window only"); + return None; + } + let build = || -> tauri::Result { + 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(app: &AppHandle) { + 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) +} diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index aae7cc4..4175d97 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -15,7 +15,8 @@ "width": 1100, "height": 760, "minWidth": 800, - "minHeight": 560 + "minHeight": 560, + "visible": false } ], "security": { diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx index 945a1a2..96c1777 100644 --- a/apps/desktop/src/App.tsx +++ b/apps/desktop/src/App.tsx @@ -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(null); +export function App({ host }: { host: Host }) { + const [setting, setSetting] = useState(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 ( - - + + ); } -function Interface({ hote, onLangue }: { hote: Hote; onLangue: (code: string | null) => void }) { - const { t, langue } = useI18n(); - const [etat, setEtat] = useState(null); - const [sources, setSources] = useState(null); - const [selection, setSelection] = useState(null); - const [envoi, setEnvoi] = useState(false); - const [reglagesOuverts, setReglagesOuverts] = useState(false); - const [theme, setTheme] = useState('systeme'); +function Shell({ host, onLanguage }: { host: Host; onLanguage: (code: string | null) => void }) { + const { t, language } = useI18n(); + const [state, setState] = useState(null); + const [sources, setSources] = useState(null); + const [selection, setSelection] = useState(null); + const [sending, setSending] = useState(false); + const [settingsOpen, setSettingsOpen] = useState(false); + const [confirmQuit, setConfirmQuit] = useState(false); + const [theme, setTheme] = useState('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
{t('titre')}
; + if (!state) { + return
{t('title')}
; } - const boutons = actions(etat, selection, envoi); - const etiquette = statut(etat, t); - const envoyer = async (commande: () => Promise) => { - setEnvoi(true); + const buttons = actions(state, selection, sending); + const badge = status(state, t); + const send = async (command: () => Promise) => { + 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 (
-
-

{t('titre')}

- - {etiquette.texte} +
+

{t('title')}

+ + {badge.text} - {etat.phase === 'en_cours' && ( - - {etat.veille_inhibee.length > 0 ? t('veille') : t('veilleAbsente')} + {state.phase === 'live' && ( + + {state.sleep_inhibited.length > 0 ? t('sleepInhibited') : t('sleepNotInhibited')} )} - -
-
- +
+ - {etat.phase === 'en_cours' && etat.partage ? ( - envoyer(() => hote.deconnecter(connexion))} - onNouveauCode={() => envoyer(() => hote.regenererAcces())} + {state.phase === 'live' && state.share ? ( + send(() => host.disconnect(connection))} + onNewCode={() => send(() => host.regenerateAccess())} /> ) : ( - )}
-
- {etat.phase === 'demarrage' && ( -

- {portail ? t('attenteBureau') : t('attente')} +

+ {state.phase === 'starting' && ( +

+ {portal ? t('waitingDesktop') : t('waiting')}

)} - - {boutons.demarrer.visible && ( + + {buttons.start.visible && ( )} - {boutons.annuler.visible && ( + {buttons.cancel.visible && ( )} - {boutons.arreter.visible && ( + {buttons.stop.visible && ( )}
- {reglagesOuverts && ( - setReglagesOuverts(false)} - onEnregistre={(r) => { - setTheme(r.theme); - onLangue(r.langue); + {confirmQuit && ( + setConfirmQuit(false)} + onQuit={(dontAskAgain) => { + void host.quit(dontAskAgain); + }} + /> + )} + {settingsOpen && ( + 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' && ( -
- {t('erreurDemarrage')} {etat.erreur} + {state.error && state.phase === 'stopped' && ( +
+ {t('startFailed')} {state.error}
)} - {etat.arret && etat.phase === 'arrete' && ( -
- {t('arretBureau')} {etat.arret.raison} + {state.stop && state.phase === 'stopped' && ( +
+ {t('stoppedByDesktop')} {state.stop.reason}
)} - {etat.reglages_recuperes &&
{etat.reglages_recuperes}
} - {etat.avertissements.map((a) => ( -
- {a} + {state.settings_recovered &&
{state.settings_recovered}
} + {state.warnings.map((w) => ( +
+ {w}
))} - {etat.reglages_en_attente.length > 0 && ( -
- {t('enAttente')} {etat.reglages_en_attente.join('; ')} + {state.pending_settings.length > 0 && ( +
+ {t('pendingSettings')} {state.pending_settings.join('; ')}
)} diff --git a/apps/desktop/src/bindings/AppareilConfiance.ts b/apps/desktop/src/bindings/AppareilConfiance.ts deleted file mode 100644 index ec992f0..0000000 --- a/apps/desktop/src/bindings/AppareilConfiance.ts +++ /dev/null @@ -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, }; diff --git a/apps/desktop/src/bindings/AppareilVu.ts b/apps/desktop/src/bindings/AppareilVu.ts deleted file mode 100644 index f126e68..0000000 --- a/apps/desktop/src/bindings/AppareilVu.ts +++ /dev/null @@ -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, }; diff --git a/apps/desktop/src/bindings/Application.ts b/apps/desktop/src/bindings/Application.ts deleted file mode 100644 index e3892d3..0000000 --- a/apps/desktop/src/bindings/Application.ts +++ /dev/null @@ -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, -/** - * Champs qui attendent le prochain partage, avec la raison. - */ -au_prochain_partage: Array, }; diff --git a/apps/desktop/src/bindings/Arret.ts b/apps/desktop/src/bindings/Arret.ts deleted file mode 100644 index e766786..0000000 --- a/apps/desktop/src/bindings/Arret.ts +++ /dev/null @@ -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, }; diff --git a/apps/desktop/src/bindings/Capabilities.ts b/apps/desktop/src/bindings/Capabilities.ts new file mode 100644 index 0000000..b47592f --- /dev/null +++ b/apps/desktop/src/bindings/Capabilities.ts @@ -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, }; diff --git a/apps/desktop/src/bindings/Capacites.ts b/apps/desktop/src/bindings/Capacites.ts deleted file mode 100644 index d866596..0000000 --- a/apps/desktop/src/bindings/Capacites.ts +++ /dev/null @@ -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, }; diff --git a/apps/desktop/src/bindings/CloseAction.ts b/apps/desktop/src/bindings/CloseAction.ts new file mode 100644 index 0000000..bc88485 --- /dev/null +++ b/apps/desktop/src/bindings/CloseAction.ts @@ -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"; diff --git a/apps/desktop/src/bindings/Codec.ts b/apps/desktop/src/bindings/Codec.ts index 39e70e2..aebf39e 100644 --- a/apps/desktop/src/bindings/Codec.ts +++ b/apps/desktop/src/bindings/Codec.ts @@ -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"; diff --git a/apps/desktop/src/bindings/Etat.ts b/apps/desktop/src/bindings/Etat.ts deleted file mode 100644 index 3f138b5..0000000 --- a/apps/desktop/src/bindings/Etat.ts +++ /dev/null @@ -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, -/** - * Mécanismes d'inhibition de veille tenus (`login1`, `screensaver`): - * vide hors partage, ou si aucun n'a pu être pris. - */ -veille_inhibee: Array, -/** - * Réglages modifiés pendant le partage, appliqués au prochain. - */ -reglages_en_attente: Array, -/** - * 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, }; diff --git a/apps/desktop/src/bindings/Fermeture.ts b/apps/desktop/src/bindings/Fermeture.ts deleted file mode 100644 index dee7622..0000000 --- a/apps/desktop/src/bindings/Fermeture.ts +++ /dev/null @@ -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"; diff --git a/apps/desktop/src/bindings/HostState.ts b/apps/desktop/src/bindings/HostState.ts new file mode 100644 index 0000000..a972f9b --- /dev/null +++ b/apps/desktop/src/bindings/HostState.ts @@ -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, +/** + * Sleep inhibition mechanisms held (`login1`, `screensaver`): empty + * outside a share, or if none could be taken. + */ +sleep_inhibited: Array, +/** + * Settings changed during the share, applied to the next one. + */ +pending_settings: Array, +/** + * 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, }; diff --git a/apps/desktop/src/bindings/InterfaceProposee.ts b/apps/desktop/src/bindings/InterfaceOption.ts similarity index 55% rename from apps/desktop/src/bindings/InterfaceProposee.ts rename to apps/desktop/src/bindings/InterfaceOption.ts index 73ca900..5e465b0 100644 --- a/apps/desktop/src/bindings/InterfaceProposee.ts +++ b/apps/desktop/src/bindings/InterfaceOption.ts @@ -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, active: boolean, }; +export type InterfaceOption = { name: string, addresses: Array, active: boolean, }; diff --git a/apps/desktop/src/bindings/Label.ts b/apps/desktop/src/bindings/Label.ts new file mode 100644 index 0000000..09277ee --- /dev/null +++ b/apps/desktop/src/bindings/Label.ts @@ -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" }; diff --git a/apps/desktop/src/bindings/Libelle.ts b/apps/desktop/src/bindings/Libelle.ts deleted file mode 100644 index 77ab6a3..0000000 --- a/apps/desktop/src/bindings/Libelle.ts +++ /dev/null @@ -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" }; diff --git a/apps/desktop/src/bindings/NoteSource.ts b/apps/desktop/src/bindings/NoteSource.ts deleted file mode 100644 index 1b30ffb..0000000 --- a/apps/desktop/src/bindings/NoteSource.ts +++ /dev/null @@ -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"; diff --git a/apps/desktop/src/bindings/Partage.ts b/apps/desktop/src/bindings/Partage.ts deleted file mode 100644 index 1817446..0000000 --- a/apps/desktop/src/bindings/Partage.ts +++ /dev/null @@ -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, limite: number, demarre_ms: number, }; diff --git a/apps/desktop/src/bindings/Phase.ts b/apps/desktop/src/bindings/Phase.ts index e43ccbf..26b1a55 100644 --- a/apps/desktop/src/bindings/Phase.ts +++ b/apps/desktop/src/bindings/Phase.ts @@ -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"; diff --git a/apps/desktop/src/bindings/Refus.ts b/apps/desktop/src/bindings/Refus.ts deleted file mode 100644 index 959827a..0000000 --- a/apps/desktop/src/bindings/Refus.ts +++ /dev/null @@ -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, }; diff --git a/apps/desktop/src/bindings/Reglages.ts b/apps/desktop/src/bindings/Reglages.ts deleted file mode 100644 index 28e9050..0000000 --- a/apps/desktop/src/bindings/Reglages.ts +++ /dev/null @@ -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, }; diff --git a/apps/desktop/src/bindings/Rejection.ts b/apps/desktop/src/bindings/Rejection.ts new file mode 100644 index 0000000..5c5051b --- /dev/null +++ b/apps/desktop/src/bindings/Rejection.ts @@ -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, }; diff --git a/apps/desktop/src/bindings/Settings.ts b/apps/desktop/src/bindings/Settings.ts new file mode 100644 index 0000000..d6d248e --- /dev/null +++ b/apps/desktop/src/bindings/Settings.ts @@ -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, }; diff --git a/apps/desktop/src/bindings/SettingsOutcome.ts b/apps/desktop/src/bindings/SettingsOutcome.ts new file mode 100644 index 0000000..7b293f9 --- /dev/null +++ b/apps/desktop/src/bindings/SettingsOutcome.ts @@ -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, +/** + * Fields waiting for the next share, with the reason. + */ +next_share: Array, }; diff --git a/apps/desktop/src/bindings/Share.ts b/apps/desktop/src/bindings/Share.ts new file mode 100644 index 0000000..97b4f53 --- /dev/null +++ b/apps/desktop/src/bindings/Share.ts @@ -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, limit: number, started_ms: number, }; diff --git a/apps/desktop/src/bindings/SharedSource.ts b/apps/desktop/src/bindings/SharedSource.ts new file mode 100644 index 0000000..8c24b12 --- /dev/null +++ b/apps/desktop/src/bindings/SharedSource.ts @@ -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, }; diff --git a/apps/desktop/src/bindings/SourceChoice.ts b/apps/desktop/src/bindings/SourceChoice.ts new file mode 100644 index 0000000..ed229a6 --- /dev/null +++ b/apps/desktop/src/bindings/SourceChoice.ts @@ -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, }; diff --git a/apps/desktop/src/bindings/SourceChoisie.ts b/apps/desktop/src/bindings/SourceChoisie.ts deleted file mode 100644 index ed10208..0000000 --- a/apps/desktop/src/bindings/SourceChoisie.ts +++ /dev/null @@ -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, }; diff --git a/apps/desktop/src/bindings/SourceNote.ts b/apps/desktop/src/bindings/SourceNote.ts new file mode 100644 index 0000000..c8e2d4a --- /dev/null +++ b/apps/desktop/src/bindings/SourceNote.ts @@ -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"; diff --git a/apps/desktop/src/bindings/SourceOption.ts b/apps/desktop/src/bindings/SourceOption.ts new file mode 100644 index 0000000..99cc959 --- /dev/null +++ b/apps/desktop/src/bindings/SourceOption.ts @@ -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, }; diff --git a/apps/desktop/src/bindings/SourcePartagee.ts b/apps/desktop/src/bindings/SourcePartagee.ts deleted file mode 100644 index a5e59c5..0000000 --- a/apps/desktop/src/bindings/SourcePartagee.ts +++ /dev/null @@ -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, }; diff --git a/apps/desktop/src/bindings/SourceProposee.ts b/apps/desktop/src/bindings/SourceProposee.ts deleted file mode 100644 index 199b8f7..0000000 --- a/apps/desktop/src/bindings/SourceProposee.ts +++ /dev/null @@ -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, }; diff --git a/apps/desktop/src/bindings/Stop.ts b/apps/desktop/src/bindings/Stop.ts new file mode 100644 index 0000000..3902d9e --- /dev/null +++ b/apps/desktop/src/bindings/Stop.ts @@ -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, }; diff --git a/apps/desktop/src/bindings/Theme.ts b/apps/desktop/src/bindings/Theme.ts index ddc2cf7..7b75bcf 100644 --- a/apps/desktop/src/bindings/Theme.ts +++ b/apps/desktop/src/bindings/Theme.ts @@ -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"; diff --git a/apps/desktop/src/bindings/TrustedDevice.ts b/apps/desktop/src/bindings/TrustedDevice.ts new file mode 100644 index 0000000..aa35fd7 --- /dev/null +++ b/apps/desktop/src/bindings/TrustedDevice.ts @@ -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, }; diff --git a/apps/desktop/src/bindings/ViewerDevice.ts b/apps/desktop/src/bindings/ViewerDevice.ts new file mode 100644 index 0000000..2a8dce8 --- /dev/null +++ b/apps/desktop/src/bindings/ViewerDevice.ts @@ -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, }; diff --git a/apps/desktop/src/components/ChoixSource.tsx b/apps/desktop/src/components/ChoixSource.tsx deleted file mode 100644 index edf53f2..0000000 --- a/apps/desktop/src/components/ChoixSource.tsx +++ /dev/null @@ -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 ( -
-
-

{t('choisirTitre')}

- {sources && sources.length > SEUIL_RECHERCHE && ( - setRecherche(e.target.value)} - /> - )} - -
- {sources === null &&

{t('chargementSources')}

} - {sources !== null && visibles.length === 0 &&

{t('aucuneSource')}

} -
    - {visibles.map((source) => { - const id = cle(source.choix); - const nom = nomAffiche(source.libelle, t); - const selectionnee = id === choisie; - return ( -
  • - -
  • - ); - })} -
-
- ); -} diff --git a/apps/desktop/src/components/ConfirmQuit.tsx b/apps/desktop/src/components/ConfirmQuit.tsx new file mode 100644 index 0000000..7065b7a --- /dev/null +++ b/apps/desktop/src/components/ConfirmQuit.tsx @@ -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 ( +
+
e.key === 'Escape' && onCancel()} + > +

{t('quitTitle')}

+

{t('quitText', { count: viewers })}

+ +
+ + {/* biome-ignore lint/a11y/noAutofocus: the safe choice gets the focus, Enter stops nothing */} + + +
+
+
+ ); +} diff --git a/apps/desktop/src/components/PanneauPartage.tsx b/apps/desktop/src/components/PanneauPartage.tsx deleted file mode 100644 index 4c9ff63..0000000 --- a/apps/desktop/src/components/PanneauPartage.tsx +++ /dev/null @@ -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 ( -
-
-

{t('scanner')}

- {/* SVG produit par l'hôte (rs-signaling::qr), jamais par une entrée extérieure. */} -
- -
- - {t('code')} {t('codeAide', { accueil })} - - - {codeAffiche(partage.code)} - - {reste && ( - {reste} - )} - -
- {partage.empreinte && ( -

- {t('empreinte')}: {partage.empreinte} -

- )} -
- -
-
-
{t('source')}
-
- {nomAffiche(partage.source.libelle, t)} - - {' '} - {partage.source.largeur} × {partage.source.hauteur} - -
-
{t('ecoute')}
-
- {partage.interface ? `${partage.interface} (${hote})` : t('toutesInterfaces')} - - {' '} - {t('port', { port: partage.ecoute.split(':').pop() ?? '' })} - -
-
{t('depuis')}
-
{duree(partage.demarre_ms, maintenant)}
-
- -

- {t('spectateurs')} - - {t('places', { n: partage.appareils.length, limite: partage.limite })} - -

- {partage.appareils.length === 0 ? ( -

{t('personne')}

- ) : ( -
    - {partage.appareils.map((appareil) => ( -
  • - {appareil.nom} - - {[appareil.plateforme, appareil.adresse].filter(Boolean).join(' · ')} - {' · '} - {duree(appareil.depuis_ms, maintenant)} - - -
  • - ))} -
- )} -
-
- ); -} - -/** 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; -} diff --git a/apps/desktop/src/components/Reglages.tsx b/apps/desktop/src/components/Reglages.tsx deleted file mode 100644 index fea31c0..0000000 --- a/apps/desktop/src/components/Reglages.tsx +++ /dev/null @@ -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(null); - const [interfaces, setInterfaces] = useState([]); - const [refus, setRefus] = useState([]); - // 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 = (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 ( -
-
e.key === 'Escape' && onFermer()} - > -

{t('reglages')}

-
{ - e.preventDefault(); - enregistrer(); - }} - > - - changer('port', Number(e.target.value))} - /> - - - - - - changer('limite', Number(e.target.value))} - /> - - - changer('validite_code_min', Number(e.target.value))} - /> - - - - - - - - - - - - - - - - - {demarrageAuto && ( - - )} - {erreur('fichier') &&

{erreur('fichier')}

} - {message && ( -

- {message.type === 'application' - ? resumeApplication(message.application, t) - : t('diagnosticsEcrits', { chemin: message.chemin })} -

- )} -
- - - - -
-

{t('diagnosticsAide')}

- {erreur('diagnostics') &&

{erreur('diagnostics')}

} -
-
-
- ); -} - -function Champ({ - id, - libelle, - aide, - erreur, - children, -}: { - id: string; - libelle: string; - aide?: string; - erreur?: string | undefined; - children: React.ReactNode; -}) { - return ( -
- - {children} - {erreur ? ( - - {erreur} - - ) : ( - aide && {aide} - )} -
- ); -} diff --git a/apps/desktop/src/components/SettingsDialog.tsx b/apps/desktop/src/components/SettingsDialog.tsx new file mode 100644 index 0000000..c7dca7d --- /dev/null +++ b/apps/desktop/src/components/SettingsDialog.tsx @@ -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(null); + const [interfaces, setInterfaces] = useState([]); + const [rejections, setRejections] = useState([]); + // 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 = (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 ( +
+
e.key === 'Escape' && onClose()} + > +

{t('settings')}

+
{ + e.preventDefault(); + save(); + }} + > + + change('port', Number(e.target.value))} + /> + + + + + + change('limit', Number(e.target.value))} + /> + + + change('code_validity_min', Number(e.target.value))} + /> + + + + + + + + + + + + + + + + + + {autostart && ( + + )} + {error('file') &&

{error('file')}

} + {message && ( +

+ {message.type === 'outcome' + ? outcomeSummary(message.outcome, t) + : t('diagnosticsWritten', { path: message.path })} +

+ )} +
+ + + + +
+

{t('diagnosticsHelp')}

+ {error('diagnostics') &&

{error('diagnostics')}

} +
+
+
+ ); +} + +function Field({ + id, + label, + help, + error, + children, +}: { + id: string; + label: string; + help?: string; + error?: string | undefined; + children: React.ReactNode; +}) { + return ( +
+ + {children} + {error ? ( + + {error} + + ) : ( + help && {help} + )} +
+ ); +} diff --git a/apps/desktop/src/components/SharePanel.tsx b/apps/desktop/src/components/SharePanel.tsx new file mode 100644 index 0000000..cc58e97 --- /dev/null +++ b/apps/desktop/src/components/SharePanel.tsx @@ -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 ( +
+
+

{t('scan')}

+ {/* SVG produced by the host (rs-signaling::qr), never by an outside input. */} +
+ +
+ + {t('code')} {t('codeHelp', { home })} + + + {displayCode(share.code)} + + {remaining && ( + {remaining} + )} + +
+ {share.fingerprint && ( +

+ {t('fingerprint')}: {share.fingerprint} +

+ )} +
+ +
+
+
{t('source')}
+
+ {displayName(share.source.label, t)} + + {' '} + {share.source.width} × {share.source.height} + +
+
{t('listen')}
+
+ {share.interface ? `${share.interface} (${address})` : t('allInterfaces')} + + {' '} + {t('port', { port: share.listen.split(':').pop() ?? '' })} + +
+
{t('since')}
+
{duration(share.started_ms, now)}
+
+ +

+ {t('viewers')} + + {t('seats', { n: share.devices.length, limit: share.limit })} + +

+ {share.devices.length === 0 ? ( +

{t('nobody')}

+ ) : ( +
    + {share.devices.map((device) => ( +
  • + {device.name} + + {[device.platform, device.address].filter(Boolean).join(' · ')} + {' · '} + {duration(device.since_ms, now)} + + +
  • + ))} +
+ )} +
+
+ ); +} + +/** 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; +} diff --git a/apps/desktop/src/components/SourcePicker.tsx b/apps/desktop/src/components/SourcePicker.tsx new file mode 100644 index 0000000..1f77422 --- /dev/null +++ b/apps/desktop/src/components/SourcePicker.tsx @@ -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 ( +
+
+

{t('pickTitle')}

+ {sources && sources.length > SEARCH_THRESHOLD && ( + setSearch(e.target.value)} + /> + )} + +
+ {sources === null &&

{t('loadingSources')}

} + {sources !== null && visible.length === 0 &&

{t('noSource')}

} +
    + {visible.map((source) => { + const id = key(source.choice); + const name = displayName(source.label, t); + const selected = id === picked; + return ( +
  • + +
  • + ); + })} +
+
+ ); +} diff --git a/apps/desktop/src/i18n.tsx b/apps/desktop/src/i18n.tsx index c70c5ac..f6ef7bb 100644 --- a/apps/desktop/src/i18n.tsx +++ b/apps/desktop/src/i18n.tsx @@ -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('../../../locales/*.json', { eager: true, import: 'default' }), +const FILES = Object.values( + import.meta.glob('../../../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(null); +const I18n = createContext(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 {children}; +/** 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 {children}; } diff --git a/apps/desktop/src/lib/host.ts b/apps/desktop/src/lib/host.ts new file mode 100644 index 0000000..1aa64c0 --- /dev/null +++ b/apps/desktop/src/lib/host.ts @@ -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; + /** Returns the function that stops listening. */ + listen(callback: (state: HostState) => void): Promise<() => void>; + sources(): Promise; + start(choice: SourceChoice): Promise; + stop(): Promise; + disconnect(connection: number): Promise; + /** New QR code and new short code (#19). */ + regenerateAccess(): Promise; + settings(): Promise; + /** Rejects with the list of refused values. */ + updateSettings(settings: Settings): Promise; + interfaces(): Promise; + /** Returns the path of the written archive. */ + exportDiagnostics(): Promise; + /** The texts of the system tray menu, in the language of the interface. */ + translateTray(texts: TrayTexts): Promise; + /** The host asks for confirmation before quitting (#43). */ + listenQuit(callback: () => void): Promise<() => void>; + quit(dontAskAgain: boolean): Promise; +}; + +export const tauriHost: Host = { + state: () => invoke('state'), + listen: (callback) => listen('state', (event) => callback(event.payload)), + sources: () => invoke('sources'), + start: (choice) => invoke('start', { choice }), + stop: () => invoke('stop'), + disconnect: (connection) => invoke('disconnect', { connection }), + regenerateAccess: () => invoke('regenerate_access'), + settings: () => invoke('settings'), + updateSettings: (settings) => invoke('update_settings', { settings }), + interfaces: () => invoke('interfaces'), + exportDiagnostics: () => invoke('export_diagnostics'), + translateTray: (texts) => invoke('translate_tray', { texts }), + listenQuit: (callback) => listen('confirm-quit', () => callback()), + quit: (dontAskAgain) => invoke('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) }]; +} diff --git a/apps/desktop/src/lib/hote.ts b/apps/desktop/src/lib/hote.ts deleted file mode 100644 index 68f5722..0000000 --- a/apps/desktop/src/lib/hote.ts +++ /dev/null @@ -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; - /** Rend la fonction qui arrête l'écoute. */ - ecouter(rappel: (etat: Etat) => void): Promise<() => void>; - sources(): Promise; - demarrer(choix: SourceChoisie): Promise; - arreter(): Promise; - deconnecter(connexion: number): Promise; - /** Nouveau QR code et nouveau code court (#19). */ - regenererAcces(): Promise; - reglages(): Promise; - /** Rejette avec la liste des valeurs refusées. */ - modifierReglages(reglages: Reglages): Promise; - interfaces(): Promise; - /** Rend le chemin de l'archive écrite. */ - exporterDiagnostics(): Promise; - /** Les textes du menu de la barre système, dans la langue de l'interface. */ - traduireBarre(textes: TextesBarre): Promise; -}; - -export const hoteTauri: Hote = { - etat: () => invoke('etat'), - ecouter: (rappel) => listen('etat', (evenement) => rappel(evenement.payload)), - sources: () => invoke('sources'), - demarrer: (choix) => invoke('demarrer', { choix }), - arreter: () => invoke('arreter'), - deconnecter: (connexion) => invoke('deconnecter', { connexion }), - regenererAcces: () => invoke('regenerer_acces'), - reglages: () => invoke('reglages'), - modifierReglages: (reglages) => invoke('modifier_reglages', { reglages }), - interfaces: () => invoke('interfaces'), - exporterDiagnostics: () => invoke('exporter_diagnostics'), - traduireBarre: (textes) => invoke('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) }]; -} diff --git a/apps/desktop/src/lib/view.test.ts b/apps/desktop/src/lib/view.test.ts new file mode 100644 index 0000000..23a7903 --- /dev/null +++ b/apps/desktop/src/lib/view.test.ts @@ -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'); + }); +}); diff --git a/apps/desktop/src/lib/view.ts b/apps/desktop/src/lib/view.ts new file mode 100644 index 0000000..6277f1e --- /dev/null +++ b/apps/desktop/src/lib/view.ts @@ -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'), + }; +} diff --git a/apps/desktop/src/lib/vue.test.ts b/apps/desktop/src/lib/vue.test.ts deleted file mode 100644 index b60da77..0000000 --- a/apps/desktop/src/lib/vue.test.ts +++ /dev/null @@ -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'); - }); -}); diff --git a/apps/desktop/src/lib/vue.ts b/apps/desktop/src/lib/vue.ts deleted file mode 100644 index a7f200a..0000000 --- a/apps/desktop/src/lib/vue.ts +++ /dev/null @@ -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'), - }; -} diff --git a/apps/desktop/src/main.tsx b/apps/desktop/src/main.tsx index 33861f4..5bc427c 100644 --- a/apps/desktop/src/main.tsx +++ b/apps/desktop/src/main.tsx @@ -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( - + , ); diff --git a/apps/desktop/src/styles.css b/apps/desktop/src/styles.css index 6811220..94ba36f 100644 --- a/apps/desktop/src/styles.css +++ b/apps/desktop/src/styles.css @@ -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; } diff --git a/apps/desktop/vite.config.ts b/apps/desktop/vite.config.ts index e89bf18..afbe8ed 100644 --- a/apps/desktop/vite.config.ts +++ b/apps/desktop/vite.config.ts @@ -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, diff --git a/apps/viewer/package.json b/apps/viewer/package.json index 487c5d3..40346e7 100644 --- a/apps/viewer/package.json +++ b/apps/viewer/package.json @@ -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" }, diff --git a/apps/viewer/src/App.tsx b/apps/viewer/src/App.tsx index 87bca26..f9b2123 100644 --- a/apps/viewer/src/App.tsx +++ b/apps/viewer/src/App.tsx @@ -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(null); const [attemptKey, setAttemptKey] = useState(0); const [isFullscreen, setIsFullscreen] = useState(false); - const [theme, setTheme] = useState(() => lireTheme()); - const [rotation, setRotation] = useState(() => lireRotation()); + const [theme, setTheme] = useState(() => readTheme()); + const [rotation, setRotation] = useState(() => 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(null); const containerRef = useRef(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 ( -
-
+
+
{t('appName')} {location.value.fingerprint && ( @@ -146,23 +192,47 @@ export function App() { {live && ( )} + {live && ( + + )} + {live && !isFullscreen && ( + + )} {live && (
-
+
- +
); diff --git a/apps/viewer/src/components/ChoixLangue.tsx b/apps/viewer/src/components/ChoixLangue.tsx deleted file mode 100644 index b03d226..0000000 --- a/apps/viewer/src/components/ChoixLangue.tsx +++ /dev/null @@ -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 ( - - - - - ); -} diff --git a/apps/viewer/src/components/ErrorPanel.tsx b/apps/viewer/src/components/ErrorPanel.tsx index b6a38b1..75aee54 100644 --- a/apps/viewer/src/components/ErrorPanel.tsx +++ b/apps/viewer/src/components/ErrorPanel.tsx @@ -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(); diff --git a/apps/viewer/src/components/LanguagePicker.tsx b/apps/viewer/src/components/LanguagePicker.tsx new file mode 100644 index 0000000..5d6a6b8 --- /dev/null +++ b/apps/viewer/src/components/LanguagePicker.tsx @@ -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 ( + + + + + ); +} diff --git a/apps/viewer/src/components/Pairing.tsx b/apps/viewer/src/components/Pairing.tsx index e8ae681..cdc1120 100644 --- a/apps/viewer/src/components/Pairing.tsx +++ b/apps/viewer/src/components/Pairing.tsx @@ -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) { )} {scanning && setScanning(false)} onError={setError} />} - + ); } -/** 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(null); diff --git a/apps/viewer/src/components/StatsBar.tsx b/apps/viewer/src/components/StatsBar.tsx index bff406b..4b79abe 100644 --- a/apps/viewer/src/components/StatsBar.tsx +++ b/apps/viewer/src/components/StatsBar.tsx @@ -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(null); @@ -57,7 +57,7 @@ export function StatsBar({ stats }: Props) {
{kbps >= 1000 ? t('mbps', { - value: (kbps / 1000).toLocaleString(langue, { maximumFractionDigits: 1 }), + value: (kbps / 1000).toLocaleString(language, { maximumFractionDigits: 1 }), }) : t('kbps', { value: kbps })}
diff --git a/apps/viewer/src/components/StatusBadge.tsx b/apps/viewer/src/components/StatusBadge.tsx index 2b967a7..525b586 100644 --- a/apps/viewer/src/components/StatusBadge.tsx +++ b/apps/viewer/src/components/StatusBadge.tsx @@ -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' }; diff --git a/apps/viewer/src/components/VideoStage.tsx b/apps/viewer/src/components/VideoStage.tsx index 694f0ef..e70e7cf 100644 --- a/apps/viewer/src/components/VideoStage.tsx +++ b/apps/viewer/src/components/VideoStage.tsx @@ -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(null); const stageRef = useRef(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 (
diff --git a/apps/viewer/src/i18n.tsx b/apps/viewer/src/i18n.tsx index 04f2855..008753f 100644 --- a/apps/viewer/src/i18n.tsx +++ b/apps/viewer/src/i18n.tsx @@ -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(null); +const I18n = createContext(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 {children}; + return {children}; } -/** Les langues que sert l'hôte, vide s'il ne répond pas. */ -export async function chargerLangues(): Promise { +/** The languages the host serves, empty if it does not answer. */ +export async function loadLanguages(): Promise { 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 { - 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 { + 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. } } diff --git a/apps/viewer/src/lib/controls.test.ts b/apps/viewer/src/lib/controls.test.ts new file mode 100644 index 0000000..969e326 --- /dev/null +++ b/apps/viewer/src/lib/controls.test.ts @@ -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 = {}) { + 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); + }); +}); diff --git a/apps/viewer/src/lib/controls.ts b/apps/viewer/src/lib/controls.ts new file mode 100644 index 0000000..ffa5215 --- /dev/null +++ b/apps/viewer/src/lib/controls.ts @@ -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. + } +} diff --git a/apps/viewer/src/lib/device.test.ts b/apps/viewer/src/lib/device.test.ts index dd68751..cfafca3 100644 --- a/apps/viewer/src/lib/device.test.ts +++ b/apps/viewer/src/lib/device.test.ts @@ -1,40 +1,78 @@ import { describe, expect, it, vi } from 'vitest'; import { deviceId } from './device'; +import type { KeyValueStore } from './storage'; -function memoire(): Pick { - const valeurs = new Map(); +function memory( + initial: Record = {}, +): KeyValueStore & { values: Map } { + 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); }); }); diff --git a/apps/viewer/src/lib/device.ts b/apps/viewer/src/lib/device.ts index 2e6152f..c686e15 100644 --- a/apps/viewer/src/lib/device.ts +++ b/apps/viewer/src/lib/device.ts @@ -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 | 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(''); } diff --git a/apps/viewer/src/lib/i18n.test.ts b/apps/viewer/src/lib/i18n.test.ts index df7797e..a94de39 100644 --- a/apps/viewer/src/lib/i18n.test.ts +++ b/apps/viewer/src/lib/i18n.test.ts @@ -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'); }); }); diff --git a/apps/viewer/src/lib/i18n.ts b/apps/viewer/src/lib/i18n.ts index 6c201e7..6c2243a 100644 --- a/apps/viewer/src/lib/i18n.ts +++ b/apps/viewer/src/lib/i18n.ts @@ -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/.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/.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; -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; +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); } diff --git a/apps/viewer/src/lib/lifecycle.ts b/apps/viewer/src/lib/lifecycle.ts index d347b04..0f00ff3 100644 --- a/apps/viewer/src/lib/lifecycle.ts +++ b/apps/viewer/src/lib/lifecycle.ts @@ -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> = []; diff --git a/apps/viewer/src/lib/pairing.test.ts b/apps/viewer/src/lib/pairing.test.ts index 76b0c67..1876edb 100644 --- a/apps/viewer/src/lib/pairing.test.ts +++ b/apps/viewer/src/lib/pairing.test.ts @@ -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(); }); }); diff --git a/apps/viewer/src/lib/pairing.ts b/apps/viewer/src/lib/pairing.ts index f59c238..63755a9 100644 --- a/apps/viewer/src/lib/pairing.ts +++ b/apps/viewer/src/lib/pairing.ts @@ -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>; }; 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 { diff --git a/apps/viewer/src/lib/reconnect.test.ts b/apps/viewer/src/lib/reconnect.test.ts index f27bb69..31d3c0f 100644 --- a/apps/viewer/src/lib/reconnect.test.ts +++ b/apps/viewer/src/lib/reconnect.test.ts @@ -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', diff --git a/apps/viewer/src/lib/resume.test.ts b/apps/viewer/src/lib/resume.test.ts index 3e5c2ea..1894042 100644 --- a/apps/viewer/src/lib/resume.test.ts +++ b/apps/viewer/src/lib/resume.test.ts @@ -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 { 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 { 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(); diff --git a/apps/viewer/src/lib/room.test.ts b/apps/viewer/src/lib/room.test.ts index 9224e3e..4733567 100644 --- a/apps/viewer/src/lib/room.test.ts +++ b/apps/viewer/src/lib/room.test.ts @@ -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'); }); }); diff --git a/apps/viewer/src/lib/room.ts b/apps/viewer/src/lib/room.ts index 6912e23..8597f8b 100644 --- a/apps/viewer/src/lib/room.ts +++ b/apps/viewer/src/lib/room.ts @@ -1,10 +1,10 @@ /** - * Lecture de la session dans l'URL. + * Reading the session from the URL. * - * Forme attendue: `/r/?t=&v=`, suivie en HTTPS de - * `#fp=` (#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/?t=&v=`, followed over HTTPS by + * `#fp=` (#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/` et `/`. Le préfixe `r` évite de - // confondre une room avec un chemin d'asset servi par le même serveur. + // Two accepted forms: `/r/` and `/`. 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`; diff --git a/apps/viewer/src/lib/rotation.test.ts b/apps/viewer/src/lib/rotation.test.ts index 7099157..a178f57 100644 --- a/apps/viewer/src/lib/rotation.test.ts +++ b/apps/viewer/src/lib/rotation.test.ts @@ -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 = {}) { + 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); }); }); diff --git a/apps/viewer/src/lib/rotation.ts b/apps/viewer/src/lib/rotation.ts index d4d5a70..ecf4be7 100644 --- a/apps/viewer/src/lib/rotation.ts +++ b/apps/viewer/src/lib/rotation.ts @@ -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 | 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. } } diff --git a/apps/viewer/src/lib/session.test.ts b/apps/viewer/src/lib/session.test.ts index 9f65b05..563339d 100644 --- a/apps/viewer/src/lib/session.test.ts +++ b/apps/viewer/src/lib/session.test.ts @@ -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.'); }); }); diff --git a/apps/viewer/src/lib/session.ts b/apps/viewer/src/lib/session.ts index f889db4..90c7093 100644 --- a/apps/viewer/src/lib/session.ts +++ b/apps/viewer/src/lib/session.ts @@ -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 = new Set([ 'bad_token', 'token_expired', @@ -61,8 +61,8 @@ const TERMINAL_CODES: ReadonlySet = 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 = 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 | 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 { 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'; diff --git a/apps/viewer/src/lib/storage.ts b/apps/viewer/src/lib/storage.ts new file mode 100644 index 0000000..f79f71f --- /dev/null +++ b/apps/viewer/src/lib/storage.ts @@ -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; + +/** `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; +} diff --git a/apps/viewer/src/lib/theme.test.ts b/apps/viewer/src/lib/theme.test.ts index 160ab21..e18ac23 100644 --- a/apps/viewer/src/lib/theme.test.ts +++ b/apps/viewer/src/lib/theme.test.ts @@ -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 { - const valeurs = new Map(); +function memory(): KeyValueStore { + const values = new Map(); 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); + } }); }); diff --git a/apps/viewer/src/lib/theme.ts b/apps/viewer/src/lib/theme.ts index d786dff..2e1e000 100644 --- a/apps/viewer/src/lib/theme.ts +++ b/apps/viewer/src/lib/theme.ts @@ -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> = { + systeme: 'system', + clair: 'light', + sombre: 'dark', +}; -type Stockage = Pick | 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; } diff --git a/apps/viewer/src/lib/useActivity.ts b/apps/viewer/src/lib/useActivity.ts new file mode 100644 index 0000000..99dda4f --- /dev/null +++ b/apps/viewer/src/lib/useActivity.ts @@ -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 | 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; +} diff --git a/apps/viewer/src/main.tsx b/apps/viewer/src/main.tsx index 54ef658..7a0383c 100644 --- a/apps/viewer/src/main.tsx +++ b/apps/viewer/src/main.tsx @@ -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( - + , ); } -void demarrer(root); +void start(root); diff --git a/apps/viewer/src/proto/ClientMessage.ts b/apps/viewer/src/proto/ClientMessage.ts index 8b1e9ef..55c9ad5 100644 --- a/apps/viewer/src/proto/ClientMessage.ts +++ b/apps/viewer/src/proto/ClientMessage.ts @@ -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" }; diff --git a/apps/viewer/src/proto/DeviceInfo.ts b/apps/viewer/src/proto/DeviceInfo.ts index 2a3d3b9..55f21c0 100644 --- a/apps/viewer/src/proto/DeviceInfo.ts +++ b/apps/viewer/src/proto/DeviceInfo.ts @@ -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, }; diff --git a/apps/viewer/src/proto/PairingRequest.ts b/apps/viewer/src/proto/PairingRequest.ts index e61cc02..4edb589 100644 --- a/apps/viewer/src/proto/PairingRequest.ts +++ b/apps/viewer/src/proto/PairingRequest.ts @@ -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, }; diff --git a/apps/viewer/src/proto/PairingResponse.ts b/apps/viewer/src/proto/PairingResponse.ts index 80c5c44..ada9591 100644 --- a/apps/viewer/src/proto/PairingResponse.ts +++ b/apps/viewer/src/proto/PairingResponse.ts @@ -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, }; diff --git a/apps/viewer/src/proto/QualityPreset.ts b/apps/viewer/src/proto/QualityPreset.ts index c301efa..cdc09a4 100644 --- a/apps/viewer/src/proto/QualityPreset.ts +++ b/apps/viewer/src/proto/QualityPreset.ts @@ -1,6 +1,6 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. /** - * Profil de qualité, repris du vocabulaire de Deskreen. + * Quality preset, borrowed from Deskreen's vocabulary. */ export type QualityPreset = "saver" | "balanced" | "sharp"; diff --git a/apps/viewer/src/proto/RoomId.ts b/apps/viewer/src/proto/RoomId.ts index e95c0fb..ebd9f09 100644 --- a/apps/viewer/src/proto/RoomId.ts +++ b/apps/viewer/src/proto/RoomId.ts @@ -1,7 +1,7 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. /** - * Identifiant de room, choisi pour être dictable: six caractères, sans - * caractères ambigus (pas de `0`, `o`, `1`, `l`, `i`). + * Room identifier, chosen to be easy to dictate: six characters, without + * ambiguous characters (no `0`, `o`, `1`, `l`, `i`). */ export type RoomId = string; diff --git a/apps/viewer/src/proto/ServerMessage.ts b/apps/viewer/src/proto/ServerMessage.ts index f358515..160cac1 100644 --- a/apps/viewer/src/proto/ServerMessage.ts +++ b/apps/viewer/src/proto/ServerMessage.ts @@ -5,10 +5,10 @@ import type { SourceInfo } from "./SourceInfo"; import type { StreamSettings } from "./StreamSettings"; /** - * Ce que l'hôte envoie au spectateur. + * What the host sends to the viewer. */ export type ServerMessage = { "type": "welcome", version: number, room: RoomId, source: SourceInfo | null, settings: StreamSettings, /** - * Nombre de spectateurs déjà connectés, limite incluse. + * Number of viewers already connected, and the limit. */ connected: number, limit: number, } | { "type": "answer", sdp: string, } | { "type": "ice_candidate", candidate: string, sdp_mid: string | null, sdp_mline_index: number | null, } | { "type": "source_changed", source: SourceInfo, } | { "type": "settings_applied", settings: StreamSettings, } | { "type": "error", code: ErrorCode, message: string, } | { "type": "bye", reason: string, }; diff --git a/apps/viewer/src/proto/SessionToken.ts b/apps/viewer/src/proto/SessionToken.ts index 77c6e6d..e84b890 100644 --- a/apps/viewer/src/proto/SessionToken.ts +++ b/apps/viewer/src/proto/SessionToken.ts @@ -1,6 +1,6 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. /** - * Jeton d'accès à une session. Opaque pour le client, 128 bits d'entropie. + * Access token to a session. Opaque to the client, 128 bits of entropy. */ export type SessionToken = string; diff --git a/apps/viewer/src/proto/SourceInfo.ts b/apps/viewer/src/proto/SourceInfo.ts index 11faa7c..d6d8005 100644 --- a/apps/viewer/src/proto/SourceInfo.ts +++ b/apps/viewer/src/proto/SourceInfo.ts @@ -4,6 +4,6 @@ import type { SourceKind } from "./SourceKind"; export type SourceInfo = { id: SourceId, kind: SourceKind, name: string, width: number, height: number, /** - * Vrai si la plateforme sait capturer cette source en continu. + * True if the platform can capture this source continuously. */ available: boolean, }; diff --git a/apps/viewer/src/proto/SourceKind.ts b/apps/viewer/src/proto/SourceKind.ts index 21b9bcb..e6ca55e 100644 --- a/apps/viewer/src/proto/SourceKind.ts +++ b/apps/viewer/src/proto/SourceKind.ts @@ -1,7 +1,7 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. /** - * Ce que l'hôte partage. La distinction n'est pas cosmétique: sous Wayland le - * portail ne sait pas toujours rendre une fenêtre précise. + * What the host shares. The distinction is not cosmetic: under Wayland the + * portal cannot always deliver one specific window. */ export type SourceKind = "screen" | "window"; diff --git a/apps/viewer/src/proto/index.ts b/apps/viewer/src/proto/index.ts index 14888b9..e212f58 100644 --- a/apps/viewer/src/proto/index.ts +++ b/apps/viewer/src/proto/index.ts @@ -1,5 +1,5 @@ -// Types générés depuis crates/rs-proto par `cargo test -p rs-proto export_bindings`. -// Ne pas modifier à la main: régénérer, puis committer le résultat. +// Types generated from crates/rs-proto by `cargo test -p rs-proto export_bindings`. +// Do not edit by hand: regenerate, then commit the result. export type { ClientMessage } from './ClientMessage'; export type { ErrorCode } from './ErrorCode'; @@ -16,8 +16,8 @@ export type { SourceInfo } from './SourceInfo'; export type { SourceKind } from './SourceKind'; export type { StreamSettings } from './StreamSettings'; -/** Version du protocole, à garder alignée avec crates/rs-proto/src/lib.rs. */ +/** Protocol version, kept in step with crates/rs-proto/src/lib.rs. */ export const PROTOCOL_VERSION = 1; -/** Version du format du lien du QR code, alignée sur `LINK_VERSION` (rs-proto). */ +/** Version of the QR code link format, in step with `LINK_VERSION` (rs-proto). */ export const LINK_VERSION = 1; diff --git a/apps/viewer/src/styles.css b/apps/viewer/src/styles.css index 64fed8f..0e30f9d 100644 --- a/apps/viewer/src/styles.css +++ b/apps/viewer/src/styles.css @@ -1,6 +1,6 @@ -/* Deux paliers de couleurs (#28): clair par défaut, sombre sur demande ou - selon le système. Chaque paire texte et fond passe le contraste AA (4,5:1). - La scène vidéo reste noire dans les deux: c'est un écran, pas une page. */ +/* Two colour schemes (#28): light by default, dark on request or following + the system. Every text and background pair passes AA contrast (4.5:1). + The video stage stays black in both: it is a screen, not a page. */ :root { color-scheme: light; --bg: #f5f6f8; @@ -19,7 +19,7 @@ font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; } -:root[data-theme="sombre"] { +:root[data-theme="dark"] { color-scheme: dark; --bg: #0d1116; --surface: #151b23; @@ -36,7 +36,7 @@ } @media (prefers-color-scheme: dark) { - :root:not([data-theme="clair"]) { + :root:not([data-theme="light"]) { color-scheme: dark; --bg: #0d1116; --surface: #151b23; @@ -71,6 +71,7 @@ body { } .app { + position: relative; display: flex; min-height: 100%; flex-direction: column; @@ -118,8 +119,8 @@ body { background: #000; } -/* Hors du flux: sans cela, la taille naturelle du flux (1280x720) fixe celle - de la scène, et la page déborde de l'écran en poussant le pied de page. */ +/* Out of the flow: otherwise the natural size of the stream (1280x720) sets + the stage size, and the page overflows the screen, pushing the footer. */ .stage-video { position: absolute; inset: 0; @@ -255,13 +256,13 @@ body { background: var(--surface); } -/* Choix de la langue (#21): discret, au bout du pied de page. */ -.langue { +/* Language picker (#21): discreet, at the end of the footer. */ +.language { margin-left: auto; padding: 0 1rem; } -.langue select { +.language select { padding: 0.25rem 0.4rem; border: 1px solid var(--border); border-radius: 6px; @@ -271,7 +272,7 @@ body { font-size: 0.82rem; } -.pairing .langue { +.pairing .language { display: block; margin-top: 1rem; padding: 0; @@ -322,7 +323,7 @@ body { } } -/* Accueil sans session: code court et scan (#19). */ +/* Home without a session: short code and scan (#19). */ .pairing { width: min(26rem, 100%); } @@ -384,3 +385,43 @@ body { border-radius: var(--radius); background: #000; } + +/* Compact mode (#31, #81): the bars sit over the picture instead of pushing + it, so that their return does not resize the video. */ +.app-compact { + height: 100%; +} + +.app-compact .topbar, +.app-compact .footer { + position: absolute; + right: 0; + left: 0; + z-index: 2; + transition: opacity 0.2s ease; +} + +.app-compact .topbar { + top: 0; +} + +.app-compact .footer { + bottom: 0; +} + +.app-hidden { + cursor: none; +} + +.app-hidden .topbar, +.app-hidden .footer { + opacity: 0; + pointer-events: none; +} + +@media (prefers-reduced-motion: reduce) { + .app-compact .topbar, + .app-compact .footer { + transition: none; + } +} diff --git a/apps/viewer/vite.config.ts b/apps/viewer/vite.config.ts index 98d7916..08e4117 100644 --- a/apps/viewer/vite.config.ts +++ b/apps/viewer/vite.config.ts @@ -4,35 +4,37 @@ import react from '@vitejs/plugin-react'; import { defineConfig, type Plugin } from 'vite'; /** - * En développement (`npm run dev`), personne ne sert `/locales/`: ce greffon - * le fait depuis `locales/` à la racine du dépôt, comme l'hôte en production. + * In development (`npm run dev`), nobody serves `/locales/`: this plugin does + * it from `locales/` at the repository root, like the host in production. */ -function traductions(): Plugin { - const dossier = join(__dirname, '../../locales'); +function locales(): Plugin { + const dir = join(__dirname, '../../locales'); return { name: 'rustscreen-locales', configureServer(server) { - server.middlewares.use('/locales', (requete, reponse, suite) => { - const nom = (requete.url ?? '').replace(/^\//, ''); - const fichiers = readdirSync(dossier).filter((f) => f.endsWith('.json')); - let corps: string | undefined; - if (nom === 'index.json') { - corps = JSON.stringify( - fichiers.map((f) => JSON.parse(readFileSync(join(dossier, f), 'utf8'))._langue), + server.middlewares.use('/locales', (request, response, next) => { + const name = (request.url ?? '').replace(/^\//, ''); + const files = readdirSync(dir).filter((f) => f.endsWith('.json')); + let body: string | undefined; + if (name === 'index.json') { + // `_language` is the language header of each locale file, as the + // host reads it. + body = JSON.stringify( + files.map((f) => JSON.parse(readFileSync(join(dir, f), 'utf8'))._language), ); - } else if (fichiers.includes(nom)) { - corps = readFileSync(join(dossier, nom), 'utf8'); + } else if (files.includes(name)) { + body = readFileSync(join(dir, name), 'utf8'); } - if (corps === undefined) return suite(); - reponse.setHeader('Content-Type', 'application/json; charset=utf-8'); - reponse.end(corps); + if (body === undefined) return next(); + response.setHeader('Content-Type', 'application/json; charset=utf-8'); + response.end(body); }); }, }; } export default defineConfig({ - plugins: [react(), traductions()], + plugins: [react(), locales()], build: { target: 'es2022', sourcemap: true, diff --git a/assets/rustscreen.desktop b/assets/rustscreen.desktop index c28c58e..2f2123c 100644 --- a/assets/rustscreen.desktop +++ b/assets/rustscreen.desktop @@ -1,8 +1,10 @@ [Desktop Entry] Type=Application Name=rustscreen -GenericName=Partage d'écran -Comment=Partager son écran sur le réseau local, à regarder depuis un navigateur +GenericName=Screen sharing +GenericName[fr]=Partage d'écran +Comment=Share your screen over the local network, watched from a browser +Comment[fr]=Partager son écran sur le réseau local, à regarder depuis un navigateur Exec=rustscreen Icon=rustscreen Terminal=true diff --git a/crates/rs-capture/Cargo.toml b/crates/rs-capture/Cargo.toml index b772426..fca8b1f 100644 --- a/crates/rs-capture/Cargo.toml +++ b/crates/rs-capture/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rs-capture" -description = "Capture écran et fenêtres, une implémentation par système." +description = "Screen and window capture, one implementation per system." version.workspace = true edition.workspace = true rust-version.workspace = true @@ -8,9 +8,9 @@ license.workspace = true repository.workspace = true [features] -# Capture Wayland par PipeWire. Optionnelle parce qu'elle exige -# `libpipewire-0.3` et libclang au build: la CI n'a ni l'une ni l'autre, le -# paquet Nix et l'AppImage l'activent (ADR 0009). +# Wayland capture through PipeWire. Optional because it needs +# `libpipewire-0.3` and libclang at build time: CI has neither, the Nix +# package and the AppImage enable it (ADR 0009). pipewire = ["dep:pipewire"] [dependencies] @@ -20,7 +20,7 @@ tracing.workspace = true [target.'cfg(target_os = "linux")'.dependencies] pipewire = { version = "0.10.1", optional = true, features = ["v0_3_44"] } -# Pur Rust, sans libX11: le repli X11 ne coûte aucune dépendance système. +# Pure Rust, no libX11: the X11 fallback costs no system dependency. x11rb = { version = "0.14.0", features = ["shm", "composite", "randr"] } rustix = { version = "1", features = ["fs", "mm", "shm"] } diff --git a/crates/rs-capture/src/backend.rs b/crates/rs-capture/src/backend.rs index 23c0adb..96337df 100644 --- a/crates/rs-capture/src/backend.rs +++ b/crates/rs-capture/src/backend.rs @@ -1,68 +1,74 @@ -//! Quel chemin de capture prendre, et pourquoi. +//! Which capture path to take, and why. //! -//! Il n'existe pas de chemin portable (AGENTS.md): Wayland interdit la lecture -//! directe de l'écran et impose le portail, X11 permet XShm. La décision dépend -//! de la session graphique, avec un forçage par `RUSTSCREEN_CAPTURE` pour le -//! débogage et les cas que la détection rate (Xwayland, session imbriquée). +//! There is no portable path (AGENTS.md): Wayland forbids reading the screen +//! directly and imposes the portal, X11 allows XShm. The decision depends on +//! the graphical session, with an override through `RUSTSCREEN_CAPTURE` for +//! debugging and for cases detection gets wrong (Xwayland, nested session). -/// Session graphique, vue par la capture. +/// Graphical session, as seen by capture. #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Graphique { +pub enum DisplaySession { Wayland, X11, - Aucune, + Headless, } -/// Chemin de capture retenu. +/// Chosen capture path. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Backend { - /// Portail `xdg-desktop-portal` puis flux PipeWire. - Portail, - /// X11 direct, MIT-SHM quand le serveur l'offre. + /// `xdg-desktop-portal` portal, then a PipeWire stream. + Portal, + /// Direct X11, MIT-SHM when the server offers it. X11, - /// Mire générée, sans écran. - Synthetique, + /// Generated test pattern, no screen. + Synthetic, } impl Backend { pub fn as_str(self) -> &'static str { match self { - Self::Portail => "portail", + Self::Portal => "portal", Self::X11 => "x11", - Self::Synthetique => "synthetique", + Self::Synthetic => "synthetic", } } } #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] -pub enum ChoixError { - #[error("RUSTSCREEN_CAPTURE={0} inconnu: attendu portail, x11 ou synthetique")] - Inconnu(String), - #[error("pas de session graphique: rien à capturer (utiliser --synthetic pour une mire)")] - PasDeSession, +pub enum BackendChoiceError { + #[error("unknown RUSTSCREEN_CAPTURE={0}: expected portal, x11 or synthetic")] + Unknown(String), + #[error("no graphical session: nothing to capture (use --synthetic for a test pattern)")] + NoSession, } -/// Variable d'environnement qui force le chemin. -pub const FORCAGE: &str = "RUSTSCREEN_CAPTURE"; +/// Environment variable that forces the path. +pub const OVERRIDE_VAR: &str = "RUSTSCREEN_CAPTURE"; -/// Choisit le chemin. Le forçage gagne toujours, même s'il contredit la -/// session: c'est précisément quand la détection se trompe qu'on en a besoin. -pub fn choisir(session: Graphique, forcage: Option<&str>) -> Result { - if let Some(valeur) = forcage.map(str::trim).filter(|v| !v.is_empty()) { - return match valeur.to_ascii_lowercase().as_str() { - "portail" | "portal" | "pipewire" | "wayland" => Ok(Backend::Portail), +/// Chooses the path. The override always wins, even if it contradicts the +/// session: it is precisely when detection is wrong that we need it. +/// +/// The French spellings (`portail`, `synthetique`) are still accepted, for +/// existing scripts and documentation. +pub fn choose( + session: DisplaySession, + override_value: Option<&str>, +) -> Result { + if let Some(value) = override_value.map(str::trim).filter(|v| !v.is_empty()) { + return match value.to_ascii_lowercase().as_str() { + "portail" | "portal" | "pipewire" | "wayland" => Ok(Backend::Portal), "x11" | "xshm" => Ok(Backend::X11), - "synthetique" | "synthétique" | "synthetic" => Ok(Backend::Synthetique), - _ => Err(ChoixError::Inconnu(valeur.to_string())), + "synthetique" | "synthétique" | "synthetic" => Ok(Backend::Synthetic), + _ => Err(BackendChoiceError::Unknown(value.to_string())), }; } match session { - // Sous Wayland, X11 existe souvent (Xwayland) mais ne voit que les - // fenêtres X: l'écran capturé serait noir. Le portail est le seul - // chemin honnête. - Graphique::Wayland => Ok(Backend::Portail), - Graphique::X11 => Ok(Backend::X11), - Graphique::Aucune => Err(ChoixError::PasDeSession), + // Under Wayland, X11 often exists (Xwayland) but only sees X windows: + // the captured screen would be black. The portal is the only honest + // path. + DisplaySession::Wayland => Ok(Backend::Portal), + DisplaySession::X11 => Ok(Backend::X11), + DisplaySession::Headless => Err(BackendChoiceError::NoSession), } } @@ -72,35 +78,42 @@ mod tests { #[test] fn the_session_decides_by_default() { - assert_eq!(choisir(Graphique::Wayland, None), Ok(Backend::Portail)); - assert_eq!(choisir(Graphique::X11, None), Ok(Backend::X11)); + assert_eq!(choose(DisplaySession::Wayland, None), Ok(Backend::Portal)); + assert_eq!(choose(DisplaySession::X11, None), Ok(Backend::X11)); assert_eq!( - choisir(Graphique::Aucune, None), - Err(ChoixError::PasDeSession) + choose(DisplaySession::Headless, None), + Err(BackendChoiceError::NoSession) ); } #[test] fn the_override_wins_even_against_the_session() { - assert_eq!(choisir(Graphique::Wayland, Some("x11")), Ok(Backend::X11)); assert_eq!( - choisir(Graphique::X11, Some("Portail")), - Ok(Backend::Portail) + choose(DisplaySession::Wayland, Some("x11")), + Ok(Backend::X11) ); assert_eq!( - choisir(Graphique::Aucune, Some("synthetique")), - Ok(Backend::Synthetique) + choose(DisplaySession::X11, Some("Portail")), + Ok(Backend::Portal) + ); + assert_eq!( + choose(DisplaySession::Headless, Some("synthetique")), + Ok(Backend::Synthetic) + ); + assert_eq!( + choose(DisplaySession::Headless, Some("synthetic")), + Ok(Backend::Synthetic) ); } #[test] fn an_empty_override_is_ignored() { - assert_eq!(choisir(Graphique::X11, Some(" ")), Ok(Backend::X11)); + assert_eq!(choose(DisplaySession::X11, Some(" ")), Ok(Backend::X11)); } #[test] fn an_unknown_override_is_refused_by_name() { - let erreur = choisir(Graphique::X11, Some("dxgi")).unwrap_err(); - assert!(erreur.to_string().contains("dxgi")); + let error = choose(DisplaySession::X11, Some("dxgi")).unwrap_err(); + assert!(error.to_string().contains("dxgi")); } } diff --git a/crates/rs-capture/src/cadence.rs b/crates/rs-capture/src/cadence.rs index b05c68d..97b8510 100644 --- a/crates/rs-capture/src/cadence.rs +++ b/crates/rs-capture/src/cadence.rs @@ -1,10 +1,10 @@ -//! Cadence régulière d'une source de capture. +//! Regular cadence of a capture source. //! -//! Les horodatages RTP avancent d'un pas fixe par image: une source qui livre -//! par à-coups fait dériver la gigue côté spectateur. On attend donc l'échéance -//! suivante au lieu de produire au plus vite, et l'échéance avance d'une période -//! exacte, pas de « maintenant plus une période », pour ne pas accumuler le -//! retard de chaque réveil. +//! RTP timestamps advance by a fixed step per frame: a source that delivers in +//! bursts makes the jitter drift on the viewer side. So we wait for the next +//! deadline instead of producing as fast as possible, and the deadline +//! advances by exactly one period, not "now plus one period", so the delay of +//! each wake-up does not accumulate. use std::time::{Duration, Instant}; @@ -21,15 +21,15 @@ impl Cadence { } } - /// Bloque jusqu'à la prochaine échéance. + /// Blocks until the next deadline. pub fn wait(&mut self) { let now = Instant::now(); let due = self.next_at.unwrap_or(now); if due > now { std::thread::sleep(due - now); } - // Après un long retard (machine suspendue, source bloquée), repartir de - // maintenant: rattraper produirait une rafale d'images. + // After a long delay (suspended machine, stalled source), restart from + // now: catching up would produce a burst of frames. let next = due + self.period; self.next_at = Some(if next + self.period * 4 < now { now + self.period @@ -54,7 +54,7 @@ mod tests { for _ in 0..6 { cadence.wait(); } - // Cinq périodes de 20 ms après la première échéance, immédiate. + // Five 20 ms periods after the first deadline, which is immediate. let elapsed = started.elapsed(); assert!(elapsed >= Duration::from_millis(95), "{elapsed:?}"); assert!(elapsed < Duration::from_millis(250), "{elapsed:?}"); @@ -70,7 +70,7 @@ mod tests { cadence.wait(); assert!( started.elapsed() >= Duration::from_millis(15), - "après un retard, l'image suivante doit attendre une période" + "after a delay, the next frame must wait one period" ); } } diff --git a/crates/rs-capture/src/frame.rs b/crates/rs-capture/src/frame.rs index 1012a03..4b317f8 100644 --- a/crates/rs-capture/src/frame.rs +++ b/crates/rs-capture/src/frame.rs @@ -1,20 +1,20 @@ -//! Capture d'écran: une interface, une implémentation par système. +//! Screen capture: one interface, one implementation per system. //! -//! Le trait ne ment pas sur les capacités: tout ce qu'une plateforme ne sait -//! pas faire (partager une fenêtre précise sous Wayland, par exemple) doit être -//! visible dans les données, pas découvert par l'utilisateur à l'usage. +//! The trait does not lie about capabilities: anything a platform cannot do +//! (sharing one specific window under Wayland, for instance) must be visible +//! in the data, not discovered by the user in use. use std::time::Instant; -/// Une image brute, telle que la rend le système, en BGRA 8 bits. +/// A raw image, as the system delivers it, in 8-bit BGRA. #[derive(Clone)] pub struct CapturedFrame { pub width: u32, pub height: u32, - /// Largeur * hauteur * 4 octets, ordre B, G, R, A. + /// Width * height * 4 bytes, in B, G, R, A order. pub bgra: Vec, pub captured_at: Instant, - /// Numéro d'ordre, pour détecter une frame sautée ou dupliquée. + /// Sequence number, to detect a skipped or duplicated frame. pub sequence: u64, } @@ -26,15 +26,15 @@ impl CapturedFrame { #[derive(Debug, Clone, thiserror::Error, PartialEq, Eq)] pub enum CaptureError { - #[error("permission de capture refusée par le système")] + #[error("capture permission denied by the system")] PermissionDenied, - #[error("la source a disparu (écran débranché, fenêtre fermée)")] + #[error("the source is gone (screen unplugged, window closed)")] SourceGone, - #[error("capture impossible sur cette plateforme: {0}")] + #[error("capture not possible on this platform: {0}")] Unsupported(String), - /// La source existe mais ne peut pas être lue maintenant (fenêtre réduite). + /// The source exists but cannot be read right now (minimized window). #[error("{0}")] - Indisponible(String), - #[error("erreur interne: {0}")] + Unavailable(String), + #[error("internal error: {0}")] Internal(String), } diff --git a/crates/rs-capture/src/lib.rs b/crates/rs-capture/src/lib.rs index 28e3022..1b874cb 100644 --- a/crates/rs-capture/src/lib.rs +++ b/crates/rs-capture/src/lib.rs @@ -1,12 +1,13 @@ -//! Capture d'écran et de fenêtres. +//! Screen and window capture. //! -//! Une interface [`ScreenCapturer`], une implémentation par système, et une -//! mire synthétique pour tester le reste du pipeline sans écran. Sous Linux: -//! le portail et PipeWire pour Wayland ([`pipewire`], feature `pipewire`), X11 -//! en repli ([`x11`]). Le choix du chemin est dans [`backend`]. +//! One [`ScreenCapturer`] interface, one implementation per system, and a +//! synthetic test pattern to test the rest of the pipeline without a screen. +//! On Linux: the portal and PipeWire for Wayland ([`pipewire`], `pipewire` +//! feature), X11 as a fallback ([`x11`]). The choice of path lives in +//! [`backend`]. //! -//! Sortie: des frames BGRA avec un horodatage monotone. La conversion en I420 et -//! l'encodage appartiennent à `rs-codec`. +//! Output: BGRA frames with a monotonic timestamp. Conversion to I420 and +//! encoding belong to `rs-codec`. pub mod backend; pub mod cadence; @@ -20,7 +21,7 @@ pub mod pipewire; #[cfg(target_os = "linux")] pub mod x11; -pub use backend::{Backend, Graphique}; +pub use backend::{Backend, DisplaySession}; pub use frame::{CaptureError, CapturedFrame}; pub use source::{ScreenCapturer, describe}; pub use synthetic::SyntheticCapturer; diff --git a/crates/rs-capture/src/pipewire.rs b/crates/rs-capture/src/pipewire.rs index 51322ab..6e0a1fc 100644 --- a/crates/rs-capture/src/pipewire.rs +++ b/crates/rs-capture/src/pipewire.rs @@ -1,21 +1,21 @@ -//! Capture Wayland: consommer le flux PipeWire rendu par le portail. +//! Wayland capture: consuming the PipeWire stream handed over by the portal. //! -//! Le portail (`rs-platform::portal`) négocie la capture et rend un descripteur -//! et un identifiant de nœud. Ce module s'y connecte et transforme les tampons -//! en images BGRA, à cadence régulière. +//! The portal (`rs-platform::portal`) negotiates the capture and returns a file +//! descriptor and a node id. This module connects to it and turns the buffers +//! into BGRA images, at a regular cadence. //! -//! Trois choix, et leur raison: +//! Three choices, and why: //! -//! - **un thread dédié** porte la boucle PipeWire: ses objets ne sont pas -//! `Send`, et la boucle ne doit jamais tourner dans une tâche tokio; -//! - **mémoire partagée seulement**: on n'annonce aucun modificateur DMA-BUF, -//! donc le compositeur rend des tampons en mémoire (MemFd ou MemPtr). Le -//! chemin sans copie CPU viendra avec l'encodage matériel, qui saura lire une -//! texture; aujourd'hui l'encodeur logiciel recopierait de toute façon; -//! - **duplication de la dernière image**: GNOME n'envoie une image que quand -//! l'écran change. Le pipeline, lui, avance à pas fixe (voir AGENTS.md): -//! l'image précédente est rendue telle quelle, l'encodeur VP8 la compresse en -//! quelques octets. +//! - **a dedicated thread** runs the PipeWire loop: its objects are not +//! `Send`, and the loop must never run inside a tokio task; +//! - **shared memory only**: we announce no DMA-BUF modifier, so the +//! compositor hands memory buffers (MemFd or MemPtr). The zero-copy path will +//! come with hardware encoding, which will be able to read a texture; today +//! the software encoder would copy anyway; +//! - **duplicating the last image**: GNOME only sends an image when the screen +//! changes. The pipeline, though, moves at a fixed step (see AGENTS.md): the +//! previous image is returned as is, and the VP8 encoder compresses it to a +//! few bytes. use std::os::fd::OwnedFd; use std::sync::{Arc, Condvar, Mutex, MutexGuard}; @@ -31,190 +31,191 @@ use crate::frame::{CaptureError, CapturedFrame}; use crate::pixels::{self, PixelFormat}; use crate::source::{ScreenCapturer, describe}; -/// Ce qu'on demande au compositeur. +/// What we ask of the compositor. #[derive(Debug, Clone, Copy)] pub struct PipeWireOptions { pub fps: u8, - /// Taille imposée. Utile pour un écran virtuel: c'est le consommateur qui - /// en fixe la résolution. Pour un moniteur réel, `None` accepte la sienne. + /// Forced size. Useful for a virtual screen: the consumer sets its + /// resolution. For a real monitor, `None` accepts the monitor's own. pub size: Option<(u32, u32)>, } -/// Délai d'attente de la première image, au-delà duquel on considère que le -/// compositeur ne livrera rien. -const PREMIERE_IMAGE: Duration = Duration::from_secs(3); +/// How long to wait for the first image, beyond which we consider that the +/// compositor will deliver nothing. +const FIRST_FRAME_TIMEOUT: Duration = Duration::from_secs(3); #[derive(Default)] -struct Etat { - /// Dernière image convertie en BGRA serré. +struct State { + /// Last image, converted to tightly packed BGRA. bgra: Vec, - taille: (u32, u32), - /// Une image est arrivée depuis la dernière lecture. - neuve: bool, - /// Nombre d'images reçues du compositeur, pour les diagnostics. - recues: u64, + size: (u32, u32), + /// An image arrived since the last read. + fresh: bool, + /// Number of images received from the compositor, for diagnostics. + received: u64, format: Option<(PixelFormat, u32, u32)>, - /// La capture est terminée, et pourquoi. Plus aucune image n'arrivera. - fin: Option, - /// Le flux a atteint l'état `Streaming` au moins une fois. - actif: bool, + /// The capture has ended, and why. No more images will arrive. + end: Option, + /// The stream reached the `Streaming` state at least once. + active: bool, } -struct Partage { - etat: Mutex, +struct Shared { + state: Mutex, signal: Condvar, } -impl Partage { - fn lock(&self) -> MutexGuard<'_, Etat> { - self.etat.lock().unwrap_or_else(|e| e.into_inner()) +impl Shared { + fn lock(&self) -> MutexGuard<'_, State> { + self.state.lock().unwrap_or_else(|e| e.into_inner()) } - fn terminer(&self, raison: CaptureError) { - let mut etat = self.lock(); - if etat.fin.is_none() { - tracing::warn!(evenement = "capture_terminee", raison = %raison, "fin de la capture"); - etat.fin = Some(raison); + fn end(&self, reason: CaptureError) { + let mut state = self.lock(); + if state.end.is_none() { + tracing::warn!(event = "capture_ended", reason = %reason, "capture ended"); + state.end = Some(reason); } - drop(etat); + drop(state); self.signal.notify_all(); } } -/// Permet à un autre composant (le portail, qui voit la session se fermer) de -/// déclarer la capture terminée. +/// Lets another component (the portal, which sees the session close) declare +/// the capture over. #[derive(Clone)] -pub struct Revocation(Arc); +pub struct Revocation(Arc); impl Revocation { - pub fn revoquer(&self, raison: CaptureError) { - self.0.terminer(raison); + pub fn revoke(&self, reason: CaptureError) { + self.0.end(reason); } } pub struct PipeWireCapturer { - partage: Arc, + shared: Arc, node_id: u32, - quitter: pw::channel::Sender<()>, + quit: pw::channel::Sender<()>, thread: Option>, cadence: Cadence, sequence: u64, - /// Taille négociée au départ, pour décrire la source. Les images suivent - /// ensuite la taille courante du flux. - sortie: Option<(u32, u32)>, - derniere: Vec, - ajustee: Vec, + /// Size negotiated at start, to describe the source. Images then follow + /// the current size of the stream. + output: Option<(u32, u32)>, + last: Vec, + fitted: Vec, started: bool, } impl PipeWireCapturer { - /// Se connecte au flux du portail. Ne bloque pas sur la première image: - /// voir [`Self::attendre_format`]. - pub fn connecter( + /// Connects to the portal's stream. Does not block on the first image: + /// see [`Self::wait_for_format`]. + pub fn connect( fd: OwnedFd, node_id: u32, options: PipeWireOptions, ) -> Result { - let partage = Arc::new(Partage { - etat: Mutex::new(Etat::default()), + let shared = Arc::new(Shared { + state: Mutex::new(State::default()), signal: Condvar::new(), }); - let (quitter, recepteur) = pw::channel::channel::<()>(); - let (pret_tx, pret_rx) = std::sync::mpsc::channel::>(); + let (quit, receiver) = pw::channel::channel::<()>(); + let (ready_tx, ready_rx) = std::sync::mpsc::channel::>(); - let partage_thread = partage.clone(); + let thread_shared = shared.clone(); let thread = std::thread::Builder::new() .name("rustscreen-pipewire".into()) .spawn(move || { - if let Err(erreur) = - boucle(fd, node_id, options, partage_thread, recepteur, &pret_tx) + if let Err(error) = + run_loop(fd, node_id, options, thread_shared, receiver, &ready_tx) { - let _ = pret_tx.send(Err(erreur)); + let _ = ready_tx.send(Err(error)); } }) - .map_err(|e| CaptureError::Internal(format!("thread PipeWire: {e}")))?; + .map_err(|e| CaptureError::Internal(format!("PipeWire thread: {e}")))?; - match pret_rx.recv_timeout(Duration::from_secs(5)) { + match ready_rx.recv_timeout(Duration::from_secs(5)) { Ok(Ok(())) => {} - Ok(Err(erreur)) => { + Ok(Err(error)) => { let _ = thread.join(); - return Err(erreur); + return Err(error); } Err(_) => { return Err(CaptureError::Internal( - "PipeWire ne s'est pas initialisé en 5 s".into(), + "PipeWire did not initialize within 5 s".into(), )); } } Ok(Self { - partage, + shared, node_id, - quitter, + quit, thread: Some(thread), cadence: Cadence::new(options.fps), sequence: 0, - sortie: None, - derniere: Vec::new(), - ajustee: Vec::new(), + output: None, + last: Vec::new(), + fitted: Vec::new(), started: false, }) } - /// Attend que le compositeur ait fixé le format, et rend la taille que - /// recevra l'encodeur (paire). C'est elle qui configure l'encodeur. - pub fn attendre_format(&mut self, delai: Duration) -> Result<(u32, u32), CaptureError> { - let limite = Instant::now() + delai; - let mut etat = self.partage.lock(); + /// Waits until the compositor has settled the format, and returns the + /// (even) size the encoder will receive. That size configures the encoder. + pub fn wait_for_format(&mut self, timeout: Duration) -> Result<(u32, u32), CaptureError> { + let deadline = Instant::now() + timeout; + let mut state = self.shared.lock(); loop { - if let Some(fin) = &etat.fin { - return Err(fin.clone()); + if let Some(end) = &state.end { + return Err(end.clone()); } - if let Some((_, w, h)) = etat.format { - let taille = pixels::even((w, h)); - self.sortie = Some(taille); - return Ok(taille); + if let Some((_, w, h)) = state.format { + let size = pixels::even((w, h)); + self.output = Some(size); + return Ok(size); } - let reste = limite.saturating_duration_since(Instant::now()); - if reste.is_zero() { + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { return Err(CaptureError::Internal(format!( - "aucun format négocié avec le compositeur en {} s", - delai.as_secs() + "no format negotiated with the compositor within {} s", + timeout.as_secs() ))); } - etat = self - .partage + state = self + .shared .signal - .wait_timeout(etat, reste) + .wait_timeout(state, remaining) .unwrap_or_else(|e| e.into_inner()) .0; } } pub fn revocation(&self) -> Revocation { - Revocation(self.partage.clone()) + Revocation(self.shared.clone()) } - /// Images reçues du compositeur (pas celles livrées, qui incluent les - /// duplications). - pub fn recues(&self) -> u64 { - self.partage.lock().recues + /// Images received from the compositor (not the ones delivered, which + /// include duplicates). + pub fn received(&self) -> u64 { + self.shared.lock().received } fn source_id(&self) -> String { + // Value kept as it was, like the X11 identifiers. format!("portail:{}", self.node_id) } } impl ScreenCapturer for PipeWireCapturer { fn sources(&mut self) -> Result, CaptureError> { - let (w, h) = self.sortie.unwrap_or((0, 0)); - // Le nom ne dit rien de l'écran: le portail ne le donne pas, et c'est - // l'utilisateur qui l'a choisi dans le sélecteur. + let (w, h) = self.output.unwrap_or((0, 0)); + // The name says nothing about the screen: the portal does not give + // it, and the user picked it in the chooser. Ok(vec![describe( self.source_id(), SourceKind::Screen, - "Écran choisi dans le portail", + "Screen chosen in the portal", w, h, true, @@ -232,60 +233,62 @@ impl ScreenCapturer for PipeWireCapturer { fn next_frame(&mut self) -> Result { if !self.started { - return Err(CaptureError::Internal("capture non démarrée".into())); + return Err(CaptureError::Internal("capture not started".into())); } self.cadence.wait(); - let mut etat = self.partage.lock(); - if let Some(fin) = &etat.fin { - return Err(fin.clone()); + let mut state = self.shared.lock(); + if let Some(end) = &state.end { + return Err(end.clone()); } - if etat.recues == 0 { - // Première image: le compositeur peut prendre un moment, surtout - // pour créer un écran virtuel. - etat = self - .partage + if state.received == 0 { + // First image: the compositor may take a moment, especially to + // create a virtual screen. + state = self + .shared .signal - .wait_timeout_while(etat, PREMIERE_IMAGE, |e| e.recues == 0 && e.fin.is_none()) + .wait_timeout_while(state, FIRST_FRAME_TIMEOUT, |s| { + s.received == 0 && s.end.is_none() + }) .unwrap_or_else(|e| e.into_inner()) .0; - if let Some(fin) = &etat.fin { - return Err(fin.clone()); + if let Some(end) = &state.end { + return Err(end.clone()); } - if etat.recues == 0 { + if state.received == 0 { return Err(CaptureError::Internal( - "aucune image reçue du compositeur".into(), + "no image received from the compositor".into(), )); } } - let (w, h) = etat.taille; - if etat.neuve { - std::mem::swap(&mut self.derniere, &mut etat.bgra); - etat.neuve = false; + let (w, h) = state.size; + if state.fresh { + std::mem::swap(&mut self.last, &mut state.bgra); + state.fresh = false; } - drop(etat); + drop(state); - // La sortie suit le flux: un moniteur dont la résolution change est - // renégocié par PipeWire, et l'encodeur se reconfigure (#16). Seule une - // dimension impaire est rognée. - let sortie = pixels::even((w, h)); - let bgra = if (w, h) == sortie { - self.derniere.clone() + // The output follows the stream: a monitor whose resolution changes is + // renegotiated by PipeWire, and the encoder reconfigures itself (#16). + // Only an odd dimension is trimmed. + let output = pixels::even((w, h)); + let bgra = if (w, h) == output { + self.last.clone() } else { pixels::fit( - &self.derniere, + &self.last, w as usize, h as usize, - (sortie.0 as usize, sortie.1 as usize), - &mut self.ajustee, + (output.0 as usize, output.1 as usize), + &mut self.fitted, ); - self.ajustee.clone() + self.fitted.clone() }; let frame = CapturedFrame { - width: sortie.0, - height: sortie.1, + width: output.0, + height: output.1, bgra, captured_at: Instant::now(), sequence: self.sequence, @@ -296,60 +299,60 @@ impl ScreenCapturer for PipeWireCapturer { fn stop(&mut self) { self.started = false; - let _ = self.quitter.send(()); + let _ = self.quit.send(()); } } impl Drop for PipeWireCapturer { fn drop(&mut self) { - let _ = self.quitter.send(()); + let _ = self.quit.send(()); if let Some(thread) = self.thread.take() { let _ = thread.join(); } } } -/// Ce que la boucle garde entre deux rappels. -struct Locale { - partage: Arc, +/// What the loop keeps between two callbacks. +struct LoopData { + shared: Arc, format: Option<(PixelFormat, u32, u32)>, - tampon: Vec, - /// Octets lus d'un tampon MemFd non mappé. - lu: Vec, - signale: bool, - /// Le premier tampon a été décrit au journal. - decrit: bool, + buffer: Vec, + /// Bytes read from an unmapped MemFd buffer. + read: Vec, + warned: bool, + /// The first buffer has been described in the log. + described: bool, } -/// La boucle PipeWire, dans son thread. Signale `pret` une fois le flux -/// connecté, puis tourne jusqu'à la demande d'arrêt. -fn boucle( +/// The PipeWire loop, in its own thread. Signals `ready` once the stream is +/// connected, then runs until asked to stop. +fn run_loop( fd: OwnedFd, node_id: u32, options: PipeWireOptions, - partage: Arc, - recepteur: pw::channel::Receiver<()>, - pret: &std::sync::mpsc::Sender>, + shared: Arc, + receiver: pw::channel::Receiver<()>, + ready: &std::sync::mpsc::Sender>, ) -> Result<(), CaptureError> { - let interne = |contexte: &str, e: pw::Error| CaptureError::Internal(format!("{contexte}: {e}")); + let internal = |context: &str, e: pw::Error| CaptureError::Internal(format!("{context}: {e}")); pw::init(); - let mainloop = pw::main_loop::MainLoopRc::new(None).map_err(|e| interne("boucle", e))?; + let mainloop = pw::main_loop::MainLoopRc::new(None).map_err(|e| internal("main loop", e))?; let context = - pw::context::ContextRc::new(&mainloop, None).map_err(|e| interne("contexte", e))?; + pw::context::ContextRc::new(&mainloop, None).map_err(|e| internal("context", e))?; let core = context .connect_fd_rc(fd, None) - .map_err(|e| interne("connexion au flux du portail", e))?; + .map_err(|e| internal("connection to the portal stream", e))?; - let partage_core = partage.clone(); + let core_shared = shared.clone(); let _core_listener = core .add_listener_local() .error(move |id, _seq, res, message| { - // Une erreur sur l'objet 0 (le cœur) coupe la connexion: le portail - // a fermé le flux, ou le compositeur s'est arrêté. - tracing::warn!(id, res, message, "erreur PipeWire"); + // An error on object 0 (the core) cuts the connection: the portal + // closed the stream, or the compositor stopped. + tracing::warn!(id, res, message, "PipeWire error"); if id == 0 { - partage_core.terminer(CaptureError::SourceGone); + core_shared.end(CaptureError::SourceGone); } }) .register(); @@ -363,55 +366,58 @@ fn boucle( *pw::keys::MEDIA_ROLE => "Screen", }, ) - .map_err(|e| interne("flux", e))?; + .map_err(|e| internal("stream", e))?; - let locale = Locale { - partage: partage.clone(), + let data = LoopData { + shared: shared.clone(), format: None, - tampon: Vec::new(), - lu: Vec::new(), - signale: false, - decrit: false, + buffer: Vec::new(), + read: Vec::new(), + warned: false, + described: false, }; let _listener = stream - .add_local_listener_with_user_data(locale) - .state_changed(|_, locale, avant, apres| { - tracing::debug!(?avant, ?apres, "état du flux PipeWire"); - match apres { + .add_local_listener_with_user_data(data) + .state_changed(|_, data, before, after| { + tracing::debug!(?before, ?after, "PipeWire stream state"); + match after { pw::stream::StreamState::Streaming => { - let mut etat = locale.partage.lock(); - if !etat.actif { - tracing::info!(evenement = "flux_pipewire_actif", "le compositeur diffuse"); + let mut state = data.shared.lock(); + if !state.active { + tracing::info!( + event = "pipewire_stream_active", + "the compositor is streaming" + ); } - etat.actif = true; + state.active = true; } pw::stream::StreamState::Error(message) => { - let actif = locale.partage.lock().actif; - locale.partage.terminer(if actif { + let active = data.shared.lock().active; + data.shared.end(if active { CaptureError::SourceGone } else { - CaptureError::Internal(format!("flux PipeWire en erreur: {message}")) + CaptureError::Internal(format!("PipeWire stream error: {message}")) }); } - // Le nœud a disparu: c'est ce qui arrive quand l'utilisateur - // arrête le partage depuis le bureau. - pw::stream::StreamState::Unconnected if locale.partage.lock().actif => { - locale.partage.terminer(CaptureError::SourceGone); + // The node is gone: this is what happens when the user stops + // sharing from the desktop. + pw::stream::StreamState::Unconnected if data.shared.lock().active => { + data.shared.end(CaptureError::SourceGone); } _ => {} } }) - .param_changed(|_, locale, id, param| { + .param_changed(|_, data, id, param| { let Some(param) = param else { return }; if id != spa::param::ParamType::Format.as_raw() { return; } - let Ok((media, sous_type)) = spa::param::format_utils::parse_format(param) else { + let Ok((media, subtype)) = spa::param::format_utils::parse_format(param) else { return; }; if media != spa::param::format::MediaType::Video - || sous_type != spa::param::format::MediaSubtype::Raw + || subtype != spa::param::format::MediaSubtype::Raw { return; } @@ -419,143 +425,144 @@ fn boucle( if info.parse(param).is_err() { return; } - let taille = info.size(); + let size = info.size(); let format = match info.format() { spa::param::video::VideoFormat::BGRA => PixelFormat::Bgra, spa::param::video::VideoFormat::BGRx => PixelFormat::Bgrx, spa::param::video::VideoFormat::RGBA => PixelFormat::Rgba, spa::param::video::VideoFormat::RGBx => PixelFormat::Rgbx, - autre => { - // Ne devrait pas arriver: on n'a proposé que ces quatre-là. - locale.partage.terminer(CaptureError::Unsupported(format!( - "format de pixels non négocié: {autre:?}" + other => { + // Should not happen: we only offered these four. + data.shared.end(CaptureError::Unsupported(format!( + "pixel format not negotiated: {other:?}" ))); return; } }; tracing::info!( - evenement = "format_capture", + event = "capture_format", format = ?format, - largeur = taille.width, - hauteur = taille.height, - "format négocié avec le compositeur" + width = size.width, + height = size.height, + "format negotiated with the compositor" ); - let negocie = (format, taille.width, taille.height); - locale.format = Some(negocie); - locale.partage.lock().format = Some(negocie); - locale.partage.signal.notify_all(); + let negotiated = (format, size.width, size.height); + data.format = Some(negotiated); + data.shared.lock().format = Some(negotiated); + data.shared.signal.notify_all(); }) - .process(|stream, locale| { - // Garder la plus récente des images en attente: les autres sont - // déjà périmées, et les rendre libère leur tampon au compositeur. - let mut derniere = None; + .process(|stream, data| { + // Keep the most recent of the pending images: the others are + // already stale, and returning them frees their buffer for the + // compositor. + let mut latest = None; while let Some(buffer) = stream.dequeue_buffer() { - derniere = Some(buffer); + latest = Some(buffer); } - let Some(mut buffer) = derniere else { return }; - let Some((format, w, h)) = locale.format else { + let Some(mut buffer) = latest else { return }; + let Some((format, w, h)) = data.format else { return; }; let datas = buffer.datas_mut(); - let Some(data) = datas.first_mut() else { + let Some(plane) = datas.first_mut() else { return; }; - if !locale.decrit { - // Le premier tampon dit comment le compositeur livre: c'est la - // première question quand l'image reste noire. - locale.decrit = true; - let chunk = data.chunk(); + if !data.described { + // The first buffer tells how the compositor delivers: it is + // the first question when the image stays black. + data.described = true; + let chunk = plane.chunk(); tracing::info!( - evenement = "premier_tampon", - genre = ?data.type_(), - taille = chunk.size(), + event = "first_buffer", + kind = ?plane.type_(), + size = chunk.size(), stride = chunk.stride(), - mappe = data.data().is_some(), - "premier tampon du compositeur" + mapped = plane.data().is_some(), + "first buffer from the compositor" ); } - if data.type_() == spa::buffer::DataType::DmaBuf { - if !locale.signale { - locale.signale = true; - tracing::warn!("tampon DMA-BUF reçu alors que seule la mémoire a été demandée"); + if plane.type_() == spa::buffer::DataType::DmaBuf { + if !data.warned { + data.warned = true; + tracing::warn!("DMA-BUF buffer received although only memory was requested"); } return; } - let chunk = data.chunk(); + let chunk = plane.chunk(); let offset = chunk.offset() as usize; - let taille = chunk.size() as usize; + let size = chunk.size() as usize; let stride = match chunk.stride() { s if s > 0 => s as usize, _ => w as usize * 4, }; - // Un tampon vide signale une image sans changement (curseur seul, - // ou image corrompue): on garde la précédente. - if taille == 0 { + // An empty buffer signals an unchanged image (cursor only, or a + // corrupted image): we keep the previous one. + if size == 0 { return; } - // GNOME livre des tampons MemFd que PipeWire ne mappe pas (pas de - // drapeau MAPPABLE): `data()` est vide. On lit alors la zone utile - // du descripteur par `pread`, comme le segment MIT-SHM sous X11, - // sans `mmap`. Ignorer ces tampons donnait un écran noir. - let genre = data.type_(); - let descripteur = data.fd(); - let decalage = data.as_raw().mapoffset as usize; - let octets: &[u8] = match data.data() { - Some(octets) => { - let fin = (offset + taille).min(octets.len()); - if offset >= fin { + // GNOME delivers MemFd buffers that PipeWire does not map (no + // MAPPABLE flag): `data()` is empty. We then read the useful area + // of the descriptor with `pread`, like the MIT-SHM segment under + // X11, without `mmap`. Ignoring these buffers gave a black screen. + let kind = plane.type_(); + let raw_fd = plane.fd(); + let map_offset = plane.as_raw().mapoffset as usize; + let bytes: &[u8] = match plane.data() { + Some(bytes) => { + let end = (offset + size).min(bytes.len()); + if offset >= end { return; } - &octets[offset..fin] + &bytes[offset..end] } - None if genre == spa::buffer::DataType::MemFd && descripteur >= 0 => { - match lire_memfd(descripteur, decalage + offset, taille, &mut locale.lu) { - Ok(()) => &locale.lu, - Err(erreur) => { - if !locale.signale { - locale.signale = true; - tracing::warn!(%erreur, "tampon MemFd illisible: image ignorée"); + None if kind == spa::buffer::DataType::MemFd && raw_fd >= 0 => { + match read_memfd(raw_fd, map_offset + offset, size, &mut data.read) { + Ok(()) => &data.read, + Err(error) => { + if !data.warned { + data.warned = true; + tracing::warn!(%error, "unreadable MemFd buffer: image skipped"); } return; } } } None => { - if !locale.signale { - locale.signale = true; - tracing::warn!(?genre, "tampon PipeWire non mappé: image ignorée"); + if !data.warned { + data.warned = true; + tracing::warn!(?kind, "unmapped PipeWire buffer: image skipped"); } return; } }; - if let Err(erreur) = pixels::to_bgra( + if let Err(error) = pixels::to_bgra( format, - octets, + bytes, stride, w as usize, h as usize, - &mut locale.tampon, + &mut data.buffer, ) { - if !locale.signale { - locale.signale = true; - tracing::warn!(%erreur, "image PipeWire illisible"); + if !data.warned { + data.warned = true; + tracing::warn!(%error, "unreadable PipeWire image"); } return; } - let mut etat = locale.partage.lock(); - std::mem::swap(&mut etat.bgra, &mut locale.tampon); - etat.taille = (w, h); - etat.neuve = true; - etat.recues += 1; - drop(etat); - locale.partage.signal.notify_all(); + let mut state = data.shared.lock(); + std::mem::swap(&mut state.bgra, &mut data.buffer); + state.size = (w, h); + state.fresh = true; + state.received += 1; + drop(state); + data.shared.signal.notify_all(); }) .register() - .map_err(|e| interne("écouteur du flux", e))?; + .map_err(|e| internal("stream listener", e))?; - let parametres = parametres_format(options); - let mut params = [spa::pod::Pod::from_bytes(¶metres) - .ok_or_else(|| CaptureError::Internal("paramètres de format invalides".into()))?]; + let format_params = format_parameters(options); + let mut params = [spa::pod::Pod::from_bytes(&format_params) + .ok_or_else(|| CaptureError::Internal("invalid format parameters".into()))?]; stream .connect( spa::utils::Direction::Input, @@ -563,31 +570,31 @@ fn boucle( pw::stream::StreamFlags::AUTOCONNECT | pw::stream::StreamFlags::MAP_BUFFERS, &mut params, ) - .map_err(|e| interne("connexion au nœud", e))?; + .map_err(|e| internal("connection to the node", e))?; - let boucle_faible = mainloop.downgrade(); - let _arret = recepteur.attach(mainloop.loop_(), move |()| { - if let Some(boucle) = boucle_faible.upgrade() { - boucle.quit(); + let weak_loop = mainloop.downgrade(); + let _stop = receiver.attach(mainloop.loop_(), move |()| { + if let Some(main_loop) = weak_loop.upgrade() { + main_loop.quit(); } }); - let _ = pret.send(Ok(())); + let _ = ready.send(Ok(())); mainloop.run(); let _ = stream.disconnect(); Ok(()) } -/// Les formats qu'on sait convertir, et la taille voulue. -fn parametres_format(options: PipeWireOptions) -> Vec { +/// The formats we can convert, and the wanted size. +fn format_parameters(options: PipeWireOptions) -> Vec { use spa::param::format::{FormatProperties, MediaSubtype, MediaType}; use spa::param::video::VideoFormat; use spa::utils::{Fraction, Rectangle}; let fps = options.fps.clamp(1, 60) as u32; - let taille = match options.size { - // Taille imposée: un écran virtuel prend la résolution que le - // consommateur fixe, une plage le laisserait choisir la sienne. + let size = match options.size { + // Forced size: a virtual screen takes the resolution the consumer + // sets, a range would let it pick its own. Some((width, height)) => spa::pod::property!( FormatProperties::VideoSize, Rectangle, @@ -612,13 +619,13 @@ fn parametres_format(options: PipeWireOptions) -> Vec { } ), }; - let objet = spa::pod::object!( + let object = spa::pod::object!( spa::utils::SpaTypes::ObjectParamFormat, spa::param::ParamType::EnumFormat, spa::pod::property!(FormatProperties::MediaType, Id, MediaType::Video), spa::pod::property!(FormatProperties::MediaSubtype, Id, MediaSubtype::Raw), - // 8 bits seulement: un format 10 bits lu comme du 8 bits donnerait des - // couleurs fausses (AGENTS.md). + // 8 bits only: a 10-bit format read as 8-bit would give wrong colors + // (AGENTS.md). spa::pod::property!( FormatProperties::VideoFormat, Choice, @@ -630,7 +637,7 @@ fn parametres_format(options: PipeWireOptions) -> Vec { VideoFormat::RGBx, VideoFormat::RGBA, ), - taille, + size, spa::pod::property!( FormatProperties::VideoFramerate, Choice, @@ -646,32 +653,32 @@ fn parametres_format(options: PipeWireOptions) -> Vec { ); spa::pod::serialize::PodSerializer::serialize( std::io::Cursor::new(Vec::new()), - &spa::pod::Value::Object(objet), + &spa::pod::Value::Object(object), ) - .map(|(curseur, _)| curseur.into_inner()) + .map(|(cursor, _)| cursor.into_inner()) .unwrap_or_default() } -/// Lit `taille` octets d'un tampon MemFd à partir de `position`, sans le -/// mapper. -fn lire_memfd( - descripteur: std::os::fd::RawFd, +/// Reads `size` bytes of a MemFd buffer starting at `position`, without +/// mapping it. +fn read_memfd( + raw_fd: std::os::fd::RawFd, position: usize, - taille: usize, - sortie: &mut Vec, + size: usize, + out: &mut Vec, ) -> std::io::Result<()> { - // SAFETY: le descripteur appartient au tampon que PipeWire nous prête - // pendant ce rappel `process`; il reste ouvert jusqu'à la remise du - // tampon, après notre retour. On ne fait que l'emprunter, sans le fermer. - let fd = unsafe { std::os::fd::BorrowedFd::borrow_raw(descripteur) }; - sortie.resize(taille, 0); - let mut lus = 0; - while lus < taille { - let n = rustix::io::pread(fd, &mut sortie[lus..], (position + lus) as u64)?; + // SAFETY: the descriptor belongs to the buffer PipeWire lends us during + // this `process` callback; it stays open until the buffer is queued back, + // after we return. We only borrow it, without closing it. + let fd = unsafe { std::os::fd::BorrowedFd::borrow_raw(raw_fd) }; + out.resize(size, 0); + let mut read = 0; + while read < size { + let n = rustix::io::pread(fd, &mut out[read..], (position + read) as u64)?; if n == 0 { return Err(std::io::ErrorKind::UnexpectedEof.into()); } - lus += n; + read += n; } Ok(()) } @@ -680,40 +687,40 @@ fn lire_memfd( mod tests { use super::*; - /// Le chemin des tampons MemFd non mappés (GNOME): la zone utile se lit à - /// la bonne position, et un descripteur trop court se dit au lieu de - /// rendre une image tronquée. + /// The path for unmapped MemFd buffers (GNOME): the useful area is read + /// at the right position, and a descriptor that is too short says so + /// instead of returning a truncated image. #[test] fn an_unmapped_memfd_is_read_at_its_offset() { use std::os::fd::AsRawFd; - let fd = rustix::fs::memfd_create("rs-essai", rustix::fs::MemfdFlags::CLOEXEC).unwrap(); - let contenu: Vec = (0..=255u8).cycle().take(4096).collect(); - rustix::io::write(&fd, &contenu).unwrap(); - let mut lu = Vec::new(); - lire_memfd(fd.as_raw_fd(), 100, 1000, &mut lu).unwrap(); - assert_eq!(lu, contenu[100..1100]); - assert!(lire_memfd(fd.as_raw_fd(), 4000, 1000, &mut lu).is_err()); + let fd = rustix::fs::memfd_create("rs-test", rustix::fs::MemfdFlags::CLOEXEC).unwrap(); + let content: Vec = (0..=255u8).cycle().take(4096).collect(); + rustix::io::write(&fd, &content).unwrap(); + let mut read = Vec::new(); + read_memfd(fd.as_raw_fd(), 100, 1000, &mut read).unwrap(); + assert_eq!(read, content[100..1100]); + assert!(read_memfd(fd.as_raw_fd(), 4000, 1000, &mut read).is_err()); } #[test] fn format_parameters_serialize() { for size in [None, Some((1280, 800))] { - let octets = parametres_format(PipeWireOptions { fps: 30, size }); - assert!(!octets.is_empty()); - assert!(spa::pod::Pod::from_bytes(&octets).is_some()); + let bytes = format_parameters(PipeWireOptions { fps: 30, size }); + assert!(!bytes.is_empty()); + assert!(spa::pod::Pod::from_bytes(&bytes).is_some()); } } #[test] fn a_revocation_ends_the_capture() { - let partage = Arc::new(Partage { - etat: Mutex::new(Etat::default()), + let shared = Arc::new(Shared { + state: Mutex::new(State::default()), signal: Condvar::new(), }); - Revocation(partage.clone()).revoquer(CaptureError::SourceGone); - assert_eq!(partage.lock().fin, Some(CaptureError::SourceGone)); - // La première raison reste: une seconde fin ne la remplace pas. - Revocation(partage.clone()).revoquer(CaptureError::PermissionDenied); - assert_eq!(partage.lock().fin, Some(CaptureError::SourceGone)); + Revocation(shared.clone()).revoke(CaptureError::SourceGone); + assert_eq!(shared.lock().end, Some(CaptureError::SourceGone)); + // The first reason stays: a second end does not replace it. + Revocation(shared.clone()).revoke(CaptureError::PermissionDenied); + assert_eq!(shared.lock().end, Some(CaptureError::SourceGone)); } } diff --git a/crates/rs-capture/src/pixels.rs b/crates/rs-capture/src/pixels.rs index 2c23449..7d81bc9 100644 --- a/crates/rs-capture/src/pixels.rs +++ b/crates/rs-capture/src/pixels.rs @@ -1,27 +1,26 @@ -//! Formats de pixels rendus par les systèmes, et leur conversion en BGRA. +//! Pixel formats delivered by the systems, and their conversion to BGRA. //! -//! Le reste du pipeline ne connaît que le BGRA 8 bits. Chaque chemin de capture -//! déclare donc le format qu'il reçoit au lieu de le supposer: un RGBx traité -//! comme du BGRx échange le rouge et le bleu sans que rien ne le signale, et un -//! format 10 bits lu comme du 8 bits donne des couleurs fausses. Seuls les -//! formats 8 bits à quatre octets par pixel sont acceptés; les autres ne sont -//! jamais négociés. +//! The rest of the pipeline only knows 8-bit BGRA. Each capture path therefore +//! declares the format it receives instead of assuming it: RGBx treated as +//! BGRx swaps red and blue without anything flagging it, and a 10-bit format +//! read as 8-bit gives wrong colors. Only 8-bit formats with four bytes per +//! pixel are accepted; the others are never negotiated. use crate::frame::CaptureError; -/// Ordre des octets en mémoire, du premier au dernier. +/// Byte order in memory, from first to last. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PixelFormat { Bgra, - /// BGR plus un octet de remplissage, sans signification. + /// BGR plus one meaningless padding byte. Bgrx, Rgba, Rgbx, } impl PixelFormat { - /// Un octet de remplissage n'est pas une transparence: il peut valoir - /// n'importe quoi, et doit être remplacé par une opacité pleine. + /// A padding byte is not transparency: it can hold anything, and must be + /// replaced with full opacity. fn has_padding(self) -> bool { matches!(self, Self::Bgrx | Self::Rgbx) } @@ -31,11 +30,11 @@ impl PixelFormat { } } -/// Convertit une image brute en BGRA serré (sans remplissage de fin de ligne). +/// Converts a raw image to tightly packed BGRA (no end-of-line padding). /// -/// `stride` est la longueur d'une ligne en octets, telle que rendue par la -/// source: elle dépasse souvent `width * 4` pour des raisons d'alignement. -/// `out` est réutilisé d'une image à l'autre. +/// `stride` is the length of a line in bytes, as delivered by the source: it +/// often exceeds `width * 4` for alignment reasons. `out` is reused from one +/// image to the next. pub fn to_bgra( format: PixelFormat, src: &[u8], @@ -47,13 +46,13 @@ pub fn to_bgra( let row_bytes = width * 4; if stride < row_bytes { return Err(CaptureError::Internal(format!( - "ligne de {stride} octets pour {width} pixels" + "line of {stride} bytes for {width} pixels" ))); } let needed = stride * height.saturating_sub(1) + row_bytes; if height > 0 && src.len() < needed { return Err(CaptureError::Internal(format!( - "image tronquée: {} octets pour {needed} attendus", + "truncated image: {} bytes, {needed} expected", src.len() ))); } @@ -79,13 +78,12 @@ pub fn to_bgra( Ok(()) } -/// Recadre ou complète une image BGRA pour qu'elle ait exactement la taille -/// attendue par l'encodeur. +/// Crops or pads a BGRA image so it has exactly the size the encoder expects. /// -/// L'encodeur est configuré une fois, à la taille de la première image. Si la -/// source change de taille en cours de route (résolution modifiée, fenêtre -/// redimensionnée), on garde le coin haut gauche et on complète en noir plutôt -/// que de couper la session. +/// The encoder is configured once, at the size of the first image. If the +/// source changes size along the way (resolution changed, window resized), we +/// keep the top-left corner and pad with black rather than cutting the +/// session. pub fn fit(src: &[u8], width: usize, height: usize, target: (usize, usize), out: &mut Vec) { let (tw, th) = target; out.clear(); @@ -96,14 +94,14 @@ pub fn fit(src: &[u8], width: usize, height: usize, target: (usize, usize), out: let to = row * tw * 4; out[to..to + copy_w].copy_from_slice(&src[from..from + copy_w]); } - // Le noir complété doit être opaque, sinon un encodeur qui tiendrait compte - // de l'alpha y verrait autre chose que du noir. + // The padding black must be opaque, otherwise an encoder that took alpha + // into account would see something other than black. for px in out.as_chunks_mut::<4>().0 { px[3] = 255; } } -/// Arrondit à la dimension paire inférieure: VP8 et I420 l'exigent. +/// Rounds down to the even dimension below: VP8 and I420 require it. pub fn even(size: (u32, u32)) -> (u32, u32) { ((size.0 & !1).max(2), (size.1 & !1).max(2)) } @@ -112,9 +110,9 @@ pub fn even(size: (u32, u32)) -> (u32, u32) { mod tests { use super::*; - /// Mire de quatre pixels connus, rouge, vert, bleu, blanc, écrite dans le - /// format demandé, avec `pad` octets de remplissage en fin de ligne. - fn mire(format: PixelFormat, pad: usize) -> (Vec, usize) { + /// Test pattern of four known pixels, red, green, blue, white, written in + /// the requested format, with `pad` padding bytes at the end of each line. + fn test_pattern(format: PixelFormat, pad: usize) -> (Vec, usize) { let rgb = [[255u8, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 255]]; let stride = 2 * 4 + pad; let mut data = Vec::new(); @@ -123,7 +121,7 @@ mod tests { let [r, g, b] = rgb[row * 2 + col]; let px = match format { PixelFormat::Bgra => [b, g, r, 255], - // Remplissage volontairement non nul: il ne doit pas fuir. + // Deliberately non-zero padding: it must not leak. PixelFormat::Bgrx => [b, g, r, 7], PixelFormat::Rgba => [r, g, b, 255], PixelFormat::Rgbx => [r, g, b, 7], @@ -135,11 +133,11 @@ mod tests { (data, stride) } - const ATTENDU: [u8; 16] = [ - 0, 0, 255, 255, // rouge - 0, 255, 0, 255, // vert - 255, 0, 0, 255, // bleu - 255, 255, 255, 255, // blanc + const EXPECTED: [u8; 16] = [ + 0, 0, 255, 255, // red + 0, 255, 0, 255, // green + 255, 0, 0, 255, // blue + 255, 255, 255, 255, // white ]; #[test] @@ -150,28 +148,28 @@ mod tests { PixelFormat::Rgba, PixelFormat::Rgbx, ] { - let (data, stride) = mire(format, 0); + let (data, stride) = test_pattern(format, 0); let mut out = Vec::new(); to_bgra(format, &data, stride, 2, 2, &mut out).unwrap(); - assert_eq!(out, ATTENDU, "{format:?}"); + assert_eq!(out, EXPECTED, "{format:?}"); } } #[test] fn line_padding_is_dropped() { - // Les compositeurs alignent les lignes (souvent sur 64 ou 256 octets): - // un pas ignoré décale chaque ligne et donne une image penchée. + // Compositors align lines (often on 64 or 256 bytes): an ignored stride + // shifts every line and gives a slanted image. for format in [PixelFormat::Bgrx, PixelFormat::Rgba] { - let (data, stride) = mire(format, 24); + let (data, stride) = test_pattern(format, 24); let mut out = Vec::new(); to_bgra(format, &data, stride, 2, 2, &mut out).unwrap(); - assert_eq!(out, ATTENDU, "{format:?}"); + assert_eq!(out, EXPECTED, "{format:?}"); } } #[test] fn a_truncated_image_is_refused() { - let (data, stride) = mire(PixelFormat::Bgra, 0); + let (data, stride) = test_pattern(PixelFormat::Bgra, 0); let mut out = Vec::new(); assert!(to_bgra(PixelFormat::Bgra, &data[..10], stride, 2, 2, &mut out).is_err()); assert!(to_bgra(PixelFormat::Bgra, &data, 4, 2, 2, &mut out).is_err()); @@ -179,25 +177,25 @@ mod tests { #[test] fn the_last_line_needs_no_padding() { - // Certains tampons s'arrêtent juste après le dernier pixel utile. - let (mut data, stride) = mire(PixelFormat::Bgra, 8); + // Some buffers end right after the last useful pixel. + let (mut data, stride) = test_pattern(PixelFormat::Bgra, 8); data.truncate(stride + 8); let mut out = Vec::new(); to_bgra(PixelFormat::Bgra, &data, stride, 2, 2, &mut out).unwrap(); - assert_eq!(out, ATTENDU); + assert_eq!(out, EXPECTED); } #[test] fn fit_crops_and_pads_with_opaque_black() { let mut out = Vec::new(); - fit(&ATTENDU, 2, 2, (1, 1), &mut out); + fit(&EXPECTED, 2, 2, (1, 1), &mut out); assert_eq!(out, [0, 0, 255, 255]); - fit(&ATTENDU, 2, 2, (3, 2), &mut out); + fit(&EXPECTED, 2, 2, (3, 2), &mut out); assert_eq!(out.len(), 3 * 2 * 4); - assert_eq!(&out[0..8], &ATTENDU[0..8]); - assert_eq!(&out[8..12], &[0, 0, 0, 255], "colonne ajoutée en noir"); - assert_eq!(&out[12..20], &ATTENDU[8..16]); + assert_eq!(&out[0..8], &EXPECTED[0..8]); + assert_eq!(&out[8..12], &[0, 0, 0, 255], "added column is black"); + assert_eq!(&out[12..20], &EXPECTED[8..16]); } #[test] diff --git a/crates/rs-capture/src/source.rs b/crates/rs-capture/src/source.rs index ecaf8da..ba7ddf4 100644 --- a/crates/rs-capture/src/source.rs +++ b/crates/rs-capture/src/source.rs @@ -1,26 +1,26 @@ -//! Le trait de capture, et ce qu'une source déclare d'elle-même. +//! The capture trait, and what a source declares about itself. use rs_proto::{SourceId, SourceInfo, SourceKind}; use crate::frame::{CaptureError, CapturedFrame}; -/// Une implémentation par système: DXGI ou WGC sous Windows, ScreenCaptureKit -/// sous macOS, portail PipeWire ou X11 sous Linux. +/// One implementation per system: DXGI or WGC on Windows, ScreenCaptureKit on +/// macOS, the PipeWire portal or X11 on Linux. pub trait ScreenCapturer: Send { - /// Sources disponibles à cet instant. Peut changer entre deux appels. + /// Sources available right now. May change between two calls. fn sources(&mut self) -> Result, CaptureError>; - /// Démarre la capture d'une source. Échoue si elle a disparu entre le - /// listing et l'appel. + /// Starts capturing a source. Fails if it disappeared between the listing + /// and the call. fn start(&mut self, source: &SourceId) -> Result<(), CaptureError>; - /// Frame suivante. Bloque jusqu'à la cadence demandée. + /// Next frame. Blocks until the requested cadence. fn next_frame(&mut self) -> Result; fn stop(&mut self); } -/// Décrit une source en annonçant honnêtement ce qui est capturable. +/// Describes a source, stating honestly what can be captured. pub fn describe( id: impl Into, kind: SourceKind, diff --git a/crates/rs-capture/src/synthetic.rs b/crates/rs-capture/src/synthetic.rs index 1340ca7..92c1bad 100644 --- a/crates/rs-capture/src/synthetic.rs +++ b/crates/rs-capture/src/synthetic.rs @@ -1,10 +1,9 @@ -//! Mire synthétique: une fausse source de capture, pour tester tout le pipeline -//! sans écran ni permission système. +//! Synthetic test pattern: a fake capture source, to test the whole pipeline +//! without a screen or a system permission. //! -//! Elle dessine trois bandes (rouge, vert, bleu) et un carré blanc qui se -//! déplace. C'est ce qui permet de vérifier dans un navigateur que les couleurs -//! arrivent au bon endroit et que l'image bouge, au lieu de constater -//! simplement que des octets circulent. +//! It draws three bands (red, green, blue) and a moving white square. This is +//! what lets you check in a browser that the colors land in the right place +//! and that the image moves, instead of merely seeing bytes flow. use std::time::{Duration, Instant}; @@ -24,9 +23,9 @@ pub struct SyntheticCapturer { sequence: u64, next_at: Option, started: bool, - /// Image courante, réutilisée d'une frame à l'autre. + /// Current image, reused from one frame to the next. bgra: Vec, - /// Dernier carré dessiné, à effacer avant de dessiner le suivant. + /// Last square drawn, to erase before drawing the next one. last_square: Option<(usize, usize)>, } @@ -50,9 +49,9 @@ impl SyntheticCapturer { Self::new(1280, 720, fps) } - /// Une image de la mire, tout de suite: la première image après le - /// démarrage n'attend pas la cadence. Sert aux vignettes. - pub fn premiere_image(&mut self) -> Result { + /// One frame of the pattern, right away: the first frame after start does + /// not wait for the cadence. Used for thumbnails. + pub fn first_frame(&mut self) -> Result { self.start(&SourceId(SOURCE_ID.into()))?; self.next_frame() } @@ -73,7 +72,7 @@ impl SyntheticCapturer { for row in y..(y + size).min(self.height) { for col in x..(x + size).min(self.width) { let index = (row * self.width + col) * 4; - // Le rectangle blanc est effacé en repeignant la bande d'origine. + // The white rectangle is erased by repainting the original band. let value = if color == [255, 255, 255, 255] { color } else { @@ -99,13 +98,13 @@ impl SyntheticCapturer { fn band_color(col: usize, third: usize) -> [u8; 4] { if col < third { - // BGRA: rouge + // BGRA: red [0, 0, 255, 255] } else if col < third * 2 { - // vert + // green [0, 255, 0, 255] } else { - // bleu + // blue [255, 0, 0, 255] } } @@ -115,7 +114,7 @@ impl ScreenCapturer for SyntheticCapturer { Ok(vec![describe( SOURCE_ID, SourceKind::Screen, - "Mire synthétique", + "Synthetic test pattern", self.width as u32, self.height as u32, true, @@ -138,11 +137,11 @@ impl ScreenCapturer for SyntheticCapturer { fn next_frame(&mut self) -> Result { if !self.started { - return Err(CaptureError::Internal("capture non démarrée".into())); + return Err(CaptureError::Internal("capture not started".into())); } - // Cadence régulière: on attend l'échéance au lieu de produire au plus - // vite, sinon le pipeline avale le CPU et les horodatages dérivent. + // Regular cadence: wait for the deadline instead of producing as fast + // as possible, otherwise the pipeline eats the CPU and timestamps drift. let now = Instant::now(); let due = self.next_at.unwrap_or(now); if due > now { @@ -183,18 +182,18 @@ mod tests { let index = (row * width + col) * 4; frame.bgra[index..index + 4].to_vec() }; - let left = at(40); // bande rouge - let middle = at(150); // bande verte - let right = at(260); // bande bleue + let left = at(40); // red band + let middle = at(150); // green band + let right = at(260); // blue band (left[2], middle[1], right[0]) } #[test] fn bands_have_the_expected_colors() { let (red, green, blue) = frame_colors(); - assert_eq!(red, 255, "canal rouge de la bande gauche"); - assert_eq!(green, 255, "canal vert de la bande centrale"); - assert_eq!(blue, 255, "canal bleu de la bande droite"); + assert_eq!(red, 255, "red channel of the left band"); + assert_eq!(green, 255, "green channel of the middle band"); + assert_eq!(blue, 255, "blue channel of the right band"); } #[test] @@ -205,7 +204,7 @@ mod tests { let second = capturer.next_frame().unwrap(); assert_eq!(first.sequence, 0); assert_eq!(second.sequence, 1); - assert_ne!(first.bgra, second.bgra, "le carré doit avoir bougé"); + assert_ne!(first.bgra, second.bgra, "the square must have moved"); } #[test] @@ -219,7 +218,7 @@ mod tests { fn unknown_source_is_refused() { let mut capturer = SyntheticCapturer::new(64, 64, 30); assert_eq!( - capturer.start(&SourceId("autre".into())).unwrap_err(), + capturer.start(&SourceId("other".into())).unwrap_err(), CaptureError::SourceGone ); } diff --git a/crates/rs-capture/src/x11.rs b/crates/rs-capture/src/x11.rs index d7a7ccc..6c97b35 100644 --- a/crates/rs-capture/src/x11.rs +++ b/crates/rs-capture/src/x11.rs @@ -1,21 +1,20 @@ -//! Capture X11: l'écran entier ou une fenêtre précise. +//! X11 capture: the whole screen or one specific window. //! -//! **Repli**, pas la cible: le produit vise Wayland (ADR 0009). Mais sous X11 la -//! capture est directe, sans consentement ni portail, et c'est le seul système -//! où l'on peut nommer une fenêtre précise de façon fiable. +//! **Fallback**, not the target: the product aims at Wayland (ADR 0009). But +//! under X11 capture is direct, with no consent and no portal, and it is the +//! only system where one specific window can be named reliably. //! -//! - l'écran se lit sur la fenêtre racine, un moniteur sur le rectangle que -//! RandR lui donne dans cette racine (#16); -//! - une fenêtre se lit après redirection par l'extension Composite: son -//! contenu est alors gardé hors écran, même recouverte par une autre; -//! - MIT-SHM, quand le serveur l'offre, évite de faire transiter chaque image -//! par le socket X. Le segment est un memfd transmis au serveur -//! (`ShmAttachFd`), relu par `pread`: pas de `mmap`, donc pas de code -//! `unsafe`. +//! - the screen is read from the root window, a monitor from the rectangle +//! RandR gives it inside that root (#16); +//! - a window is read after redirection through the Composite extension: its +//! content is then kept off screen, even when another window covers it; +//! - MIT-SHM, when the server offers it, avoids sending every image through +//! the X socket. The segment is a memfd handed to the server +//! (`ShmAttachFd`), read back with `pread`: no `mmap`, so no `unsafe` code. //! -//! Les titres de fenêtres apparaissent dans [`ScreenCapturer::sources`], pour -//! l'interface. Ils ne sont **jamais** journalisés: un titre dit ce que -//! l'utilisateur fait, et les diagnostics ne doivent pas le contenir (ADR 0008). +//! Window titles appear in [`ScreenCapturer::sources`], for the interface. +//! They are **never** logged: a title tells what the user is doing, and +//! diagnostics must not contain it (ADR 0008). use std::os::fd::OwnedFd; use std::time::Instant; @@ -33,165 +32,167 @@ use crate::frame::{CaptureError, CapturedFrame}; use crate::pixels::{self, PixelFormat}; use crate::source::{ScreenCapturer, describe}; -const ECRAN: &str = "x11:ecran"; -const PREFIXE_FENETRE: &str = "x11:fenetre:"; -const PREFIXE_MONITEUR: &str = "x11:moniteur:"; -/// Côté en pixels sous lequel une fenêtre n'est pas proposée. -const MINIMUM_FENETRE: u32 = 48; +// The identifier values are kept as they were: they travel to the interface +// and may be remembered between two runs. +const SCREEN: &str = "x11:ecran"; +const WINDOW_PREFIX: &str = "x11:fenetre:"; +const MONITOR_PREFIX: &str = "x11:moniteur:"; +/// Side in pixels below which a window is not offered. +const MIN_WINDOW_SIZE: u32 = 48; -/// Un moniteur vu par RandR: un rectangle de la fenêtre racine, nommé par sa -/// sortie (`HDMI-1`). Le nom survit à un débranchement suivi d'un -/// rebranchement, pas l'indice. +/// A monitor as seen by RandR: a rectangle of the root window, named after its +/// output (`HDMI-1`). The name survives an unplug followed by a replug, the +/// index does not. #[derive(Debug, Clone, PartialEq, Eq)] -struct Moniteur { - nom: String, - principal: bool, +struct Monitor { + name: String, + primary: bool, x: i16, y: i16, - largeur: u16, - hauteur: u16, + width: u16, + height: u16, } -enum Cible { - Ecran, - Fenetre(Window), - Moniteur { - nom: String, - /// Rectangle lu à la dernière vérification. +enum Target { + Screen, + Window(Window), + Monitor { + name: String, + /// Rectangle read at the last check. rectangle: (i16, i16, u16, u16), - /// Images avant de revérifier la géométrie: une requête RandR par image - /// coûterait un aller-retour de plus, pour un changement rare. - verification: u32, + /// Frames left before checking the geometry again: one RandR request + /// per frame would cost one more round trip, for a rare change. + countdown: u32, }, } -/// Images entre deux vérifications de la géométrie d'un moniteur, une seconde -/// à 30 i/s. -const VERIFICATION_MONITEUR: u32 = 30; +/// Frames between two checks of a monitor's geometry, one second at 30 fps. +const MONITOR_CHECK_INTERVAL: u32 = 30; -/// Segment de mémoire partagée avec le serveur X. +/// Memory segment shared with the X server. struct Segment { id: shm::Seg, fd: OwnedFd, - taille: usize, + size: usize, } pub struct X11Capturer { conn: RustConnection, - racine: Window, + root: Window, format: PixelFormat, - cible: Option, - shm_disponible: bool, + target: Option, + shm_available: bool, segment: Option, cadence: Cadence, sequence: u64, - brut: Vec, + raw: Vec, bgra: Vec, - /// Taille de l'image contenue dans `bgra`. - taille_bgra: (u32, u32), - ajustee: Vec, + /// Size of the image held in `bgra`. + bgra_size: (u32, u32), + fitted: Vec, } -fn interne(contexte: &str, e: impl std::fmt::Display) -> CaptureError { - CaptureError::Internal(format!("{contexte}: {e}")) +fn internal(context: &str, e: impl std::fmt::Display) -> CaptureError { + CaptureError::Internal(format!("{context}: {e}")) } impl X11Capturer { - /// Se connecte au serveur X désigné par `DISPLAY` (ou celui donné). - pub fn connecter(display: Option<&str>, fps: u8) -> Result { - let (conn, numero) = x11rb::connect(display) - .map_err(|e| CaptureError::Unsupported(format!("serveur X injoignable: {e}")))?; + /// Connects to the X server named by `DISPLAY` (or the given one). + pub fn connect(display: Option<&str>, fps: u8) -> Result { + let (conn, screen_num) = x11rb::connect(display) + .map_err(|e| CaptureError::Unsupported(format!("X server unreachable: {e}")))?; let setup = conn.setup(); - let ecran = setup + let screen = setup .roots - .get(numero) - .ok_or_else(|| CaptureError::Internal("écran X introuvable".into()))?; - let racine = ecran.root; - let format = format_pixels(setup, ecran)?; + .get(screen_num) + .ok_or_else(|| CaptureError::Internal("X screen not found".into()))?; + let root = screen.root; + let format = pixel_format(setup, screen)?; - let shm_disponible = conn + let shm_available = conn .shm_query_version() .ok() .and_then(|c| c.reply().ok()) - // ShmAttachFd est apparu en 1.2. + // ShmAttachFd appeared in 1.2. .is_some_and(|v| (v.major_version, v.minor_version) >= (1, 2)); - tracing::info!(shm = shm_disponible, format = ?format, "serveur X connecté"); + tracing::info!(shm = shm_available, format = ?format, "X server connected"); Ok(Self { conn, - racine, + root, format, - cible: None, - shm_disponible, + target: None, + shm_available, segment: None, cadence: Cadence::new(fps), sequence: 0, - brut: Vec::new(), + raw: Vec::new(), bgra: Vec::new(), - taille_bgra: (0, 0), - ajustee: Vec::new(), + bgra_size: (0, 0), + fitted: Vec::new(), }) } - /// La sortie du moniteur principal (`HDMI-1`), s'il y en a plusieurs. - pub fn moniteur_principal(&self) -> Option { - self.moniteurs() + /// The output of the primary monitor (`HDMI-1`), if there are several. + pub fn primary_monitor(&self) -> Option { + self.monitors() .into_iter() - .find(|m| m.principal) - .map(|m| m.nom) + .find(|m| m.primary) + .map(|m| m.name) } - pub fn utilise_shm(&self) -> bool { - self.shm_disponible + pub fn uses_shm(&self) -> bool { + self.shm_available } - fn atome(&self, nom: &str) -> Result { + fn atom(&self, name: &str) -> Result { Ok(self .conn - .intern_atom(false, nom.as_bytes()) - .map_err(|e| interne("atome", e))? + .intern_atom(false, name.as_bytes()) + .map_err(|e| internal("atom", e))? .reply() - .map_err(|e| interne("atome", e))? + .map_err(|e| internal("atom", e))? .atom) } - fn taille(&self, fenetre: Window) -> Result<(u32, u32), CaptureError> { + fn size(&self, window: Window) -> Result<(u32, u32), CaptureError> { let geo = self .conn - .get_geometry(fenetre) - .map_err(|e| interne("géométrie", e))? + .get_geometry(window) + .map_err(|e| internal("geometry", e))? .reply() - // Une fenêtre détruite répond BadDrawable: c'est une source perdue, - // pas une panne. + // A destroyed window answers BadDrawable: that is a lost source, + // not a failure. .map_err(|_| CaptureError::SourceGone)?; Ok((geo.width as u32, geo.height as u32)) } - fn titre(&self, fenetre: Window) -> String { - let lire = |propriete: &str, type_: xproto::AtomEnum| -> Option { - let atome = self.atome(propriete).ok()?; - let type_atome = if propriete == "_NET_WM_NAME" { - self.atome("UTF8_STRING").ok()? + fn title(&self, window: Window) -> String { + let read = |property: &str, type_: xproto::AtomEnum| -> Option { + let atom = self.atom(property).ok()?; + let type_atom = if property == "_NET_WM_NAME" { + self.atom("UTF8_STRING").ok()? } else { type_.into() }; - let reponse = self + let reply = self .conn - .get_property(false, fenetre, atome, type_atome, 0, 1024) + .get_property(false, window, atom, type_atom, 0, 1024) .ok()? .reply() .ok()?; - let texte = String::from_utf8_lossy(&reponse.value).into_owned(); - (!texte.is_empty()).then_some(texte) + let text = String::from_utf8_lossy(&reply.value).into_owned(); + (!text.is_empty()).then_some(text) }; - lire("_NET_WM_NAME", xproto::AtomEnum::STRING) - .or_else(|| lire("WM_NAME", xproto::AtomEnum::STRING)) - .unwrap_or_else(|| format!("fenêtre 0x{fenetre:x}")) + read("_NET_WM_NAME", xproto::AtomEnum::STRING) + .or_else(|| read("WM_NAME", xproto::AtomEnum::STRING)) + .unwrap_or_else(|| format!("window 0x{window:x}")) } - /// Les moniteurs actifs selon RandR 1.5, vide si l'extension manque (Xephyr - /// sans `+extension RANDR`, serveur ancien): l'écran entier reste capturable. - fn moniteurs(&self) -> Vec { + /// Active monitors according to RandR 1.5, empty if the extension is + /// missing (Xephyr without `+extension RANDR`, old server): the whole + /// screen stays capturable. + fn monitors(&self) -> Vec { let version = self .conn .randr_query_version(1, 5) @@ -200,54 +201,54 @@ impl X11Capturer { if !version.is_some_and(|v| (v.major_version, v.minor_version) >= (1, 5)) { return Vec::new(); } - let Some(reponse) = self + let Some(reply) = self .conn - .randr_get_monitors(self.racine, true) + .randr_get_monitors(self.root, true) .ok() .and_then(|c| c.reply().ok()) else { return Vec::new(); }; - reponse + reply .monitors .into_iter() .filter(|m| m.width > 0 && m.height > 0) - .map(|m| Moniteur { - nom: self + .map(|m| Monitor { + name: self .conn .get_atom_name(m.name) .ok() .and_then(|c| c.reply().ok()) .map(|r| String::from_utf8_lossy(&r.name).into_owned()) - .unwrap_or_else(|| format!("moniteur-{}", m.name)), - principal: m.primary, + .unwrap_or_else(|| format!("monitor-{}", m.name)), + primary: m.primary, x: m.x, y: m.y, - largeur: m.width, - hauteur: m.height, + width: m.width, + height: m.height, }) .collect() } - /// Les valeurs d'une propriété faite d'atomes (`_NET_WM_STATE`, - /// `_NET_WM_WINDOW_TYPE`), vide si elle manque. - fn atomes(&self, fenetre: Window, propriete: &str) -> Vec { - let Ok(nom) = self.atome(propriete) else { + /// The values of an atom-list property (`_NET_WM_STATE`, + /// `_NET_WM_WINDOW_TYPE`), empty if it is missing. + fn atoms(&self, window: Window, property: &str) -> Vec { + let Ok(name) = self.atom(property) else { return Vec::new(); }; self.conn - .get_property(false, fenetre, nom, xproto::AtomEnum::ATOM, 0, 64) + .get_property(false, window, name, xproto::AtomEnum::ATOM, 0, 64) .ok() .and_then(|c| c.reply().ok()) .and_then(|r| r.value32().map(Iterator::collect)) .unwrap_or_default() } - /// Une fenêtre que personne ne veut partager: le bureau lui-même, une - /// barre des tâches, un menu, une bulle, ou rustscreen (#17). Le type et - /// l'état viennent du gestionnaire de fenêtres (EWMH); le PID, la boîte à - /// outils le pose elle-même (GTK), avec ou sans gestionnaire. - fn sans_interet(&self, fenetre: Window) -> bool { + /// A window nobody wants to share: the desktop itself, a taskbar, a menu, + /// a tooltip, or rustscreen (#17). Type and state come from the window + /// manager (EWMH); the PID is set by the toolkit itself (GTK), with or + /// without a window manager. + fn uninteresting(&self, window: Window) -> bool { const TYPES: [&str; 9] = [ "_NET_WM_WINDOW_TYPE_DESKTOP", "_NET_WM_WINDOW_TYPE_DOCK", @@ -259,25 +260,25 @@ impl X11Capturer { "_NET_WM_WINDOW_TYPE_POPUP_MENU", "_NET_WM_WINDOW_TYPE_TOOLTIP", ]; - let types = self.atomes(fenetre, "_NET_WM_WINDOW_TYPE"); - let ecartes: Vec = TYPES + let types = self.atoms(window, "_NET_WM_WINDOW_TYPE"); + let excluded: Vec = TYPES .iter() - .filter_map(|nom| self.atome(nom).ok()) + .filter_map(|name| self.atom(name).ok()) .collect(); - if types.iter().any(|t| ecartes.contains(t)) { + if types.iter().any(|t| excluded.contains(t)) { return true; } - let etat = self.atomes(fenetre, "_NET_WM_STATE"); + let state = self.atoms(window, "_NET_WM_STATE"); if self - .atome("_NET_WM_STATE_SKIP_TASKBAR") - .is_ok_and(|a| etat.contains(&a)) + .atom("_NET_WM_STATE_SKIP_TASKBAR") + .is_ok_and(|a| state.contains(&a)) { return true; } - // Partager la fenêtre de rustscreen montrerait le QR code et le jeton. - let pid = self.atome("_NET_WM_PID").ok().and_then(|atome| { + // Sharing rustscreen's own window would show the QR code and the token. + let pid = self.atom("_NET_WM_PID").ok().and_then(|atom| { self.conn - .get_property(false, fenetre, atome, xproto::AtomEnum::CARDINAL, 0, 1) + .get_property(false, window, atom, xproto::AtomEnum::CARDINAL, 0, 1) .ok()? .reply() .ok()? @@ -287,204 +288,208 @@ impl X11Capturer { pid == Some(std::process::id()) } - /// Réduite dans la barre des tâches: plus rien à lire tant qu'elle n'est - /// pas restaurée, Composite ne garde pas le contenu d'une fenêtre démappée. - fn reduite(&self, fenetre: Window) -> bool { - let cachee = self - .atome("_NET_WM_STATE_HIDDEN") - .is_ok_and(|a| self.atomes(fenetre, "_NET_WM_STATE").contains(&a)); - let affichee = self + /// Minimized to the taskbar: nothing left to read until it is restored, + /// Composite does not keep the content of an unmapped window. + fn minimized(&self, window: Window) -> bool { + let hidden = self + .atom("_NET_WM_STATE_HIDDEN") + .is_ok_and(|a| self.atoms(window, "_NET_WM_STATE").contains(&a)); + let viewable = self .conn - .get_window_attributes(fenetre) + .get_window_attributes(window) .ok() .and_then(|c| c.reply().ok()) .is_some_and(|a| a.map_state == xproto::MapState::VIEWABLE); - cachee || !affichee + hidden || !viewable } - /// Les fenêtres que le gestionnaire de fenêtres déclare (EWMH), ou, sans - /// gestionnaire, les fenêtres de premier niveau affichées. - fn fenetres(&self) -> Result, CaptureError> { - let liste = self.atome("_NET_CLIENT_LIST")?; - let reponse = self + /// The windows the window manager declares (EWMH), or, without a window + /// manager, the mapped top-level windows. + fn windows(&self) -> Result, CaptureError> { + let list = self.atom("_NET_CLIENT_LIST")?; + let reply = self .conn - .get_property(false, self.racine, liste, xproto::AtomEnum::WINDOW, 0, 4096) - .map_err(|e| interne("liste des fenêtres", e))? + .get_property(false, self.root, list, xproto::AtomEnum::WINDOW, 0, 4096) + .map_err(|e| internal("window list", e))? .reply() - .map_err(|e| interne("liste des fenêtres", e))?; - let declarees: Vec = reponse.value32().map(|v| v.collect()).unwrap_or_default(); - if !declarees.is_empty() { - return Ok(declarees + .map_err(|e| internal("window list", e))?; + let declared: Vec = reply.value32().map(|v| v.collect()).unwrap_or_default(); + if !declared.is_empty() { + return Ok(declared .into_iter() - .filter(|&f| !self.sans_interet(f)) + .filter(|&w| !self.uninteresting(w)) .collect()); } - let arbre = self + let tree = self .conn - .query_tree(self.racine) - .map_err(|e| interne("arbre des fenêtres", e))? + .query_tree(self.root) + .map_err(|e| internal("window tree", e))? .reply() - .map_err(|e| interne("arbre des fenêtres", e))?; - Ok(arbre + .map_err(|e| internal("window tree", e))?; + Ok(tree .children .into_iter() - .filter(|&f| { + .filter(|&w| { self.conn - .get_window_attributes(f) + .get_window_attributes(w) .ok() .and_then(|c| c.reply().ok()) .is_some_and(|a| { a.map_state == xproto::MapState::VIEWABLE && a.class == xproto::WindowClass::INPUT_OUTPUT }) - && !self.sans_interet(f) + && !self.uninteresting(w) }) .collect()) } fn drawable(&self) -> Option { - match self.cible.as_ref()? { - Cible::Ecran | Cible::Moniteur { .. } => Some(self.racine), - Cible::Fenetre(f) => Some(*f), + match self.target.as_ref()? { + Target::Screen | Target::Monitor { .. } => Some(self.root), + Target::Window(w) => Some(*w), } } - /// Le rectangle à lire dans `drawable`: tout, ou le moniteur visé. Un - /// moniteur qui n'existe plus est une source perdue (écran débranché). + /// The rectangle to read in `drawable`: all of it, or the targeted + /// monitor. A monitor that no longer exists is a lost source (screen + /// unplugged). fn rectangle(&mut self, drawable: Window) -> Result<(i16, i16, u32, u32), CaptureError> { - let a_verifier = match &mut self.cible { - Some(Cible::Moniteur { verification, .. }) => { - *verification = verification.saturating_sub(1); - *verification == 0 + let must_check = match &mut self.target { + Some(Target::Monitor { countdown, .. }) => { + *countdown = countdown.saturating_sub(1); + *countdown == 0 } _ => { - let (w, h) = self.taille(drawable)?; + let (w, h) = self.size(drawable)?; return Ok((0, 0, w, h)); } }; - if a_verifier { - let moniteurs = self.moniteurs(); - if let Some(Cible::Moniteur { - nom, + if must_check { + let monitors = self.monitors(); + if let Some(Target::Monitor { + name, rectangle, - verification, - }) = &mut self.cible + countdown, + }) = &mut self.target { - let actuel = moniteurs + let current = monitors .iter() - .find(|m| m.nom == *nom) + .find(|m| m.name == *name) .ok_or(CaptureError::SourceGone)?; - *rectangle = (actuel.x, actuel.y, actuel.largeur, actuel.hauteur); - *verification = VERIFICATION_MONITEUR; + *rectangle = (current.x, current.y, current.width, current.height); + *countdown = MONITOR_CHECK_INTERVAL; } } - match &self.cible { - Some(Cible::Moniteur { rectangle, .. }) => { + match &self.target { + Some(Target::Monitor { rectangle, .. }) => { let (x, y, w, h) = *rectangle; Ok((x, y, w as u32, h as u32)) } - _ => Err(CaptureError::Internal("capture non démarrée".into())), + _ => Err(CaptureError::Internal("capture not started".into())), } } - /// Prépare (ou agrandit) le segment partagé pour une image de `octets`. - fn segment(&mut self, octets: usize) -> Result<&Segment, CaptureError> { - let trop_petit = self.segment.as_ref().is_none_or(|s| s.taille < octets); - if trop_petit { - if let Some(ancien) = self.segment.take() { - let _ = self.conn.shm_detach(ancien.id); + /// Prepares (or grows) the shared segment for an image of `bytes`. + fn segment(&mut self, bytes: usize) -> Result<&Segment, CaptureError> { + let too_small = self.segment.as_ref().is_none_or(|s| s.size < bytes); + if too_small { + if let Some(old) = self.segment.take() { + let _ = self.conn.shm_detach(old.id); } let fd = rustix::fs::memfd_create("rustscreen-x11", rustix::fs::MemfdFlags::CLOEXEC) - .map_err(|e| interne("memfd", e))?; - rustix::fs::ftruncate(&fd, octets as u64).map_err(|e| interne("memfd", e))?; - let id = self.conn.generate_id().map_err(|e| interne("segment", e))?; - let copie = fd.try_clone().map_err(|e| interne("segment", e))?; - // Lecture seule « false »: c'est le serveur qui écrit l'image dans - // le segment. En lecture seule, ShmGetImage répond BadAccess. + .map_err(|e| internal("memfd", e))?; + rustix::fs::ftruncate(&fd, bytes as u64).map_err(|e| internal("memfd", e))?; + let id = self + .conn + .generate_id() + .map_err(|e| internal("segment", e))?; + let copy = fd.try_clone().map_err(|e| internal("segment", e))?; + // Read-only "false": the server writes the image into the + // segment. Read-only, ShmGetImage answers BadAccess. self.conn - .shm_attach_fd(id, copie, false) - .map_err(|e| interne("segment", e))? + .shm_attach_fd(id, copy, false) + .map_err(|e| internal("segment", e))? .check() - .map_err(|e| interne("segment", e))?; + .map_err(|e| internal("segment", e))?; self.segment = Some(Segment { id, fd, - taille: octets, + size: bytes, }); } self.segment .as_ref() - .ok_or_else(|| CaptureError::Internal("segment absent".into())) + .ok_or_else(|| CaptureError::Internal("missing segment".into())) } - /// Lit l'image courante dans `self.brut`. Rend `false` si le serveur la - /// refuse pour un motif passager (fenêtre réduite, non affichée). - fn lire( + /// Reads the current image into `self.raw`. Returns `false` if the server + /// refuses it for a transient reason (window minimized, not mapped). + fn read( &mut self, - cible: Window, + target: Window, (x, y): (i16, i16), w: u32, h: u32, ) -> Result { - let octets = w as usize * h as usize * 4; - if self.shm_disponible { + let bytes = w as usize * h as usize * 4; + if self.shm_available { let format = ImageFormat::Z_PIXMAP.into(); - let id = self.segment(octets)?.id; - let reponse = self + let id = self.segment(bytes)?.id; + let reply = self .conn - .shm_get_image(cible, x, y, w as u16, h as u16, !0, format, id, 0) - .map_err(|e| interne("ShmGetImage", e))? + .shm_get_image(target, x, y, w as u16, h as u16, !0, format, id, 0) + .map_err(|e| internal("ShmGetImage", e))? .reply(); - if reponse.is_err() { + if reply.is_err() { return Ok(false); } let segment = self .segment .as_ref() - .ok_or_else(|| CaptureError::Internal("segment absent".into()))?; - self.brut.resize(octets, 0); - let mut lus = 0; - while lus < octets { - let n = rustix::io::pread(&segment.fd, &mut self.brut[lus..], lus as u64) - .map_err(|e| interne("lecture du segment", e))?; + .ok_or_else(|| CaptureError::Internal("missing segment".into()))?; + self.raw.resize(bytes, 0); + let mut read = 0; + while read < bytes { + let n = rustix::io::pread(&segment.fd, &mut self.raw[read..], read as u64) + .map_err(|e| internal("segment read", e))?; if n == 0 { break; } - lus += n; + read += n; } - return Ok(lus == octets); + return Ok(read == bytes); } - let reponse = self + let reply = self .conn - .get_image(ImageFormat::Z_PIXMAP, cible, x, y, w as u16, h as u16, !0) - .map_err(|e| interne("GetImage", e))? + .get_image(ImageFormat::Z_PIXMAP, target, x, y, w as u16, h as u16, !0) + .map_err(|e| internal("GetImage", e))? .reply(); - match reponse { + match reply { Ok(image) => { - self.brut = image.data; - Ok(self.brut.len() >= octets) + self.raw = image.data; + Ok(self.raw.len() >= bytes) } Err(_) => Ok(false), } } } -/// Le format des pixels de l'écran, déduit du serveur au lieu d'être supposé. -fn format_pixels( +/// The screen's pixel format, derived from the server instead of assumed. +fn pixel_format( setup: &xproto::Setup, - ecran: &xproto::Screen, + screen: &xproto::Screen, ) -> Result { let bpp = setup .pixmap_formats .iter() - .find(|f| f.depth == ecran.root_depth) + .find(|f| f.depth == screen.root_depth) .map(|f| f.bits_per_pixel); - let visuel = ecran + let visual = screen .allowed_depths .iter() .flat_map(|d| d.visuals.iter()) - .find(|v| v.visual_id == ecran.root_visual); - match (bpp, visuel, setup.image_byte_order) { + .find(|v| v.visual_id == screen.root_visual); + match (bpp, visual, setup.image_byte_order) { (Some(32), Some(v), ImageOrder::LSB_FIRST) if v.red_mask == 0x00ff_0000 && v.blue_mask == 0x0000_00ff => { @@ -495,116 +500,123 @@ fn format_pixels( { Ok(PixelFormat::Rgbx) } - // Profondeur 16 bits, 30 bits, ordre big-endian: plutôt refuser que - // livrer des couleurs fausses. - (bpp, _, ordre) => Err(CaptureError::Unsupported(format!( - "format d'écran X non géré: profondeur {}, {bpp:?} bits par pixel, ordre {ordre:?}", - ecran.root_depth + // 16-bit depth, 30-bit, big-endian order: better to refuse than to + // deliver wrong colors. + (bpp, _, order) => Err(CaptureError::Unsupported(format!( + "unsupported X screen format: depth {}, {bpp:?} bits per pixel, order {order:?}", + screen.root_depth ))), } } impl ScreenCapturer for X11Capturer { fn sources(&mut self) -> Result, CaptureError> { - let (w, h) = self.taille(self.racine)?; - let moniteurs = self.moniteurs(); - // Un seul moniteur: c'est l'écran entier, inutile de le proposer deux - // fois. Plusieurs: chacun, puis l'ensemble. + let (w, h) = self.size(self.root)?; + let monitors = self.monitors(); + // A single monitor is the whole screen, no point offering it twice. + // Several: each one, then all of them together. let mut sources = Vec::new(); - if moniteurs.len() > 1 { - let mut tries = moniteurs; - tries.sort_by_key(|m| (!m.principal, m.x, m.y)); - for m in tries { - let nom = if m.principal { - format!("{} (principal)", m.nom) + if monitors.len() > 1 { + let mut sorted = monitors; + sorted.sort_by_key(|m| (!m.primary, m.x, m.y)); + for m in sorted { + let name = if m.primary { + format!("{} (primary)", m.name) } else { - m.nom.clone() + m.name.clone() }; sources.push(describe( - format!("{PREFIXE_MONITEUR}{}", m.nom), + format!("{MONITOR_PREFIX}{}", m.name), SourceKind::Screen, - nom, - m.largeur as u32, - m.hauteur as u32, + name, + m.width as u32, + m.height as u32, true, )); } sources.push(describe( - ECRAN, + SCREEN, SourceKind::Screen, - "Tous les écrans", + "All screens", w, h, true, )); } else { - sources.push(describe(ECRAN, SourceKind::Screen, "Écran X11", w, h, true)); - } - for fenetre in self.fenetres()? { - // Une fenêtre peut disparaître entre la liste et la géométrie. - let Ok((w, h)) = self.taille(fenetre) else { - continue; - }; - // Une poignée de pixels n'est pas une application. - if w < MINIMUM_FENETRE || h < MINIMUM_FENETRE { - continue; - } - // Réduite: listée, pour que l'utilisateur la trouve et sache - // pourquoi elle n'est pas proposée, mais pas disponible. sources.push(describe( - format!("{PREFIXE_FENETRE}0x{fenetre:x}"), - SourceKind::Window, - self.titre(fenetre), + SCREEN, + SourceKind::Screen, + "X11 screen", w, h, - !self.reduite(fenetre), + true, + )); + } + for window in self.windows()? { + // A window can disappear between the list and the geometry. + let Ok((w, h)) = self.size(window) else { + continue; + }; + // A handful of pixels is not an application. + if w < MIN_WINDOW_SIZE || h < MIN_WINDOW_SIZE { + continue; + } + // Minimized: listed, so the user finds it and knows why it is not + // offered, but not available. + sources.push(describe( + format!("{WINDOW_PREFIX}0x{window:x}"), + SourceKind::Window, + self.title(window), + w, + h, + !self.minimized(window), )); } Ok(sources) } fn start(&mut self, source: &SourceId) -> Result<(), CaptureError> { - let cible = if source.0 == ECRAN { - Cible::Ecran - } else if let Some(hex) = source.0.strip_prefix(PREFIXE_FENETRE) { - let fenetre = u32::from_str_radix(hex.trim_start_matches("0x"), 16) + let target = if source.0 == SCREEN { + Target::Screen + } else if let Some(hex) = source.0.strip_prefix(WINDOW_PREFIX) { + let window = u32::from_str_radix(hex.trim_start_matches("0x"), 16) .map_err(|_| CaptureError::SourceGone)?; - self.taille(fenetre)?; - if self.reduite(fenetre) { - return Err(CaptureError::Indisponible( - "la fenêtre est réduite: la restaurer pour la partager".into(), + self.size(window)?; + if self.minimized(window) { + return Err(CaptureError::Unavailable( + "the window is minimized: restore it to share it".into(), )); } - // Sans redirection, une fenêtre recouverte se lit avec le contenu - // de celle qui la recouvre. Automatic: le serveur continue de la - // composer à l'écran, on lit simplement sa copie. + // Without redirection, a covered window reads with the content of + // the one covering it. Automatic: the server keeps compositing it + // on screen, we simply read its copy. self.conn .composite_query_version(0, 4) - .map_err(|e| interne("Composite", e))? + .map_err(|e| internal("Composite", e))? .reply() - .map_err(|_| CaptureError::Unsupported("extension Composite absente".into()))?; + .map_err(|_| CaptureError::Unsupported("Composite extension missing".into()))?; let _ = self .conn - .composite_redirect_window(fenetre, composite::Redirect::AUTOMATIC); - Cible::Fenetre(fenetre) - } else if let Some(nom) = source.0.strip_prefix(PREFIXE_MONITEUR) { - let moniteur = self - .moniteurs() + .composite_redirect_window(window, composite::Redirect::AUTOMATIC); + Target::Window(window) + } else if let Some(name) = source.0.strip_prefix(MONITOR_PREFIX) { + let monitor = self + .monitors() .into_iter() - .find(|m| m.nom == nom) + .find(|m| m.name == name) .ok_or(CaptureError::SourceGone)?; - Cible::Moniteur { - nom: moniteur.nom, - rectangle: (moniteur.x, moniteur.y, moniteur.largeur, moniteur.hauteur), - verification: VERIFICATION_MONITEUR, + Target::Monitor { + name: monitor.name, + rectangle: (monitor.x, monitor.y, monitor.width, monitor.height), + countdown: MONITOR_CHECK_INTERVAL, } } else { return Err(CaptureError::SourceGone); }; - if let Some(Cible::Fenetre(ancienne)) = self.cible.replace(cible) { + if let Some(Target::Window(previous)) = self.target.replace(target) { let _ = self .conn - .composite_unredirect_window(ancienne, composite::Redirect::AUTOMATIC); + .composite_unredirect_window(previous, composite::Redirect::AUTOMATIC); } self.bgra.clear(); self.cadence.reset(); @@ -612,52 +624,52 @@ impl ScreenCapturer for X11Capturer { } fn next_frame(&mut self) -> Result { - let cible = self + let target = self .drawable() - .ok_or_else(|| CaptureError::Internal("capture non démarrée".into()))?; + .ok_or_else(|| CaptureError::Internal("capture not started".into()))?; self.cadence.wait(); - let (x, y, w, h) = self.rectangle(cible)?; + let (x, y, w, h) = self.rectangle(target)?; if w == 0 || h == 0 { - return Err(CaptureError::Internal("source de taille nulle".into())); + return Err(CaptureError::Internal("zero-size source".into())); } - let lue = self.lire(cible, (x, y), w, h)?; - if lue { + let read = self.read(target, (x, y), w, h)?; + if read { pixels::to_bgra( self.format, - &self.brut, + &self.raw, w as usize * 4, w as usize, h as usize, &mut self.bgra, )?; - self.taille_bgra = (w, h); + self.bgra_size = (w, h); } else if self.bgra.is_empty() { - return Err(CaptureError::Internal("image X indisponible".into())); + return Err(CaptureError::Internal("X image unavailable".into())); } - // Image refusée (fenêtre réduite): la précédente reste à l'écran. + // Image refused (window minimized): the previous one stays on screen. - // La sortie suit la source (#16): un changement de résolution change - // la taille des images, et c'est l'encodeur qui se reconfigure. Seule - // une dimension impaire est rognée d'un pixel, que I420 refuse. - let (bw, bh) = self.taille_bgra; - let sortie = pixels::even((bw, bh)); - let bgra = if (bw, bh) == sortie { + // The output follows the source (#16): a resolution change changes the + // image size, and the encoder reconfigures itself. Only an odd + // dimension is trimmed by one pixel, which I420 refuses. + let (bw, bh) = self.bgra_size; + let output = pixels::even((bw, bh)); + let bgra = if (bw, bh) == output { self.bgra.clone() } else { pixels::fit( &self.bgra, bw as usize, bh as usize, - (sortie.0 as usize, sortie.1 as usize), - &mut self.ajustee, + (output.0 as usize, output.1 as usize), + &mut self.fitted, ); - self.ajustee.clone() + self.fitted.clone() }; let frame = CapturedFrame { - width: sortie.0, - height: sortie.1, + width: output.0, + height: output.1, bgra, captured_at: Instant::now(), sequence: self.sequence, @@ -667,10 +679,10 @@ impl ScreenCapturer for X11Capturer { } fn stop(&mut self) { - if let Some(Cible::Fenetre(fenetre)) = self.cible.take() { + if let Some(Target::Window(window)) = self.target.take() { let _ = self .conn - .composite_unredirect_window(fenetre, composite::Redirect::AUTOMATIC); + .composite_unredirect_window(window, composite::Redirect::AUTOMATIC); } if let Some(segment) = self.segment.take() { let _ = self.conn.shm_detach(segment.id); @@ -689,16 +701,16 @@ impl Drop for X11Capturer { mod tests { use super::*; - /// Sans serveur X, la connexion échoue par un message, jamais une panique. + /// Without an X server, connecting fails with a message, never a panic. #[test] fn connecting_to_a_missing_display_fails_cleanly() { - match X11Capturer::connecter(Some(":987"), 30) { - Ok(_) => panic!("aucun serveur X ne devrait écouter sur :987"), - Err(erreur) => assert!(erreur.to_string().contains("serveur X"), "{erreur}"), + match X11Capturer::connect(Some(":987"), 30) { + Ok(_) => panic!("no X server should listen on :987"), + Err(error) => assert!(error.to_string().contains("X server"), "{error}"), } } - /// À lancer contre un serveur X jetable: + /// To run against a throwaway X server: /// /// ```text /// Xephyr :5 -screen 640x480 +extension RANDR & DISPLAY=:5 xterm & @@ -707,50 +719,50 @@ mod tests { /// RUSTSCREEN_X11_TEST=:5 cargo test -p rs-capture x11 -- --ignored /// ``` #[test] - #[ignore = "demande un serveur X (RUSTSCREEN_X11_TEST=:N)"] + #[ignore = "needs an X server (RUSTSCREEN_X11_TEST=:N)"] fn captures_the_screen_and_windows_of_a_real_server() { let display = std::env::var("RUSTSCREEN_X11_TEST").unwrap_or_else(|_| ":5".into()); - let mut capture = X11Capturer::connecter(Some(&display), 30).unwrap(); + let mut capture = X11Capturer::connect(Some(&display), 30).unwrap(); let sources = capture.sources().unwrap(); - let ecran = sources + let screen = sources .iter() - .find(|s| s.id.0 == ECRAN) - .expect("l'écran entier est toujours proposé"); - capture.start(&ecran.id).unwrap(); + .find(|s| s.id.0 == SCREEN) + .expect("the whole screen is always offered"); + capture.start(&screen.id).unwrap(); let first = capture.next_frame().unwrap(); assert_eq!(first.bgra.len(), (first.width * first.height * 4) as usize); assert!(first.bgra.as_chunks::<4>().0.iter().all(|px| px[3] == 255)); let second = capture.next_frame().unwrap(); assert_eq!(second.sequence, 1); - // Plusieurs moniteurs RandR (`xrandr --setmonitor`): chacun se capture - // à sa taille, pas à celle de l'écran entier (#16). - for moniteur in sources + // Several RandR monitors (`xrandr --setmonitor`): each one is captured + // at its own size, not at the size of the whole screen (#16). + for monitor in sources .iter() - .filter(|s| s.id.0.starts_with(PREFIXE_MONITEUR)) + .filter(|s| s.id.0.starts_with(MONITOR_PREFIX)) { - capture.start(&moniteur.id).unwrap(); + capture.start(&monitor.id).unwrap(); let image = capture.next_frame().unwrap(); assert_eq!( (image.width, image.height), - pixels::even((moniteur.width, moniteur.height)), + pixels::even((monitor.width, monitor.height)), "{}", - moniteur.id.0 + monitor.id.0 ); } - // Aucune fenêtre minuscule ni fenêtre de ce processus (#17). - for fenetre in sources.iter().filter(|s| s.kind == SourceKind::Window) { - assert!(fenetre.width >= MINIMUM_FENETRE && fenetre.height >= MINIMUM_FENETRE); + // No tiny window and no window of this process (#17). + for window in sources.iter().filter(|s| s.kind == SourceKind::Window) { + assert!(window.width >= MIN_WINDOW_SIZE && window.height >= MIN_WINDOW_SIZE); } - if let Some(fenetre) = sources + if let Some(window) = sources .iter() .find(|s| s.kind == SourceKind::Window && s.available) { - capture.start(&fenetre.id).unwrap(); + capture.start(&window.id).unwrap(); let image = capture.next_frame().unwrap(); - // Une fenêtre affichée (xeyes, xlogo) n'est pas uniformément noire. + // A mapped window (xeyes, xlogo) is not uniformly black. assert!( image .bgra @@ -758,59 +770,59 @@ mod tests { .0 .iter() .any(|px| px[..3] != [0, 0, 0]), - "image de fenêtre entièrement noire" + "window image entirely black" ); assert_eq!( (image.width, image.height), - pixels::even((fenetre.width, fenetre.height)) + pixels::even((window.width, window.height)) ); - // Avec un gestionnaire de fenêtres (openbox): réduite en cours de - // partage, la fenêtre laisse sa dernière image sans couper la - // capture; restaurée, elle reprend (#17). + // With a window manager (openbox): minimized while shared, the + // window keeps its last image without cutting the capture; + // restored, it resumes (#17). let id = u32::from_str_radix( - fenetre + window .id .0 - .trim_start_matches(PREFIXE_FENETRE) + .trim_start_matches(WINDOW_PREFIX) .trim_start_matches("0x"), 16, ) .unwrap(); - if !capture.fenetres().unwrap_or_default().is_empty() { - iconifier(&capture, id); + if !capture.windows().unwrap_or_default().is_empty() { + iconify(&capture, id); std::thread::sleep(std::time::Duration::from_millis(300)); - assert!(capture.reduite(id), "la fenêtre doit être vue réduite"); - let pendant = capture.next_frame().expect("la capture continue"); - assert_eq!(pendant.bgra, image.bgra, "dernière image gardée"); + assert!(capture.minimized(id), "the window must be seen minimized"); + let during = capture.next_frame().expect("capture goes on"); + assert_eq!(during.bgra, image.bgra, "last image kept"); capture.conn.map_window(id).unwrap(); capture.conn.flush().unwrap(); std::thread::sleep(std::time::Duration::from_millis(300)); - assert!(!capture.reduite(id), "restaurée"); - let apres = capture.next_frame().unwrap(); + assert!(!capture.minimized(id), "restored"); + let after = capture.next_frame().unwrap(); assert!( - apres + after .bgra .as_chunks::<4>() .0 .iter() .any(|px| px[..3] != [0, 0, 0]), - "image noire après restauration" + "black image after restore" ); } } } - /// Réduit une fenêtre comme le ferait un clic: demande ICCCM au - /// gestionnaire de fenêtres (`WM_CHANGE_STATE`, état iconique). - fn iconifier(capture: &X11Capturer, fenetre: Window) { - let atome = capture.atome("WM_CHANGE_STATE").unwrap(); - let message = xproto::ClientMessageEvent::new(32, fenetre, atome, [3u32, 0, 0, 0, 0]); + /// Minimizes a window the way a click would: an ICCCM request to the + /// window manager (`WM_CHANGE_STATE`, iconic state). + fn iconify(capture: &X11Capturer, window: Window) { + let atom = capture.atom("WM_CHANGE_STATE").unwrap(); + let message = xproto::ClientMessageEvent::new(32, window, atom, [3u32, 0, 0, 0, 0]); capture .conn .send_event( false, - capture.racine, + capture.root, xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY, message, ) diff --git a/crates/rs-codec/Cargo.toml b/crates/rs-codec/Cargo.toml index 38e4915..b4e6bd2 100644 --- a/crates/rs-codec/Cargo.toml +++ b/crates/rs-codec/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rs-codec" -description = "Conversion de pixels et encodeurs vidéo (VP8 et VP9 logiciels, H.264 matériel)." +description = "Pixel conversion and video encoders (software VP8 and VP9, hardware H.264)." version.workspace = true edition.workspace = true rust-version.workspace = true @@ -11,8 +11,8 @@ repository.workspace = true rs-capture = { path = "../rs-capture" } thiserror.workspace = true tracing.workspace = true -# Liaison directe à libvpx: `vpx-encode` ne réglait ni la file d'attente ni -# l'image clé forcée (#67). Le code `unsafe` vit dans `src/vpx.rs`. +# Direct binding to libvpx: `vpx-encode` controlled neither the lag queue nor +# forced keyframes (#67). The `unsafe` code lives in `src/vpx.rs`. env-libvpx-sys = "5.1.3" [dev-dependencies] diff --git a/crates/rs-codec/examples/bench_codecs.rs b/crates/rs-codec/examples/bench_codecs.rs index 61e194b..553ac06 100644 --- a/crates/rs-codec/examples/bench_codecs.rs +++ b/crates/rs-codec/examples/bench_codecs.rs @@ -1,21 +1,21 @@ -//! Compare le coût et la qualité des codecs disponibles, sur la machine courante. +//! Compares the cost and quality of the available codecs, on the current machine. //! //! cargo run --release -p rs-codec --example bench_codecs -//! taskset -c 2 cargo run --release -p rs-codec --example bench_codecs # un cœur +//! taskset -c 2 cargo run --release -p rs-codec --example bench_codecs # one core //! -//! Mesure l'encodeur de production (`VpxEncoder`, conversion BGRA vers I420 -//! comprise), pas une configuration à part. L'image est volontairement mixte: -//! des aplats, du texte qui défile et du bruit. Une mire plate avantagerait -//! tous les codecs de la même façon et ne dirait rien d'un vrai bureau. +//! Measures the production encoder (`VpxEncoder`, BGRA to I420 conversion +//! included), not a separate configuration. The image is deliberately mixed: +//! flat areas, scrolling text and noise. A flat test pattern would favor every +//! codec the same way and say nothing about a real desktop. //! -//! Trois chiffres: -//! - la cadence (temps mur, ce que voit le spectateur) et le temps processeur -//! par image, tous fils confondus (ce que paie la machine). Le second vient -//! de `/proc/self/stat`, donc Linux seulement; -//! - le débit: en débit constant, les deux codecs tiennent la cible, donc ce -//! chiffre seul ne départage rien; -//! - la qualité à débit égal (PSNR moyen calculé par libvpx, dans une passe à -//! part pour ne pas fausser les temps). C'est elle qui dit ce que VP9 achète. +//! Three figures: +//! - the frame rate (wall time, what the viewer sees) and the CPU time per +//! image, all threads combined (what the machine pays). The latter comes +//! from `/proc/self/stat`, so Linux only; +//! - the bitrate: at constant bitrate, both codecs meet the target, so this +//! figure alone settles nothing; +//! - the quality at equal bitrate (mean PSNR computed by libvpx, in a separate +//! pass so as not to skew the timings). That is what tells what VP9 buys. use std::time::Instant; @@ -27,44 +27,44 @@ const FPS: u8 = 30; const BITRATE_KBPS: u32 = 3000; const FRAMES: u32 = 300; -/// Image BGRA représentative d'un bureau: aplats, bandes de texte, un peu de -/// bruit pour que les codecs ne puissent pas tout prédire. -fn image_bureau(t: u32) -> Vec { +/// BGRA image representative of a desktop: flat areas, bands of text, a bit +/// of noise so codecs cannot predict everything. +fn desktop_image(t: u32) -> Vec { let mut pixels = vec![0u8; (WIDTH * HEIGHT * 4) as usize]; for y in 0..HEIGHT { for x in 0..WIDTH { let i = ((y * WIDTH + x) * 4) as usize; - // Une grande zone claire, comme une page de texte. + // A large light area, like a page of text. let (r, g, b): (u8, u8, u8) = if x > 80 && x < 1200 && y > 60 && y < 660 { (250, 250, 252) } else { (32, 36, 44) }; - // Lignes de texte simulées, qui glissent avec le temps. - let ligne = (y / 18) % 2 == 0 && x > 120 && x < 1100 && (y + t) % 240 > 20; - let (r, g, b): (u8, u8, u8) = if ligne { (40, 44, 52) } else { (r, g, b) }; - // Bruit léger: sans lui, tous les codecs trouveraient la même image. - let bruit = ((x * 7 + y * 13 + t * 3) % 6) as u8; - pixels[i] = b.saturating_sub(bruit); - pixels[i + 1] = g.saturating_sub(bruit); - pixels[i + 2] = r.saturating_sub(bruit); + // Simulated lines of text, sliding over time. + let line = (y / 18) % 2 == 0 && x > 120 && x < 1100 && (y + t) % 240 > 20; + let (r, g, b): (u8, u8, u8) = if line { (40, 44, 52) } else { (r, g, b) }; + // Light noise: without it, every codec would find the same image. + let noise = ((x * 7 + y * 13 + t * 3) % 6) as u8; + pixels[i] = b.saturating_sub(noise); + pixels[i + 1] = g.saturating_sub(noise); + pixels[i + 2] = r.saturating_sub(noise); pixels[i + 3] = 255; } } pixels } -/// Temps processeur du processus (utilisateur et système, tous fils), en -/// secondes. `None` hors Linux. -fn temps_processeur() -> Option { +/// CPU time of the process (user and system, all threads), in seconds. +/// `None` outside Linux. +fn cpu_time() -> Option { let stat = std::fs::read_to_string("/proc/self/stat").ok()?; - // Le nom du processus est entre parenthèses et peut contenir des espaces: - // les champs numériques commencent après la dernière. - let champs: Vec<&str> = stat.rsplit_once(')')?.1.split_whitespace().collect(); - // utime et stime sont les champs 14 et 15, soit 11 et 12 après l'état. - let utime: f64 = champs.get(11)?.parse().ok()?; - let stime: f64 = champs.get(12)?.parse().ok()?; - // USER_HZ vaut 100 sur tous les noyaux Linux courants. + // The process name is in parentheses and may contain spaces: the numeric + // fields start after the last one. + let fields: Vec<&str> = stat.rsplit_once(')')?.1.split_whitespace().collect(); + // utime and stime are fields 14 and 15, i.e. 11 and 12 after the state. + let utime: f64 = fields.get(11)?.parse().ok()?; + let stime: f64 = fields.get(12)?.parse().ok()?; + // USER_HZ is 100 on every common Linux kernel. Some((utime + stime) / 100.0) } @@ -78,59 +78,59 @@ fn config(codec: VideoCodec, bitrate_kbps: u32) -> EncodeConfig { } } -struct Mesure { +struct Measurement { fps: f64, cpu_ms: Option, } -fn vues(images: &[Vec]) -> impl Iterator> { +fn views(images: &[Vec]) -> impl Iterator> { images .iter() .map(|bgra| BgraFrame::new(bgra, WIDTH as usize, HEIGHT as usize).expect("image")) } -/// Passe chronométrée: cadence, temps processeur, premier paquet, débit. -fn cout(codec: VideoCodec, images: &[Vec]) -> Mesure { - let mut encoder = VpxEncoder::new(config(codec, BITRATE_KBPS)).expect("encodeur"); +/// Timed pass: frame rate, CPU time, first packet, bitrate. +fn cost(codec: VideoCodec, images: &[Vec]) -> Measurement { + let mut encoder = VpxEncoder::new(config(codec, BITRATE_KBPS)).expect("encoder"); let mut total = 0usize; - let mut premier = None; - let cpu_debut = temps_processeur(); - let debut = Instant::now(); - for (t, view) in vues(images).enumerate() { - let debut_image = Instant::now(); + let mut first = None; + let cpu_start = cpu_time(); + let start = Instant::now(); + for (t, view) in views(images).enumerate() { + let image_start = Instant::now(); let packets = encoder.encode(&view).unwrap_or_default(); - if premier.is_none() && !packets.is_empty() { - premier = Some((t, debut_image.elapsed())); + if first.is_none() && !packets.is_empty() { + first = Some((t, image_start.elapsed())); } total += packets.iter().map(Vec::len).sum::(); } - let duree = debut.elapsed().as_secs_f64(); - let cpu = cpu_debut - .zip(temps_processeur()) + let duration = start.elapsed().as_secs_f64(); + let cpu = cpu_start + .zip(cpu_time()) .map(|(a, b)| (b - a) * 1000.0 / images.len() as f64); - let fps = images.len() as f64 / duree; - // Débit à la cadence nominale: ce que le réseau verrait à 30 i/s. + let fps = images.len() as f64 / duration; + // Bitrate at the nominal frame rate: what the network would see at 30 fps. let kbps = total as f64 * 8.0 * f64::from(FPS) / images.len() as f64 / 1000.0; - let (rang, latence) = premier.expect("au moins un paquet"); + let (index, latency) = first.expect("at least one packet"); println!( - "{:4} {:6.1} i/s {:>5} ms CPU/image {:5.0} kbit/s premier paquet: image {rang}, {:.1} ms", + "{:4} {:6.1} fps {:>5} ms CPU/image {:5.0} kbit/s first packet: image {index}, {:.1} ms", codec.rtp_name(), fps, cpu.map_or("?".to_string(), |c| format!("{c:.1}")), kbps, - latence.as_secs_f64() * 1000.0, + latency.as_secs_f64() * 1000.0, ); - Mesure { fps, cpu_ms: cpu } + Measurement { fps, cpu_ms: cpu } } -/// Passe de qualité: PSNR moyen à un débit donné. -fn qualite(codec: VideoCodec, bitrate_kbps: u32, images: &[Vec]) -> f64 { +/// Quality pass: mean PSNR at a given bitrate. +fn quality(codec: VideoCodec, bitrate_kbps: u32, images: &[Vec]) -> f64 { let mut encoder = - VpxEncoder::avec_psnr(config(codec, bitrate_kbps)).expect("encodeur avec PSNR"); - let mut somme = 0.0; + VpxEncoder::with_psnr(config(codec, bitrate_kbps)).expect("encoder with PSNR"); + let mut sum = 0.0; let mut n = 0; let mut total = 0usize; - for view in vues(images) { + for view in views(images) { total += encoder .encode(&view) .unwrap_or_default() @@ -138,29 +138,29 @@ fn qualite(codec: VideoCodec, bitrate_kbps: u32, images: &[Vec]) -> f64 { .map(Vec::len) .sum::(); if let Some(psnr) = encoder.psnr() { - somme += psnr; + sum += psnr; n += 1; } } - let psnr = somme / f64::from(n.max(1)); + let psnr = sum / f64::from(n.max(1)); let kbps = total as f64 * 8.0 * f64::from(FPS) / images.len() as f64 / 1000.0; println!( - "{:4} cible {bitrate_kbps:4} kbit/s: {kbps:5.0} kbit/s obtenus, PSNR moyen {psnr:.2} dB", + "{:4} target {bitrate_kbps:4} kbit/s: {kbps:5.0} kbit/s achieved, mean PSNR {psnr:.2} dB", codec.rtp_name() ); psnr } fn main() { - let fils = std::thread::available_parallelism().map_or(1, |n| n.get()); - println!("{WIDTH}x{HEIGHT} @ {FPS} i/s, {FRAMES} images, {fils} cœur(s) visibles, release\n"); - let images: Vec> = (0..FRAMES).map(image_bureau).collect(); + let threads = std::thread::available_parallelism().map_or(1, |n| n.get()); + println!("{WIDTH}x{HEIGHT} @ {FPS} fps, {FRAMES} images, {threads} visible core(s), release\n"); + let images: Vec> = (0..FRAMES).map(desktop_image).collect(); - println!("Coût, cible {BITRATE_KBPS} kbit/s:"); - let vp8 = cout(VideoCodec::Vp8, &images); - let vp9 = cout(VideoCodec::Vp9, &images); + println!("Cost, target {BITRATE_KBPS} kbit/s:"); + let vp8 = cost(VideoCodec::Vp8, &images); + let vp9 = cost(VideoCodec::Vp9, &images); println!( - "VP9 / VP8: {:.2}x le temps mur, {} le temps processeur\n", + "VP9 / VP8: {:.2}x the wall time, {} the CPU time\n", vp8.fps / vp9.fps, match vp8.cpu_ms.zip(vp9.cpu_ms) { Some((a, b)) => format!("{:.2}x", b / a), @@ -168,10 +168,10 @@ fn main() { }, ); - println!("Qualité à débit égal:"); - for debit in [500, 1000, 3000] { - let a = qualite(VideoCodec::Vp8, debit, &images); - let b = qualite(VideoCodec::Vp9, debit, &images); - println!(" écart VP9 - VP8 à {debit} kbit/s: {:+.2} dB", b - a); + println!("Quality at equal bitrate:"); + for bitrate in [500, 1000, 3000] { + let a = quality(VideoCodec::Vp8, bitrate, &images); + let b = quality(VideoCodec::Vp9, bitrate, &images); + println!(" VP9 - VP8 gap at {bitrate} kbit/s: {:+.2} dB", b - a); } } diff --git a/crates/rs-codec/src/color.rs b/crates/rs-codec/src/color.rs index 1cfeb94..135aeba 100644 --- a/crates/rs-codec/src/color.rs +++ b/crates/rs-codec/src/color.rs @@ -1,11 +1,11 @@ -//! Conversion BGRA vers I420, en BT.709. +//! BGRA to I420 conversion, in BT.709. //! -//! C'est l'étape où les couleurs se délavent sans qu'on comprenne pourquoi: la -//! matrice BT.601 appliquée à du BT.709 donne des rouges briques et des verts -//! jaunes, et rien dans le pipeline ne le signale. Les coefficients sont donc -//! figés ici, avec des tests sur des couleurs connues. +//! This is the step where colors wash out without anyone understanding why: +//! the BT.601 matrix applied to BT.709 gives brick reds and yellowish greens, +//! and nothing in the pipeline flags it. The coefficients are therefore fixed +//! here, with tests on known colors. -/// Image BGRA telle que la rendent les API de capture (Windows, macOS, PipeWire). +/// BGRA image as the capture APIs deliver it (Windows, macOS, PipeWire). pub struct BgraFrame<'a> { pub data: &'a [u8], pub width: usize, @@ -17,7 +17,7 @@ impl std::fmt::Debug for BgraFrame<'_> { f.debug_struct("BgraFrame") .field("width", &self.width) .field("height", &self.height) - .field("octets", &self.data.len()) + .field("bytes", &self.data.len()) .finish() } } @@ -28,8 +28,8 @@ impl<'a> BgraFrame<'a> { return Err(ColorError::Empty); } if !width.is_multiple_of(2) || !height.is_multiple_of(2) { - // VP8 exige des dimensions paires; mieux vaut refuser ici que - // produire une image décalée d'une colonne. + // VP8 requires even dimensions; better to refuse here than to + // produce an image shifted by one column. return Err(ColorError::OddDimensions { width, height }); } let expected = width * height * 4; @@ -47,10 +47,10 @@ impl<'a> BgraFrame<'a> { } } -/// Convertit une image BGRA en I420 (Y pleine taille, U et V en 4:2:0). +/// Converts a BGRA image to I420 (full-size Y, U and V in 4:2:0). /// -/// `out` est réutilisé d'une frame à l'autre pour éviter une allocation par -/// image, ce qui compte à 30 images par seconde. +/// `out` is reused from one frame to the next to avoid one allocation per +/// image, which matters at 30 frames per second. pub fn bgra_to_i420(frame: &BgraFrame, out: &mut Vec) { let width = frame.width; let height = frame.height; @@ -73,7 +73,7 @@ pub fn bgra_to_i420(frame: &BgraFrame, out: &mut Vec) { } } - // Chroma: moyenne des quatre pixels du bloc 2x2, en pleine résolution. + // Chroma: average of the four pixels of the 2x2 block, at full resolution. for row in (0..height).step_by(2) { for col in (0..width).step_by(2) { let mut sum_u = 0i32; @@ -96,18 +96,18 @@ pub fn bgra_to_i420(frame: &BgraFrame, out: &mut Vec) { } } -/// Y en BT.709, plage limitée (16 à 235). +/// Y in BT.709, limited range (16 to 235). #[inline] fn rgb_to_y(r: i32, g: i32, b: i32) -> u8 { (((47 * r + 157 * g + 16 * b + 128) >> 8) + 16).clamp(0, 255) as u8 } -/// Coefficients BT.709 en 1/256, somme nulle par construction. +/// BT.709 coefficients in 1/256, summing to zero by construction. /// -/// U = 0.4733*(B - Y) et V = 0.6350*(R - Y), développés avec -/// Y = 0.2126R + 0.7152G + 0.0722B. Omettre un des trois termes, c'est le bug -/// classique: la conversion reste plausible à l'oeil sur du gris et fausse sur -/// les couleurs saturées. +/// U = 0.4733*(B - Y) and V = 0.6350*(R - Y), expanded with +/// Y = 0.2126R + 0.7152G + 0.0722B. Leaving out one of the three terms is the +/// classic bug: the conversion still looks plausible on grey and is wrong on +/// saturated colors. #[inline] fn rgb_to_u(r: i32, g: i32, b: i32) -> i32 { (((-26 * r - 87 * g + 112 * b + 128) >> 8) + 128).clamp(0, 255) @@ -120,11 +120,11 @@ fn rgb_to_v(r: i32, g: i32, b: i32) -> i32 { #[derive(Debug, thiserror::Error, PartialEq, Eq)] pub enum ColorError { - #[error("image vide")] + #[error("empty image")] Empty, - #[error("dimensions impaires {width}x{height}: VP8 exige des multiples de 2")] + #[error("odd dimensions {width}x{height}: VP8 requires multiples of 2")] OddDimensions { width: usize, height: usize }, - #[error("buffer trop court: {got} octets pour {expected} attendus")] + #[error("buffer too short: {got} bytes, {expected} expected")] TooShort { expected: usize, got: usize }, } @@ -151,18 +151,18 @@ mod tests { #[test] fn white_maps_to_limited_range_y() { let out = convert(2, 2, 255, 255, 255); - assert_eq!(out[0], 235, "Y du blanc en plage limitée"); - // Un écart d'une unité sur le chroma est normal en arithmétique entière. - assert!((127..=129).contains(&out[4]), "U du blanc: {}", out[4]); - assert!((127..=129).contains(&out[5]), "V du blanc: {}", out[5]); + assert_eq!(out[0], 235, "Y of white in limited range"); + // A one-unit deviation on chroma is normal in integer arithmetic. + assert!((127..=129).contains(&out[4]), "U of white: {}", out[4]); + assert!((127..=129).contains(&out[5]), "V of white: {}", out[5]); } #[test] fn black_maps_to_sixteen() { let out = convert(2, 2, 0, 0, 0); assert_eq!(out[0], 16); - assert!((127..=129).contains(&out[4]), "U du noir: {}", out[4]); - assert!((127..=129).contains(&out[5]), "V du noir: {}", out[5]); + assert!((127..=129).contains(&out[4]), "U of black: {}", out[4]); + assert!((127..=129).contains(&out[5]), "V of black: {}", out[5]); } #[test] @@ -171,9 +171,9 @@ mod tests { let y = out[0]; let u = out[4]; let v = out[5]; - assert!((60..=68).contains(&y), "Y du rouge: {y}"); - assert!(u < 115, "U du rouge doit baisser: {u}"); - assert!(v > 230, "V du rouge doit monter: {v}"); + assert!((60..=68).contains(&y), "Y of red: {y}"); + assert!(u < 115, "U of red must drop: {u}"); + assert!(v > 230, "V of red must rise: {v}"); } #[test] @@ -181,22 +181,22 @@ mod tests { let out = convert(2, 2, 0, 255, 0); let u = out[4]; let v = out[5]; - assert!(u < 110, "U du vert: {u}"); - assert!(v < 110, "V du vert: {v}"); + assert!(u < 110, "U of green: {u}"); + assert!(v < 110, "V of green: {v}"); } #[test] fn blue_raises_u() { let out = convert(2, 2, 255, 0, 0); - assert!(out[4] > 230, "U du bleu: {}", out[4]); - // Le bleu pur garde un V légèrement au-dessus du neutre, pas en dessous. - assert!((112..=122).contains(&out[5]), "V du bleu: {}", out[5]); + assert!(out[4] > 230, "U of blue: {}", out[4]); + // Pure blue keeps V slightly above neutral, not below. + assert!((112..=122).contains(&out[5]), "V of blue: {}", out[5]); } #[test] fn chroma_averages_a_2x2_block() { - // Deux pixels rouges et deux pixels bleus dans le même bloc: U et V - // doivent être à mi-chemin, pas recopiés du premier pixel. + // Two red pixels and two blue pixels in the same block: U and V must be + // halfway, not copied from the first pixel. let mut data = Vec::new(); data.extend_from_slice(&[0, 0, 255, 255]); data.extend_from_slice(&[255, 0, 0, 255]); @@ -207,10 +207,10 @@ mod tests { bgra_to_i420(&frame, &mut out); let u = out[4]; let v = out[5]; - // U rouge ~102, U bleu ~240, donc la moyenne doit être au milieu, et - // surtout pas recopiée du premier pixel. - assert!((160..=182).contains(&u), "U moyenné: {u}"); - assert!((175..=195).contains(&v), "V moyenné: {v}"); + // Red U ~102, blue U ~240, so the average must sit in the middle, and + // above all not be copied from the first pixel. + assert!((160..=182).contains(&u), "averaged U: {u}"); + assert!((175..=195).contains(&v), "averaged V: {v}"); } #[test] diff --git a/crates/rs-codec/src/encoder.rs b/crates/rs-codec/src/encoder.rs index 155fcd1..c50c005 100644 --- a/crates/rs-codec/src/encoder.rs +++ b/crates/rs-codec/src/encoder.rs @@ -1,19 +1,20 @@ -//! Encodage vidéo: BGRA vers I420 puis VP8 ou VP9. +//! Video encoding: BGRA to I420, then VP8 or VP9. //! -//! VP8 par défaut (ADR 0004): lisible par tous les navigateurs et sans -//! dépendance matérielle. VP9 en option, au coût et au débit mesurés dans -//! `docs/perf.md`. Les deux passent par le même encodeur libvpx temps réel -//! ([`crate::vpx`]): aucune image en file, image clé forcée sur demande. -//! L'encodeur matériel viendra derrière le même trait. +//! VP8 by default (ADR 0004): readable by every browser and with no hardware +//! dependency. VP9 as an option, at the cost and bitrate measured in +//! `docs/perf.md`. Both go through the same real-time libvpx encoder +//! ([`crate::vpx`]): no queued frame, keyframe forced on request. The +//! hardware encoder will come behind the same trait. //! -//! Dépendance de build: libvpx (paquet système, ou `scripts/build-libvpx.sh` -//! pour une installation locale). Voir AGENTS.md. +//! Build dependency: libvpx (system package, or `scripts/build-libvpx.sh` for +//! a local install). See AGENTS.md. use crate::color::{BgraFrame, ColorError, bgra_to_i420}; -use crate::vpx::{Contexte, Reglages}; +use crate::vpx::{Context, EncoderSettings}; -/// Codec vidéo produit. Le transport doit annoncer le même: un flux VP9 étiqueté -/// VP8 est indécodable, et le symptôme est un écran noir sans erreur. +/// Video codec produced. The transport must announce the same one: a VP9 +/// stream labelled VP8 cannot be decoded, and the symptom is a black screen +/// with no error. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum VideoCodec { #[default] @@ -29,7 +30,7 @@ impl VideoCodec { } } - /// Nom RTP, pour l'annonce SDP. + /// RTP name, for the SDP announcement. pub fn rtp_name(self) -> &'static str { match self { Self::Vp8 => "VP8", @@ -41,17 +42,17 @@ impl VideoCodec { impl std::str::FromStr for VideoCodec { type Err = String; - fn from_str(valeur: &str) -> Result { - match valeur.to_ascii_lowercase().as_str() { + fn from_str(value: &str) -> Result { + match value.to_ascii_lowercase().as_str() { "vp8" => Ok(Self::Vp8), "vp9" => Ok(Self::Vp9), - autre => Err(format!("codec inconnu: {autre} (attendu: vp8 ou vp9)")), + other => Err(format!("unknown codec: {other} (expected: vp8 or vp9)")), } } } -/// Réglages d'un encodeur. Le débit est une cible, pas une garantie: libvpx le -/// respecte en moyenne sur environ une seconde (tampon de 1000 ms). +/// Encoder settings. The bitrate is a target, not a guarantee: libvpx meets it +/// on average over about one second (1000 ms buffer). #[derive(Clone, Copy, Debug)] pub struct EncodeConfig { pub width: u32, @@ -63,37 +64,37 @@ pub struct EncodeConfig { #[derive(Debug, thiserror::Error)] pub enum EncodeError { - #[error("couleurs: {0}")] + #[error("colors: {0}")] Color(#[from] ColorError), - #[error("initialisation de l'encodeur: {0}")] + #[error("encoder initialization: {0}")] Init(String), - #[error("encodage: {0}")] + #[error("encoding: {0}")] Encode(String), - #[error("aucune frame produite pour l'image fournie")] + #[error("no frame produced for the given image")] NoFrame, } -/// Ce qu'un encodeur doit savoir faire pour alimenter une session. +/// What an encoder must be able to do to feed a session. pub trait VideoEncoder: Send { - /// Encode une image BGRA et rend les paquets produits. + /// Encodes a BGRA image and returns the packets produced. fn encode(&mut self, frame: &BgraFrame) -> Result>, EncodeError>; - /// Force une image clé à la prochaine frame (nouveau spectateur, reprise). + /// Forces a keyframe on the next frame (new viewer, resume). fn request_keyframe(&mut self); fn config(&self) -> EncodeConfig; - /// Change la taille encodée (résolution de la source modifiée en cours de - /// session, #16). La première image qui suit est une image clé: le - /// décodeur du navigateur change de taille sans renégociation. - fn reconfigurer(&mut self, width: u32, height: u32) -> Result<(), EncodeError>; + /// Changes the encoded size (source resolution changed during the + /// session, #16). The first image that follows is a keyframe: the + /// browser's decoder changes size without renegotiation. + fn reconfigure(&mut self, width: u32, height: u32) -> Result<(), EncodeError>; } -/// Encodeur libvpx temps réel, VP8 ou VP9. +/// Real-time libvpx encoder, VP8 or VP9. pub struct VpxEncoder { - inner: Contexte, + inner: Context, config: EncodeConfig, i420: Vec, pts: i64, - keyframe_demandee: bool, - mesure_psnr: bool, + keyframe_requested: bool, + measure_psnr: bool, } impl std::fmt::Debug for VpxEncoder { @@ -106,10 +107,10 @@ impl std::fmt::Debug for VpxEncoder { } } -/// Fils d'encodage: libvpx répartit une image sur plusieurs cœurs (lignes et -/// tuiles pour VP9, partitions pour VP8). Quatre au plus: au-delà le gain est -/// faible, et la capture comme le navigateur ont besoin du reste. -fn fils() -> u32 { +/// Encoding threads: libvpx spreads an image over several cores (rows and +/// tiles for VP9, partitions for VP8). Four at most: beyond that the gain is +/// small, and both capture and the browser need the rest. +fn threads() -> u32 { std::thread::available_parallelism() .map(|n| n.get() as u32) .unwrap_or(1) @@ -118,49 +119,49 @@ fn fils() -> u32 { impl VpxEncoder { pub fn new(config: EncodeConfig) -> Result { - Self::ouvrir_avec(config, false) + Self::open_with(config, false) } - /// Comme [`VpxEncoder::new`], avec le PSNR de chaque image calculé par - /// libvpx ([`VpxEncoder::psnr`]). Pour les bancs d'essai: le calcul a un - /// coût, et comparer deux codecs à débit égal n'a de sens qu'avec une - /// mesure de qualité. - pub fn avec_psnr(config: EncodeConfig) -> Result { - Self::ouvrir_avec(config, true) + /// Like [`VpxEncoder::new`], with the PSNR of each image computed by libvpx + /// ([`VpxEncoder::psnr`]). For benchmarks: the computation has a cost, and + /// comparing two codecs at equal bitrate only makes sense with a quality + /// measurement. + pub fn with_psnr(config: EncodeConfig) -> Result { + Self::open_with(config, true) } - /// PSNR de la dernière image encodée, en dB. `None` sans - /// [`VpxEncoder::avec_psnr`]. + /// PSNR of the last encoded image, in dB. `None` without + /// [`VpxEncoder::with_psnr`]. pub fn psnr(&self) -> Option { self.inner.psnr() } - fn ouvrir_avec(config: EncodeConfig, mesure_psnr: bool) -> Result { + fn open_with(config: EncodeConfig, measure_psnr: bool) -> Result { Ok(Self { - inner: Self::ouvrir(&config, mesure_psnr)?, + inner: Self::open(&config, measure_psnr)?, config, i420: Vec::new(), pts: 0, - keyframe_demandee: false, - mesure_psnr, + keyframe_requested: false, + measure_psnr, }) } - fn ouvrir(config: &EncodeConfig, psnr: bool) -> Result { + fn open(config: &EncodeConfig, psnr: bool) -> Result { if config.width == 0 || config.height == 0 || !config.width.is_multiple_of(2) || !config.height.is_multiple_of(2) { - return Err(EncodeError::Init("dimensions impaires ou nulles".into())); + return Err(EncodeError::Init("odd or zero dimensions".into())); } - Contexte::ouvrir(&Reglages { + Context::open(&EncoderSettings { codec: config.codec, width: config.width, height: config.height, fps: u32::from(config.fps.max(1)), bitrate_kbps: config.bitrate_kbps, - threads: fils(), + threads: threads(), psnr, }) .map_err(|e| EncodeError::Init(e.to_string())) @@ -170,52 +171,52 @@ impl VpxEncoder { impl VideoEncoder for VpxEncoder { fn encode(&mut self, frame: &BgraFrame) -> Result>, EncodeError> { bgra_to_i420(frame, &mut self.i420); - // `VPX_EFLAG_FORCE_KF`: l'image clé sort de l'encodeur en place, sans - // le rouvrir ni perdre son contrôle de débit. - let image_cle = std::mem::take(&mut self.keyframe_demandee); - let paquets = match self.inner.encoder(&self.i420, self.pts, image_cle) { - Ok(paquets) => paquets, - Err(erreur) => { - self.keyframe_demandee |= image_cle; - return Err(EncodeError::Encode(erreur.to_string())); + // `VPX_EFLAG_FORCE_KF`: the keyframe comes out of the encoder in + // place, without reopening it or losing its rate control. + let keyframe = std::mem::take(&mut self.keyframe_requested); + let packets = match self.inner.encode(&self.i420, self.pts, keyframe) { + Ok(packets) => packets, + Err(error) => { + self.keyframe_requested |= keyframe; + return Err(EncodeError::Encode(error.to_string())); } }; self.pts += 1; - if paquets.is_empty() { - // La demande n'est pas perdue: la prochaine image la reprend. - self.keyframe_demandee |= image_cle; + if packets.is_empty() { + // The request is not lost: the next image picks it up. + self.keyframe_requested |= keyframe; return Err(EncodeError::NoFrame); } - if image_cle && !paquets.iter().any(|p| p.keyframe) { + if keyframe && !packets.iter().any(|p| p.keyframe) { tracing::warn!( codec = self.config.codec.as_str(), - "image clé demandée, libvpx a rendu une image inter" + "keyframe requested, libvpx returned an inter frame" ); } - Ok(paquets.into_iter().map(|p| p.data).collect()) + Ok(packets.into_iter().map(|p| p.data).collect()) } fn request_keyframe(&mut self) { - self.keyframe_demandee = true; + self.keyframe_requested = true; } fn config(&self) -> EncodeConfig { self.config } - fn reconfigurer(&mut self, width: u32, height: u32) -> Result<(), EncodeError> { + fn reconfigure(&mut self, width: u32, height: u32) -> Result<(), EncodeError> { let config = EncodeConfig { width, height, ..self.config }; - // Rouvrir plutôt que `vpx_codec_enc_config_set`: libvpx refuse - // d'agrandir au-delà de la taille d'ouverture, et rouvrir donne - // justement l'image clé dont le décodeur a besoin. Le nouvel encodeur - // est ouvert avant de lâcher l'ancien: un échec laisse le flux intact. - self.inner = Self::ouvrir(&config, self.mesure_psnr)?; + // Reopen rather than `vpx_codec_enc_config_set`: libvpx refuses to + // grow beyond the size it was opened with, and reopening gives exactly + // the keyframe the decoder needs. The new encoder is opened before the + // old one is dropped: a failure leaves the stream intact. + self.inner = Self::open(&config, self.measure_psnr)?; self.config = config; - self.keyframe_demandee = false; + self.keyframe_requested = false; Ok(()) } } @@ -242,47 +243,47 @@ mod tests { } } - /// Image clé VP8: bit 0 du premier octet à zéro (RFC 6386, 9.1). - fn vp8_cle(paquet: &[u8]) -> bool { - paquet[0] & 0x01 == 0 + /// VP8 keyframe: bit 0 of the first byte is zero (RFC 6386, 9.1). + fn vp8_key(packet: &[u8]) -> bool { + packet[0] & 0x01 == 0 } - /// Image clé VP9, profil 0: marqueur `10`, profil `00`, pas d'image - /// existante, puis `frame_type` à zéro (spécification VP9, 6.2). - fn vp9_cle(paquet: &[u8]) -> bool { - paquet[0] >> 6 == 0b10 && paquet[0] & 0b0011_1100 == 0 + /// VP9 keyframe, profile 0: marker `10`, profile `00`, no show-existing + /// frame, then `frame_type` at zero (VP9 specification, 6.2). + fn vp9_key(packet: &[u8]) -> bool { + packet[0] >> 6 == 0b10 && packet[0] & 0b0011_1100 == 0 } #[test] fn encodes_a_solid_frame() { - let mut encoder = VpxEncoder::new(config(VideoCodec::Vp8)).expect("initialisation"); + let mut encoder = VpxEncoder::new(config(VideoCodec::Vp8)).expect("initialization"); let data = solid(320, 240, 40, 80, 200); let frame = BgraFrame::new(&data, 320, 240).unwrap(); - let packets = encoder.encode(&frame).expect("encodage"); + let packets = encoder.encode(&frame).expect("encoding"); assert!(!packets.is_empty()); - assert!(!packets[0].is_empty(), "un paquet VP8 non vide"); + assert!(!packets[0].is_empty(), "a non-empty VP8 packet"); } - /// Le critère de #67: sans file d'attente dans libvpx, la première image - /// donne le premier paquet, et c'est une image clé. Avec `vpx-encode`, il - /// sortait à la frame 24 (environ 800 ms à 30 i/s). + /// The criterion of #67: with no lag queue in libvpx, the first image + /// gives the first packet, and it is a keyframe. With `vpx-encode`, it came + /// out at frame 24 (about 800 ms at 30 fps). #[test] fn the_first_frame_gives_the_first_packet_in_both_codecs() { for codec in [VideoCodec::Vp8, VideoCodec::Vp9] { - let mut encoder = VpxEncoder::new(config(codec)).expect("initialisation"); + let mut encoder = VpxEncoder::new(config(codec)).expect("initialization"); let data = solid(320, 240, 20, 120, 60); let frame = BgraFrame::new(&data, 320, 240).unwrap(); for i in 0..30 { let packets = encoder .encode(&frame) .unwrap_or_else(|e| panic!("{codec:?}, frame {i}: {e}")); - assert_eq!(packets.len(), 1, "{codec:?}: une image, un paquet"); + assert_eq!(packets.len(), 1, "{codec:?}: one image, one packet"); if i == 0 { - let cle = match codec { - VideoCodec::Vp8 => vp8_cle(&packets[0]), - VideoCodec::Vp9 => vp9_cle(&packets[0]), + let key = match codec { + VideoCodec::Vp8 => vp8_key(&packets[0]), + VideoCodec::Vp9 => vp9_key(&packets[0]), }; - assert!(cle, "{codec:?}: la première image est une image clé"); + assert!(key, "{codec:?}: the first image is a keyframe"); } } } @@ -294,25 +295,25 @@ mod tests { let mut encoder = VpxEncoder::new(config(codec)).unwrap(); let data = solid(320, 240, 10, 10, 10); let frame = BgraFrame::new(&data, 320, 240).unwrap(); - let cle = |p: &[u8]| match codec { - VideoCodec::Vp8 => vp8_cle(p), - VideoCodec::Vp9 => vp9_cle(p), + let key = |p: &[u8]| match codec { + VideoCodec::Vp8 => vp8_key(p), + VideoCodec::Vp9 => vp9_key(p), }; for _ in 0..3 { encoder.encode(&frame).unwrap(); } let inter = encoder.encode(&frame).unwrap(); - assert!(!cle(&inter[0]), "{codec:?}: image inter attendue"); + assert!(!key(&inter[0]), "{codec:?}: inter frame expected"); encoder.request_keyframe(); - // Après une demande, la frame suivante est de nouveau une image clé: - // c'est ce dont un spectateur qui rejoint a besoin. - let packets = encoder.encode(&frame).expect("encodage après demande"); - assert!(cle(&packets[0]), "{codec:?}: image clé après demande"); - // Et une seule: la suivante repart en inter. - let suite = encoder.encode(&frame).unwrap(); + // After a request, the next frame is a keyframe again: that is + // what a joining viewer needs. + let packets = encoder.encode(&frame).expect("encoding after request"); + assert!(key(&packets[0]), "{codec:?}: keyframe after request"); + // And only one: the next one goes back to inter. + let next = encoder.encode(&frame).unwrap(); assert!( - !cle(&suite[0]), - "{codec:?}: la demande ne dure qu'une image" + !key(&next[0]), + "{codec:?}: the request lasts one image only" ); } } @@ -320,19 +321,19 @@ mod tests { #[test] fn reconfiguring_restarts_on_a_keyframe_at_the_new_size() { let mut encoder = VpxEncoder::new(config(VideoCodec::Vp9)).unwrap(); - let petite = solid(320, 240, 10, 10, 10); + let small = solid(320, 240, 10, 10, 10); encoder - .encode(&BgraFrame::new(&petite, 320, 240).unwrap()) + .encode(&BgraFrame::new(&small, 320, 240).unwrap()) .unwrap(); - encoder.reconfigurer(640, 360).expect("agrandir"); + encoder.reconfigure(640, 360).expect("grow"); assert_eq!(encoder.config().width, 640); - let grande = solid(640, 360, 10, 10, 10); + let large = solid(640, 360, 10, 10, 10); let packets = encoder - .encode(&BgraFrame::new(&grande, 640, 360).unwrap()) + .encode(&BgraFrame::new(&large, 640, 360).unwrap()) .unwrap(); - assert!(vp9_cle(&packets[0])); - assert!(encoder.reconfigurer(641, 360).is_err()); - // Un refus laisse l'encodeur en place, à l'ancienne taille. + assert!(vp9_key(&packets[0])); + assert!(encoder.reconfigure(641, 360).is_err()); + // A refusal leaves the encoder in place, at the old size. assert_eq!(encoder.config().width, 640); } diff --git a/crates/rs-codec/src/frame.rs b/crates/rs-codec/src/frame.rs index 98cce75..34ba295 100644 --- a/crates/rs-codec/src/frame.rs +++ b/crates/rs-codec/src/frame.rs @@ -1,48 +1,48 @@ -//! Source de frames pour une session média. +//! Frame source for a media session. //! -//! Le produit final alimentera cette interface depuis `rs-capture` (écran réel) -//! puis `rs-codec::VpxEncoder` (VP8 ou VP9). Les implémentations en mémoire et IVF -//! servent aux tests et au banc d'essai: elles permettent de faire tourner une -//! session complète sans écran ni GPU. +//! The final product feeds this interface from `rs-capture` (real screen) then +//! `rs-codec::VpxEncoder` (VP8 or VP9). The in-memory and IVF implementations +//! serve tests and the test bench: they let a complete session run without a +//! screen or a GPU. use std::sync::Arc; -/// Cadence et contenu d'une source vidéo. +/// Cadence and content of a video source. /// -/// `Send` parce qu'une session par spectateur consomme sa propre source depuis -/// sa propre tâche. +/// `Send` because one session per viewer consumes its own source from its own +/// task. pub trait FrameSource: Send { fn fps(&self) -> u8; fn dimensions(&self) -> (u32, u32); - /// Frame suivante, en boucle. L'implémentation ne bloque pas. + /// Next frame, looping. The implementation does not block. fn next_frame(&mut self) -> Arc<[u8]>; - /// Nombre de frames déjà servies, pour les statistiques. + /// Number of frames already served, for statistics. fn served(&self) -> u64; } -/// Une source média partageable entre plusieurs sessions. +/// A media source shareable between several sessions. /// -/// Un hôte qui diffuse vers cinq spectateurs ne doit capturer et encoder qu'une -/// fois: chaque abonné reçoit son propre curseur sur la même image publiée. -/// L'implémentation décide comment, mais l'appelant n'a qu'à abonner. +/// A host streaming to five viewers must capture and encode only once: each +/// subscriber gets its own cursor on the same published image. The +/// implementation decides how, the caller only has to subscribe. pub trait SharedMedia: Send + Sync { - /// Un consommateur indépendant, avec son propre curseur. + /// An independent consumer, with its own cursor. fn subscribe(&self) -> Box; fn fps(&self) -> u8; fn dimensions(&self) -> (u32, u32); - /// Codec produit, que le transport doit annoncer dans le SDP. + /// Codec produced, which the transport must announce in the SDP. fn codec(&self) -> crate::encoder::VideoCodec { crate::encoder::VideoCodec::Vp8 } - /// Demande une image clé au prochain encodage. Sans effet sur une source - /// déjà encodée, d'où l'implémentation par défaut. + /// Requests a keyframe at the next encode. No effect on an already encoded + /// source, hence the default implementation. fn request_keyframe(&self) {} } -/// Rejeu d'une séquence déjà encodée (fichier IVF), partagé entre spectateurs. +/// Replay of an already encoded sequence (IVF file), shared between viewers. /// -/// Les frames sont en mémoire et chaque abonné boucle dessus à son rythme: pas -/// de décodage ni d'encodage, donc rien à protéger entre les sessions. +/// The frames are in memory and each subscriber loops over them at its own +/// pace: no decoding or encoding, so nothing to protect between sessions. pub struct SharedPlayback { frames: Arc>>, fps: u8, @@ -80,10 +80,10 @@ impl SharedMedia for SharedPlayback { } } -/// Frames partagées entre plusieurs sessions, chacune avec son curseur. +/// Frames shared between several sessions, each with its own cursor. /// -/// Un hôte qui diffuse vers cinq spectateurs ne doit pas encoder cinq fois: il -/// partage les frames encodées et laisse chaque session avancer son curseur. +/// A host streaming to five viewers must not encode five times: it shares the +/// encoded frames and lets each session advance its cursor. pub struct SharedFrames { frames: Arc>>, fps: u8, @@ -130,8 +130,8 @@ impl FrameSource for SharedFrames { } } -/// Une mire synthétique générée en mémoire, pour les tests qui n'ont pas de -/// fichier sous la main. +/// A synthetic test pattern generated in memory, for tests that have no file +/// at hand. pub struct SyntheticFrames { fps: u8, width: u32, @@ -160,8 +160,8 @@ impl FrameSource for SyntheticFrames { } fn next_frame(&mut self) -> Arc<[u8]> { - // Payload factice: ces frames ne sont pas décodables, elles servent à - // vérifier la mécanique de session, pas le rendu. + // Dummy payload: these frames are not decodable, they check the session + // mechanics, not the rendering. self.served += 1; Arc::from(format!("frame-{}", self.served).into_bytes()) } @@ -221,7 +221,7 @@ mod tests { assert_eq!( &*second.next_frame(), b"a", - "le second abonné démarre au début" + "the second subscriber starts at the beginning" ); } diff --git a/crates/rs-codec/src/ivf.rs b/crates/rs-codec/src/ivf.rs index 184e934..e4b4520 100644 --- a/crates/rs-codec/src/ivf.rs +++ b/crates/rs-codec/src/ivf.rs @@ -1,7 +1,7 @@ -//! Lecture d'un fichier IVF (VP8), pour rejouer un flux pré-encodé. +//! Reading an IVF (VP8) file, to replay a pre-encoded stream. //! -//! Sert au banc d'essai et aux tests de bout en bout: le vrai chemin de -//! production encode depuis les frames de `rs-capture`. +//! Used by the test bench and end-to-end tests: the real production path +//! encodes from `rs-capture` frames. use std::fs; use std::path::Path; @@ -9,7 +9,7 @@ use std::sync::Arc; use crate::frame::SharedFrames; -/// Fichier IVF chargé en mémoire, réutilisable par plusieurs sessions. +/// IVF file loaded in memory, reusable by several sessions. #[derive(Clone)] pub struct IvfFile { pub frames: Arc>>, @@ -63,7 +63,7 @@ impl IvfFile { while off + 12 <= data.len() { let size = u32::from_le_bytes([data[off], data[off + 1], data[off + 2], data[off + 3]]) as usize; - off += 12; // taille u32 + timestamp u64 + off += 12; // u32 size + u64 timestamp if size == 0 || off + size > data.len() { break; } @@ -81,7 +81,7 @@ impl IvfFile { }) } - /// Une source indépendante par session, qui partage les mêmes frames. + /// One independent source per session, sharing the same frames. pub fn source(&self) -> SharedFrames { SharedFrames::new(self.frames.clone(), self.fps, self.width, self.height) } @@ -89,13 +89,13 @@ impl IvfFile { #[derive(Debug, thiserror::Error, PartialEq, Eq)] pub enum IvfError { - #[error("lecture impossible de {path}: {reason}")] + #[error("cannot read {path}: {reason}")] Io { path: String, reason: String }, - #[error("ce fichier n'est pas un IVF (en-tête DKIF absent)")] + #[error("this file is not an IVF (DKIF header missing)")] NotIvf, - #[error("codec non pris en charge: {0} (attendu VP80)")] + #[error("unsupported codec: {0} (expected VP80)")] UnsupportedCodec(String), - #[error("aucune frame dans le fichier")] + #[error("no frame in the file")] NoFrames, } @@ -104,7 +104,7 @@ mod tests { use super::*; use crate::frame::FrameSource; - /// Construit un IVF minimal en mémoire, pour ne pas dépendre de ffmpeg. + /// Builds a minimal IVF in memory, so as not to depend on ffmpeg. fn tiny_ivf(frames: &[&[u8]], width: u16, height: u16, fps: u32) -> Vec { let mut out = Vec::new(); out.extend_from_slice(b"DKIF"); diff --git a/crates/rs-codec/src/lib.rs b/crates/rs-codec/src/lib.rs index d6e69a7..d8e665e 100644 --- a/crates/rs-codec/src/lib.rs +++ b/crates/rs-codec/src/lib.rs @@ -1,14 +1,14 @@ -//! Conversion de pixels, encodage vidéo et sources de frames. +//! Pixel conversion, video encoding and frame sources. //! -//! Le découpage assumé: une frame arrive en BGRA depuis `rs-capture`, elle est -//! convertie en I420 ([`color`]) puis encodée en VP8 ou VP9 ([`encoder`], sur -//! libvpx par une liaison directe), et le résultat sort par le trait -//! [`FrameSource`] consommé par `rs-rtc` ([`pipeline`] fait le pont). +//! The deliberate split: a frame arrives as BGRA from `rs-capture`, it is +//! converted to I420 ([`color`]) then encoded as VP8 or VP9 ([`encoder`], on +//! libvpx through a direct binding), and the result comes out through the +//! [`FrameSource`] trait consumed by `rs-rtc` ([`pipeline`] bridges the two). //! -//! L'encodeur matériel H.264 viendra derrière le même trait, sans toucher au -//! reste du pipeline (issue #53). +//! The hardware H.264 encoder will come behind the same trait, without +//! touching the rest of the pipeline (issue #53). //! -//! Dépendance de build: libvpx. Voir `scripts/build-libvpx.sh` et AGENTS.md. +//! Build dependency: libvpx. See `scripts/build-libvpx.sh` and AGENTS.md. pub mod color; pub mod encoder; diff --git a/crates/rs-codec/src/pipeline.rs b/crates/rs-codec/src/pipeline.rs index 5e78735..c6bb335 100644 --- a/crates/rs-codec/src/pipeline.rs +++ b/crates/rs-codec/src/pipeline.rs @@ -1,13 +1,13 @@ -//! Le pont entre la capture et les sessions: capture, conversion, encodage, et -//! livraison d'une frame encodée aux spectateurs. +//! The bridge between capture and sessions: capture, conversion, encoding, and +//! delivery of an encoded frame to the viewers. //! -//! **Une capture et un encodeur pour tout l'hôte, pas un par spectateur.** -//! Chaque abonné lit la même image publiée avec son propre curseur. Encoder -//! cinq fois la même image pour cinq spectateurs coûtait cinq cœurs: mesuré à -//! trois spectateurs en 720p, la cadence tombait à 16 i/s et la troisième -//! connexion échouait (voir `docs/perf.md`). +//! **One capture and one encoder for the whole host, not one per viewer.** +//! Each subscriber reads the same published image with its own cursor. +//! Encoding the same image five times for five viewers cost five cores: +//! measured with three viewers at 720p, the frame rate dropped to 16 fps and +//! the third connection failed (see `docs/perf.md`). //! -//! L'encodage vit dans son propre thread: la boucle RTP ne l'attend jamais. +//! Encoding lives in its own thread: the RTP loop never waits for it. use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; @@ -20,13 +20,13 @@ use crate::color::BgraFrame; use crate::encoder::{EncodeConfig, EncodeError, VideoEncoder}; use crate::frame::{FrameSource, SharedMedia}; -/// Ce que le thread d'encodage publie, et ce que les spectateurs lisent. +/// What the encoding thread publishes, and what the viewers read. #[derive(Default)] struct SharedOutput { frame: Mutex>, version: AtomicU64, - /// Demande d'image clé pour le prochain encodage: un spectateur qui arrive - /// en cours de flux ne peut pas décoder sans elle. + /// Keyframe request for the next encode: a viewer arriving mid-stream + /// cannot decode without one. keyframe: AtomicBool, captured: AtomicU64, encoded: AtomicU64, @@ -34,10 +34,10 @@ struct SharedOutput { encode_errors: AtomicU64, empty_frames: AtomicU64, subscribers: AtomicU64, - /// La capture est terminée pour de bon, et pourquoi. + /// The capture has ended for good, and why. ended: Mutex>, - /// Taille encodée courante, largeur dans les 32 bits hauts: elle suit la - /// source quand sa résolution change. + /// Current encoded size, width in the high 32 bits: it follows the source + /// when its resolution changes. dimensions: AtomicU64, resolution_changes: AtomicU64, } @@ -73,7 +73,7 @@ impl SharedOutput { } } -/// État d'une source en direct, pour les diagnostics. +/// State of a live source, for diagnostics. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct LiveStats { pub width: u32, @@ -83,18 +83,18 @@ pub struct LiveStats { pub encoded: u64, pub capture_errors: u64, pub encode_errors: u64, - /// Frames que l'encodeur a rendues vides (image non significative). + /// Frames the encoder returned empty (insignificant image). pub empty_frames: u64, - /// Spectateurs abonnés à cette source. + /// Viewers subscribed to this source. pub subscribers: u64, - /// Changements de résolution suivis depuis le démarrage. + /// Resolution changes followed since start. pub resolution_changes: u64, - /// La source a disparu (partage arrêté depuis le bureau, fenêtre fermée): - /// plus aucune image n'arrivera. + /// The source is gone (sharing stopped from the desktop, window closed): no + /// more images will arrive. pub ended: bool, } -/// Source en direct: une capture, un encodeur, autant de spectateurs qu'on veut. +/// Live source: one capture, one encoder, as many viewers as wanted. pub struct LiveSource { output: Arc, stop: Arc, @@ -103,7 +103,7 @@ pub struct LiveSource { } impl LiveSource { - /// Démarre la capture et l'encodage dans un thread dédié. + /// Starts capture and encoding in a dedicated thread. pub fn spawn(capturer: C, encoder: E) -> Self where C: ScreenCapturer + 'static, @@ -123,28 +123,28 @@ impl LiveSource { .spawn(move || { let mut capturer = capturer; let mut encoder = encoder; - // Chaque panne se dit une fois dans le journal: comptée en - // silence, une capture qui échoue à chaque image donne un écran - // noir chez le spectateur sans rien qui explique pourquoi. - let mut signale = Signale::default(); - let debut = Instant::now(); + // Each failure is logged once: counted silently, a capture that + // fails on every image gives the viewer a black screen with + // nothing explaining why. + let mut logged = Logged::default(); + let start = Instant::now(); while !worker_stop.load(Ordering::Relaxed) { - // Une demande d'image clé arrive quand un spectateur rejoint. + // A keyframe request arrives when a viewer joins. if worker_output.keyframe.swap(false, Ordering::Relaxed) { encoder.request_keyframe(); } let frame = match capturer.next_frame() { Ok(frame) => frame, - // Réessayer ne ramènera pas une source disparue ou une - // permission retirée: on s'arrête, et on dit pourquoi. + // Retrying will not bring back a vanished source or a + // withdrawn permission: stop, and say why. Err( error @ (CaptureError::SourceGone | CaptureError::PermissionDenied), ) => { tracing::warn!( - evenement = "capture_revoquee", + event = "capture_revoked", cause = %error, - "la source de capture a disparu" + "the capture source is gone" ); *worker_output .ended @@ -152,35 +152,35 @@ impl LiveSource { .unwrap_or_else(|e| e.into_inner()) = Some(error); break; } - Err(erreur) => { + Err(error) => { worker_output.capture_errors.fetch_add(1, Ordering::Relaxed); - if !signale.capture { - signale.capture = true; + if !logged.capture { + logged.capture = true; tracing::warn!( - evenement = "capture_en_erreur", - %erreur, - "la capture échoue: pas d'image à encoder" + event = "capture_failed", + %error, + "capture is failing: no image to encode" ); } - // Une source qui échoue en boucle ne doit pas saturer - // un cœur: on laisse respirer avant de réessayer. + // A source failing in a loop must not saturate a + // core: let it breathe before retrying. thread::sleep(Duration::from_millis(250)); continue; } }; worker_output.captured.fetch_add(1, Ordering::Relaxed); - // La source a changé de taille (résolution, rotation, - // fenêtre redimensionnée): on suit au lieu de rogner. - let actuelle = encoder.config(); - if (frame.width, frame.height) != (actuelle.width, actuelle.height) { - match encoder.reconfigurer(frame.width, frame.height) { + // The source changed size (resolution, rotation, window + // resized): follow it instead of cropping. + let current = encoder.config(); + if (frame.width, frame.height) != (current.width, current.height) { + match encoder.reconfigure(frame.width, frame.height) { Ok(()) => { tracing::info!( - evenement = "changement_resolution", - avant = ?(actuelle.width, actuelle.height), - apres = ?(frame.width, frame.height), - "l'encodeur suit la nouvelle taille de la source" + event = "resolution_changed", + before = ?(current.width, current.height), + after = ?(frame.width, frame.height), + "the encoder follows the new source size" ); worker_output .dimensions @@ -202,17 +202,17 @@ impl LiveSource { frame.height as usize, ) { Ok(view) => view, - Err(erreur) => { + Err(error) => { worker_output.encode_errors.fetch_add(1, Ordering::Relaxed); - if !signale.encodage { - signale.encodage = true; + if !logged.encode { + logged.encode = true; tracing::warn!( - evenement = "encodage_en_erreur", - %erreur, - largeur = frame.width, - hauteur = frame.height, - octets = frame.bgra.len(), - "image capturée inutilisable" + event = "encode_failed", + %error, + width = frame.width, + height = frame.height, + bytes = frame.bgra.len(), + "captured image unusable" ); } continue; @@ -225,15 +225,15 @@ impl LiveSource { for packet in packets { joined.extend_from_slice(&packet); } - if !signale.premiere { - signale.premiere = true; + if !logged.first { + logged.first = true; tracing::info!( - evenement = "premiere_image_encodee", - delai_ms = debut.elapsed().as_millis() as u64, - largeur = frame.width, - hauteur = frame.height, - octets = joined.len(), - "première image encodée" + event = "first_frame_encoded", + delay_ms = start.elapsed().as_millis() as u64, + width = frame.width, + height = frame.height, + bytes = joined.len(), + "first image encoded" ); } worker_output.publish(joined); @@ -242,21 +242,21 @@ impl LiveSource { Err(EncodeError::NoFrame) => { worker_output.empty_frames.fetch_add(1, Ordering::Relaxed); } - Err(erreur) => { + Err(error) => { worker_output.encode_errors.fetch_add(1, Ordering::Relaxed); - if !signale.encodage { - signale.encodage = true; + if !logged.encode { + logged.encode = true; tracing::warn!( - evenement = "encodage_en_erreur", - %erreur, - "l'encodeur refuse l'image" + event = "encode_failed", + %error, + "the encoder refuses the image" ); } } } } }) - .expect("thread d'encodage"); + .expect("encoding thread"); Self { output, @@ -283,7 +283,7 @@ impl LiveSource { } } - /// Pourquoi la capture s'est arrêtée, si elle l'est. + /// Why the capture stopped, if it did. pub fn ended(&self) -> Option { self.output .ended @@ -321,11 +321,11 @@ impl SharedMedia for LiveSource { } } -/// La vue d'un spectateur sur une source partagée. +/// One viewer's view on a shared source. /// -/// Deux spectateurs ont chacun la leur: ils avancent au même rythme sans se -/// voler de frames. Une frame déjà servie n'est pas renvoyée, pour ne pas -/// gaspiller de bande passante quand l'encodeur est en retard sur la cadence. +/// Two viewers each have their own: they advance at the same pace without +/// stealing frames from each other. A frame already served is not sent again, +/// so as not to waste bandwidth when the encoder lags behind the cadence. pub struct SourceView { output: Arc, config: EncodeConfig, @@ -367,18 +367,18 @@ impl Drop for LiveSource { fn drop(&mut self) { self.stop.store(true, Ordering::Relaxed); if let Some(handle) = self.worker.take() { - // Le thread peut être dans un sommeil de cadence (33 ms au pire). + // The thread may be in a cadence sleep (33 ms at worst). let _ = handle.join(); } } } -/// Ce que le thread d'encodage a déjà dit au journal, pour ne le dire qu'une fois. +/// What the encoding thread has already logged, to log it only once. #[derive(Default)] -struct Signale { +struct Logged { capture: bool, - encodage: bool, - premiere: bool, + encode: bool, + first: bool, } #[cfg(test)] @@ -416,7 +416,7 @@ mod tests { } thread::sleep(Duration::from_millis(20)); } - assert!(got_frame, "une frame encodée doit finir par être publiée"); + assert!(got_frame, "an encoded frame must eventually be published"); let stats = live.stats(); assert!(stats.captured > 0); assert!(stats.encoded > 0); @@ -435,7 +435,7 @@ mod tests { let elapsed = started.elapsed(); assert!( elapsed < Duration::from_millis(50), - "20 lectures ont pris {elapsed:?}: la session attend encore l'encodeur" + "20 reads took {elapsed:?}: the session still waits for the encoder" ); } @@ -458,16 +458,13 @@ mod tests { } thread::sleep(Duration::from_millis(10)); } - assert!( - a > 0 && b > 0, - "les deux spectateurs doivent recevoir des frames" - ); - // Un seul thread d'encodage: le compteur global ne double pas avec le - // nombre de spectateurs. + assert!(a > 0 && b > 0, "both viewers must receive frames"); + // A single encoding thread: the global counter does not double with + // the number of viewers. let stats = live.stats(); assert!( stats.encoded <= stats.captured, - "{} frames encodées pour {} capturées: plusieurs encodeurs", + "{} frames encoded for {} captured: several encoders", stats.encoded, stats.captured ); @@ -491,7 +488,7 @@ mod tests { assert_eq!(stats.fps, 30); } - /// Une source qui disparaît après quelques images. + /// A source that disappears after a few images. struct Fragile { inner: SyntheticCapturer, left: u32, @@ -535,47 +532,47 @@ mod tests { let stats = live.stats(); assert!(stats.ended); assert_eq!(stats.captured, 3); - // Pas de nouvelle tentative: le compteur d'erreurs ne grimpe pas. + // No retry: the error counter does not climb. assert_eq!(stats.capture_errors, 0); } - /// Une source dont la taille change après quelques images, comme un écran - /// dont on change la résolution. - struct Changeante { - petite: SyntheticCapturer, - grande: SyntheticCapturer, - avant: u32, + /// A source whose size changes after a few images, like a screen whose + /// resolution is changed. + struct Resizing { + small: SyntheticCapturer, + large: SyntheticCapturer, + before: u32, } - impl ScreenCapturer for Changeante { + impl ScreenCapturer for Resizing { fn sources(&mut self) -> Result, CaptureError> { - self.petite.sources() + self.small.sources() } fn start(&mut self, source: &SourceId) -> Result<(), CaptureError> { - self.petite.start(source)?; - self.grande.start(source) + self.small.start(source)?; + self.large.start(source) } fn next_frame(&mut self) -> Result { - if self.avant > 0 { - self.avant -= 1; - return self.petite.next_frame(); + if self.before > 0 { + self.before -= 1; + return self.small.next_frame(); } - self.grande.next_frame() + self.large.next_frame() } fn stop(&mut self) {} } #[test] fn a_resolution_change_reconfigures_without_stopping() { - changement_de_resolution(crate::encoder::VideoCodec::Vp8); - changement_de_resolution(crate::encoder::VideoCodec::Vp9); + resolution_change(crate::encoder::VideoCodec::Vp8); + resolution_change(crate::encoder::VideoCodec::Vp9); } - fn changement_de_resolution(codec: crate::encoder::VideoCodec) { - let mut capturer = Changeante { - petite: SyntheticCapturer::new(160, 96, 60), - grande: SyntheticCapturer::new(320, 192, 60), - avant: 5, + fn resolution_change(codec: crate::encoder::VideoCodec) { + let mut capturer = Resizing { + small: SyntheticCapturer::new(160, 96, 60), + large: SyntheticCapturer::new(320, 192, 60), + before: 5, }; capturer.start(&SourceId("synthetic".into())).unwrap(); let encoder = VpxEncoder::new(EncodeConfig { @@ -592,20 +589,20 @@ mod tests { while live.stats().resolution_changes == 0 && Instant::now() < deadline { thread::sleep(Duration::from_millis(10)); } - let changement = Instant::now(); + let changed_at = Instant::now(); assert_eq!(live.stats().resolution_changes, 1); assert_eq!(view.dimensions(), (320, 192)); - // Le flux reprend tout de suite: bien moins que les deux secondes du - // critère de #16. - let avant = live.stats().encoded; - while live.stats().encoded == avant && changement.elapsed() < Duration::from_secs(2) { + // The stream resumes right away: far less than the two seconds of the + // #16 criterion. + let before = live.stats().encoded; + while live.stats().encoded == before && changed_at.elapsed() < Duration::from_secs(2) { thread::sleep(Duration::from_millis(5)); } assert!( - live.stats().encoded > avant, - "{codec:?}: plus d'image après le changement" + live.stats().encoded > before, + "{codec:?}: no more images after the change" ); - assert!(changement.elapsed() < Duration::from_millis(500)); + assert!(changed_at.elapsed() < Duration::from_millis(500)); assert!(live.ended().is_none()); let _ = view.next_frame(); } @@ -617,7 +614,7 @@ mod tests { drop(live); assert!( started.elapsed() < Duration::from_secs(2), - "l'arrêt du thread d'encodage ne doit pas bloquer" + "stopping the encoding thread must not block" ); } } diff --git a/crates/rs-codec/src/vpx.rs b/crates/rs-codec/src/vpx.rs index 520e08e..dbd72ae 100644 --- a/crates/rs-codec/src/vpx.rs +++ b/crates/rs-codec/src/vpx.rs @@ -1,18 +1,17 @@ -//! Liaison directe avec libvpx, par `vpx-sys` (crate `env-libvpx-sys`). +//! Direct binding to libvpx, through `vpx-sys` (crate `env-libvpx-sys`). //! -//! Tout le code `unsafe` de l'encodage vit ici, et seulement ici. Le reste du -//! crate voit un [`Contexte`] sûr: ouvrir, encoder une image I420, forcer une -//! image clé, fermer. +//! All the `unsafe` encoding code lives here, and only here. The rest of the +//! crate sees a safe [`Context`]: open, encode an I420 image, force a +//! keyframe, close. //! -//! Pourquoi ne plus passer par `vpx-encode`: il ne règle ni `g_lag_in_frames` -//! (25 images en file pour VP9, soit le premier paquet à la frame 24, environ -//! 800 ms à 30 i/s), ni le drapeau `VPX_EFLAG_FORCE_KF` (on rouvrait -//! l'encodeur pour obtenir une image clé, en jetant l'état de prédiction). -//! Voir l'issue #67. +//! Why we no longer go through `vpx-encode`: it controls neither +//! `g_lag_in_frames` (25 queued frames for VP9, i.e. the first packet at frame +//! 24, about 800 ms at 30 fps), nor the `VPX_EFLAG_FORCE_KF` flag (we reopened +//! the encoder to get a keyframe, throwing away the prediction state). See +//! issue #67. //! -//! Les réglages suivent ceux de libwebrtc pour le temps réel: aucune image en -//! file, débit constant, tampon court, vitesse élevée, multithread par lignes -//! pour VP9. +//! The settings follow libwebrtc's real-time ones: no queued frame, constant +//! bitrate, short buffer, high speed, row multithreading for VP9. use std::ffi::CStr; use std::mem::MaybeUninit; @@ -34,124 +33,124 @@ use vpx_sys::{ use crate::encoder::VideoCodec; -/// Vitesse VP9 (`VP8E_SET_CPUUSED`). +/// VP9 speed (`VP8E_SET_CPUUSED`). /// -/// **Ni 6, ni le réglage « contenu écran ».** libvpx 1.13.0 et 1.13.1, celles -/// que construit `nix/libvpx.nix`, plantent (lecture hors limites dans -/// `vp9_get_mvpred_var`, depuis `vp9_pick_inter_mode`) dès que l'image bouge: -/// à la vitesse 6 quel que soit le contenu animé, et avec -/// `VP9E_SET_TUNE_CONTENT = SCREEN` à toutes les vitesses. Reproduit en C pur, -/// donc indépendant de cette liaison; absent de libvpx 1.14 (Ubuntu) et 1.17 -/// (nixpkgs) sur les mêmes images. Le 6 est justement ce qu'utilisait -/// `vpx-encode`. Détail et mesures dans `docs/perf.md` et l'issue #67. -/// Le test `vp9_survives_moving_content` garde cette valeur. -const VITESSE_VP9: c_int = 7; +/// **Neither 6, nor the "screen content" setting.** libvpx 1.13.0 and 1.13.1, +/// the ones `nix/libvpx.nix` builds, crash (out-of-bounds read in +/// `vp9_get_mvpred_var`, from `vp9_pick_inter_mode`) as soon as the image +/// moves: at speed 6 with any animated content, and with +/// `VP9E_SET_TUNE_CONTENT = SCREEN` at every speed. Reproduced in plain C, so +/// independent of this binding; absent from libvpx 1.14 (Ubuntu) and 1.17 +/// (nixpkgs) on the same images. 6 is precisely what `vpx-encode` used. +/// Details and measurements in `docs/perf.md` and issue #67. +/// The `vp9_survives_moving_content` test guards this value. +const VP9_SPEED: c_int = 7; -/// Erreur rendue par libvpx, avec son message. +/// Error returned by libvpx, with its message. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] -#[error("{appel}: {message}")] +#[error("{call}: {message}")] pub struct VpxError { - pub appel: &'static str, + pub call: &'static str, pub message: String, } -/// Ce qu'il faut pour ouvrir un encodeur. +/// What it takes to open an encoder. #[derive(Debug, Clone, Copy)] -pub struct Reglages { +pub struct EncoderSettings { pub codec: VideoCodec, pub width: u32, pub height: u32, pub fps: u32, pub bitrate_kbps: u32, pub threads: u32, - /// Faire calculer le PSNR de chaque image par libvpx. Coûte du calcul: - /// réservé aux bancs d'essai. + /// Have libvpx compute the PSNR of each image. Costs computation: + /// reserved for benchmarks. pub psnr: bool, } -/// Une image encodée. +/// An encoded image. #[derive(Debug, Clone)] -pub struct Paquet { +pub struct Packet { pub data: Vec, pub keyframe: bool, } -/// Un encodeur libvpx ouvert. Fermé au `Drop`. -pub struct Contexte { - /// En boîte: l'adresse du contexte reste stable même si `Contexte` bouge. +/// An open libvpx encoder. Closed on `Drop`. +pub struct Context { + /// Boxed: the context address stays stable even if `Context` moves. ctx: Box, width: u32, height: u32, - /// PSNR global de la dernière image, si demandé à l'ouverture. + /// Global PSNR of the last image, if requested at open time. psnr: Option, } -// SAFETY: `vpx_codec_ctx_t` ne contient que des pointeurs vers la mémoire -// propre de l'encodeur, sans affinité de thread (libvpx ne garde aucun état -// lié au thread appelant). `Contexte` n'est jamais partagé (`!Sync`) et toutes -// ses méthodes prennent `&mut self`: un seul thread l'utilise à la fois. -unsafe impl Send for Contexte {} +// SAFETY: `vpx_codec_ctx_t` only holds pointers to the encoder's own memory, +// with no thread affinity (libvpx keeps no state tied to the calling thread). +// `Context` is never shared (`!Sync`) and all its methods take `&mut self`: +// only one thread uses it at a time. +unsafe impl Send for Context {} -impl std::fmt::Debug for Contexte { +impl std::fmt::Debug for Context { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("Contexte") + f.debug_struct("Context") .field("width", &self.width) .field("height", &self.height) .finish() } } -fn message_erreur(err: vpx_codec_err_t) -> String { - // SAFETY: `vpx_codec_err_to_string` rend toujours une chaîne statique - // terminée par un zéro, jamais un pointeur nul. +fn error_message(err: vpx_codec_err_t) -> String { + // SAFETY: `vpx_codec_err_to_string` always returns a static + // NUL-terminated string, never a null pointer. unsafe { CStr::from_ptr(vpx_codec_err_to_string(err)) } .to_string_lossy() .into_owned() } -impl Contexte { - pub fn ouvrir(reglages: &Reglages) -> Result { - let iface: *const vpx_codec_iface_t = match reglages.codec { - // SAFETY: fonctions sans argument qui rendent un pointeur vers une - // table statique de libvpx. +impl Context { + pub fn open(settings: &EncoderSettings) -> Result { + let iface: *const vpx_codec_iface_t = match settings.codec { + // SAFETY: argument-less functions returning a pointer to a static + // libvpx table. VideoCodec::Vp8 => unsafe { vpx_codec_vp8_cx() }, - // SAFETY: idem. + // SAFETY: same. VideoCodec::Vp9 => unsafe { vpx_codec_vp9_cx() }, }; if iface.is_null() { return Err(VpxError { - appel: "vpx_codec_vp*_cx", - message: "libvpx compilée sans cet encodeur".into(), + call: "vpx_codec_vp*_cx", + message: "libvpx built without this encoder".into(), }); } let mut cfg = MaybeUninit::::uninit(); - // SAFETY: `iface` est valide, et `vpx_codec_enc_config_default` écrit - // la structure entière (copie de la configuration par défaut) quand il - // rend `VPX_CODEC_OK`. + // SAFETY: `iface` is valid, and `vpx_codec_enc_config_default` writes + // the whole structure (a copy of the default configuration) when it + // returns `VPX_CODEC_OK`. let err = unsafe { vpx_codec_enc_config_default(iface, cfg.as_mut_ptr(), 0) }; if err != vpx_codec_err_t::VPX_CODEC_OK { return Err(VpxError { - appel: "vpx_codec_enc_config_default", - message: message_erreur(err), + call: "vpx_codec_enc_config_default", + message: error_message(err), }); } - // SAFETY: initialisée par l'appel précédent, qui a réussi. + // SAFETY: initialized by the previous call, which succeeded. let mut cfg = unsafe { cfg.assume_init() }; - configurer(&mut cfg, reglages); + configure(&mut cfg, settings); - // SAFETY: une structure C faite de pointeurs, d'un entier et d'une - // énumération dont zéro est une valeur valide (`VPX_CODEC_OK`): l'état - // tout à zéro est celui qu'attend `vpx_codec_enc_init_ver`. + // SAFETY: a C structure made of pointers, an integer and an enum for + // which zero is a valid value (`VPX_CODEC_OK`): the all-zero state is + // what `vpx_codec_enc_init_ver` expects. let mut ctx: Box = Box::new(unsafe { std::mem::zeroed() }); - // SAFETY: `ctx`, `iface` et `cfg` sont valides pendant l'appel; libvpx - // copie `cfg` dans son état privé et ne garde pas notre pointeur. + // SAFETY: `ctx`, `iface` and `cfg` are valid during the call; libvpx + // copies `cfg` into its private state and does not keep our pointer. let err = unsafe { vpx_codec_enc_init_ver( &mut *ctx, iface, &cfg, - if reglages.psnr { + if settings.psnr { vpx_sys::VPX_CODEC_USE_PSNR as vpx_sys::vpx_codec_flags_t } else { 0 @@ -160,115 +159,111 @@ impl Contexte { ) }; if err != vpx_codec_err_t::VPX_CODEC_OK { - // Rien à détruire: un échec d'initialisation libère ce qu'il avait - // alloué et laisse `ctx.priv_` nul. + // Nothing to destroy: a failed initialization frees what it had + // allocated and leaves `ctx.priv_` null. return Err(VpxError { - appel: "vpx_codec_enc_init_ver", - message: message_erreur(err), + call: "vpx_codec_enc_init_ver", + message: error_message(err), }); } - let mut contexte = Self { + let mut context = Self { ctx, - width: reglages.width, - height: reglages.height, + width: settings.width, + height: settings.height, psnr: None, }; - contexte.controler(reglages)?; - Ok(contexte) + context.apply_controls(settings)?; + Ok(context) } - fn controle( - &mut self, - id: vpx_sys::vp8e_enc_control_id, - valeur: c_int, - ) -> Result<(), VpxError> { - // SAFETY: le contexte est initialisé; tous les contrôles utilisés ici - // attendent un `int` en argument variadique, ce qu'on passe. - let err = unsafe { vpx_sys::vpx_codec_control_(&mut *self.ctx, id as c_int, valeur) }; + fn control(&mut self, id: vpx_sys::vp8e_enc_control_id, value: c_int) -> Result<(), VpxError> { + // SAFETY: the context is initialized; every control used here expects + // an `int` as variadic argument, which is what we pass. + let err = unsafe { vpx_sys::vpx_codec_control_(&mut *self.ctx, id as c_int, value) }; if err != vpx_codec_err_t::VPX_CODEC_OK { - let mut erreur = self.erreur("vpx_codec_control", err); - erreur.message = format!("{id:?}: {}", erreur.message); - return Err(erreur); + let mut error = self.error("vpx_codec_control", err); + error.message = format!("{id:?}: {}", error.message); + return Err(error); } Ok(()) } - fn controler(&mut self, reglages: &Reglages) -> Result<(), VpxError> { - match reglages.codec { + fn apply_controls(&mut self, settings: &EncoderSettings) -> Result<(), VpxError> { + match settings.codec { VideoCodec::Vp8 => { - // Négatif: vitesse fixe, sans adaptation au temps restant. - // -6 est la valeur de libwebrtc pour VP8 sur un ordinateur. - self.controle(VP8E_SET_CPUUSED, -6)?; - self.controle(VP8E_SET_NOISE_SENSITIVITY, 0)?; - // Un bureau est surtout immobile: les blocs inchangés sont - // sautés au lieu d'être réencodés. - self.controle(VP8E_SET_STATIC_THRESHOLD, 1)?; - self.controle(VP8E_SET_SCREEN_CONTENT_MODE, 1)?; + // Negative: fixed speed, without adapting to the time left. + // -6 is libwebrtc's value for VP8 on a desktop computer. + self.control(VP8E_SET_CPUUSED, -6)?; + self.control(VP8E_SET_NOISE_SENSITIVITY, 0)?; + // A desktop is mostly still: unchanged blocks are skipped + // instead of being re-encoded. + self.control(VP8E_SET_STATIC_THRESHOLD, 1)?; + self.control(VP8E_SET_SCREEN_CONTENT_MODE, 1)?; } VideoCodec::Vp9 => { - // Voir `VITESSE_VP9`: la valeur n'est pas libre avec libvpx - // 1.13, et `VP9E_SET_TUNE_CONTENT` (écran) est volontairement - // absent pour la même raison. - self.controle(VP8E_SET_CPUUSED, VITESSE_VP9)?; - self.controle(VP9E_SET_ROW_MT, 1)?; - self.controle(VP9E_SET_TILE_COLUMNS, colonnes_log2(reglages))?; - // Rafraîchissement cyclique: libère du débit sur les zones - // fixes sans images clés périodiques coûteuses. - self.controle(VP9E_SET_AQ_MODE, 3)?; - self.controle(VP9E_SET_NOISE_SENSITIVITY, 0)?; + // See `VP9_SPEED`: the value is not free with libvpx 1.13, and + // `VP9E_SET_TUNE_CONTENT` (screen) is deliberately absent for + // the same reason. + self.control(VP8E_SET_CPUUSED, VP9_SPEED)?; + self.control(VP9E_SET_ROW_MT, 1)?; + self.control(VP9E_SET_TILE_COLUMNS, tile_columns_log2(settings))?; + // Cyclic refresh: frees bitrate on static areas without + // costly periodic keyframes. + self.control(VP9E_SET_AQ_MODE, 3)?; + self.control(VP9E_SET_NOISE_SENSITIVITY, 0)?; } } - // Une image clé ne doit pas engloutir le tampon de plusieurs images: - // elle arrive justement quand un spectateur rejoint. Formule de - // libwebrtc: la moitié du tampon optimal (600 ms), en pourcentage du - // débit d'une image, et jamais moins de trois images. - let plafond = (reglages.fps.max(1) * 30).clamp(300, 3000) as c_int; - self.controle(VP8E_SET_MAX_INTRA_BITRATE_PCT, plafond)?; + // A keyframe must not swallow the buffer of several frames: it comes + // precisely when a viewer joins. libwebrtc's formula: half the optimal + // buffer (600 ms), as a percentage of one frame's bitrate, and never + // less than three frames. + let cap = (settings.fps.max(1) * 30).clamp(300, 3000) as c_int; + self.control(VP8E_SET_MAX_INTRA_BITRATE_PCT, cap)?; Ok(()) } - fn erreur(&mut self, appel: &'static str, err: vpx_codec_err_t) -> VpxError { - // SAFETY: le contexte est initialisé. `vpx_codec_error` rend une chaîne - // non nulle; `vpx_codec_error_detail` peut rendre nul, vérifié. - let (texte, detail) = unsafe { - let texte = CStr::from_ptr(vpx_codec_error(&mut *self.ctx)) + fn error(&mut self, call: &'static str, err: vpx_codec_err_t) -> VpxError { + // SAFETY: the context is initialized. `vpx_codec_error` returns a + // non-null string; `vpx_codec_error_detail` may return null, checked. + let (text, detail) = unsafe { + let text = CStr::from_ptr(vpx_codec_error(&mut *self.ctx)) .to_string_lossy() .into_owned(); let detail = vpx_codec_error_detail(&mut *self.ctx); let detail = (!detail.is_null()).then(|| CStr::from_ptr(detail).to_string_lossy().into_owned()); - (texte, detail) + (text, detail) }; let message = match detail { - Some(detail) => format!("{texte} ({}): {detail}", message_erreur(err)), - None => format!("{texte} ({})", message_erreur(err)), + Some(detail) => format!("{text} ({}): {detail}", error_message(err)), + None => format!("{text} ({})", error_message(err)), }; - VpxError { appel, message } + VpxError { call, message } } - /// Encode une image I420 contiguë (Y, puis U, puis V, sans marge) et rend - /// les paquets produits. Avec `g_lag_in_frames = 0`, une image en entrée - /// donne une image en sortie, sauf saut décidé par le contrôle de débit. - pub fn encoder( + /// Encodes a contiguous I420 image (Y, then U, then V, without padding) + /// and returns the packets produced. With `g_lag_in_frames = 0`, one image + /// in gives one image out, unless the rate control decides to skip. + pub fn encode( &mut self, i420: &[u8], pts: i64, - image_cle: bool, - ) -> Result, VpxError> { + keyframe: bool, + ) -> Result, VpxError> { let (w, h) = (self.width as usize, self.height as usize); - let attendu = w * h + 2 * (w / 2) * (h / 2); - if i420.len() < attendu { + let expected = w * h + 2 * (w / 2) * (h / 2); + if i420.len() < expected { return Err(VpxError { - appel: "vpx_codec_encode", - message: format!("image I420 de {} octets, {attendu} attendus", i420.len()), + call: "vpx_codec_encode", + message: format!("I420 image of {} bytes, {expected} expected", i420.len()), }); } let mut image = MaybeUninit::::uninit(); - // SAFETY: `vpx_img_wrap` remet la structure à zéro puis la remplit, sans - // allouer: elle pointe vers `i420`, qui vit jusqu'à la fin de la - // fonction et dont la taille vient d'être vérifiée. libvpx ne fait que - // lire l'image source (le `*mut` vient de la signature C). + // SAFETY: `vpx_img_wrap` zeroes the structure then fills it, without + // allocating: it points to `i420`, which lives until the end of the + // function and whose size was just checked. libvpx only reads the + // source image (the `*mut` comes from the C signature). let wrapped = unsafe { vpx_img_wrap( image.as_mut_ptr(), @@ -281,58 +276,59 @@ impl Contexte { }; if wrapped.is_null() { return Err(VpxError { - appel: "vpx_img_wrap", - message: "format ou dimensions refusés".into(), + call: "vpx_img_wrap", + message: "format or dimensions refused".into(), }); } - let drapeaux = if image_cle { + let flags = if keyframe { vpx_sys::VPX_EFLAG_FORCE_KF as vpx_sys::vpx_enc_frame_flags_t } else { 0 }; - // SAFETY: contexte initialisé, image valide (voir plus haut). L'encodeur - // a fini de lire l'image au retour de l'appel: sans file d'attente, il - // ne garde aucune référence vers `i420`. + // SAFETY: initialized context, valid image (see above). The encoder + // has finished reading the image when the call returns: with no lag + // queue, it keeps no reference to `i420`. let err = unsafe { vpx_codec_encode( &mut *self.ctx, wrapped, pts, 1, - drapeaux, + flags, vpx_sys::VPX_DL_REALTIME as c_ulong, ) }; if err != vpx_codec_err_t::VPX_CODEC_OK { - return Err(self.erreur("vpx_codec_encode", err)); + return Err(self.error("vpx_codec_encode", err)); } - let mut paquets = Vec::new(); + let mut packets = Vec::new(); let mut iter: vpx_codec_iter_t = ptr::null(); loop { - // SAFETY: contexte initialisé, `iter` part de nul comme l'exige - // l'API. Le paquet rendu reste valide jusqu'au prochain appel à - // `vpx_codec_get_cx_data` ou `vpx_codec_encode`: on le copie avant. + // SAFETY: initialized context, `iter` starts null as the API + // requires. The returned packet stays valid until the next call + // to `vpx_codec_get_cx_data` or `vpx_codec_encode`: we copy it + // before that. let pkt = unsafe { vpx_codec_get_cx_data(&mut *self.ctx, &mut iter) }; if pkt.is_null() { break; } - // SAFETY: pointeur non nul rendu par libvpx, voir plus haut. + // SAFETY: non-null pointer returned by libvpx, see above. let pkt = unsafe { &*pkt }; if pkt.kind == vpx_codec_cx_pkt_kind::VPX_CODEC_PSNR_PKT { - // SAFETY: `kind` vaut `VPX_CODEC_PSNR_PKT`, donc le membre - // `psnr` de l'union est celui qui est écrit. L'indice 0 est le - // PSNR des trois plans réunis. + // SAFETY: `kind` is `VPX_CODEC_PSNR_PKT`, so the `psnr` member + // of the union is the one written. Index 0 is the PSNR of the + // three planes combined. self.psnr = Some(unsafe { pkt.data.psnr.psnr[0] }); continue; } if pkt.kind != vpx_codec_cx_pkt_kind::VPX_CODEC_CX_FRAME_PKT { continue; } - // SAFETY: `kind` vaut `VPX_CODEC_CX_FRAME_PKT`, donc le membre - // `frame` de l'union est celui qui est écrit; `buf` pointe vers - // `sz` octets possédés par l'encodeur. + // SAFETY: `kind` is `VPX_CODEC_CX_FRAME_PKT`, so the `frame` + // member of the union is the one written; `buf` points to `sz` + // bytes owned by the encoder. let (data, flags) = unsafe { let frame = pkt.data.frame; let data = if frame.buf.is_null() || frame.sz == 0 { @@ -345,49 +341,50 @@ impl Contexte { if data.is_empty() { continue; } - paquets.push(Paquet { + packets.push(Packet { data, keyframe: flags & vpx_sys::VPX_FRAME_IS_KEY != 0, }); } - Ok(paquets) + Ok(packets) } } -impl Contexte { - /// PSNR de la dernière image encodée, en dB, si demandé à l'ouverture. +impl Context { + /// PSNR of the last encoded image, in dB, if requested at open time. pub fn psnr(&self) -> Option { self.psnr } } -impl Drop for Contexte { +impl Drop for Context { fn drop(&mut self) { - // SAFETY: le contexte a été initialisé avec succès dans `ouvrir` (sinon - // `Contexte` n'existe pas) et n'est détruit qu'une fois, ici. + // SAFETY: the context was successfully initialized in `open` + // (otherwise `Context` does not exist) and is destroyed only once, + // here. let err = unsafe { vpx_codec_destroy(&mut *self.ctx) }; if err != vpx_codec_err_t::VPX_CODEC_OK { - tracing::warn!(erreur = %message_erreur(err), "fermeture de l'encodeur libvpx"); + tracing::warn!(error = %error_message(err), "closing the libvpx encoder"); } } } -/// Configuration temps réel, appliquée sur la configuration par défaut. -fn configurer(cfg: &mut vpx_codec_enc_cfg_t, reglages: &Reglages) { - cfg.g_w = reglages.width; - cfg.g_h = reglages.height; +/// Real-time configuration, applied on top of the default configuration. +fn configure(cfg: &mut vpx_codec_enc_cfg_t, settings: &EncoderSettings) { + cfg.g_w = settings.width; + cfg.g_h = settings.height; cfg.g_timebase.num = 1; - cfg.g_timebase.den = reglages.fps.max(1) as c_int; - cfg.g_threads = reglages.threads.max(1); + cfg.g_timebase.den = settings.fps.max(1) as c_int; + cfg.g_threads = settings.threads.max(1); cfg.g_pass = vpx_enc_pass::VPX_RC_ONE_PASS; - // Le cœur de #67: aucune image gardée en file. Sans cela, VP9 en garde 25. + // The heart of #67: no queued frame. Without this, VP9 keeps 25. cfg.g_lag_in_frames = 0; - // Un paquet perdu ne doit pas corrompre les images suivantes. + // A lost packet must not corrupt the following images. cfg.g_error_resilient = vpx_sys::VPX_ERROR_RESILIENT_DEFAULT; cfg.rc_end_usage = vpx_rc_mode::VPX_CBR; - cfg.rc_target_bitrate = reglages.bitrate_kbps.max(1); - // Bornes et tampon de libwebrtc: un débit tenu sur une seconde, pas sur - // dix, pour qu'une rafale ne remplisse pas la file réseau. + cfg.rc_target_bitrate = settings.bitrate_kbps.max(1); + // libwebrtc's bounds and buffer: a bitrate held over one second, not ten, + // so that a burst does not fill the network queue. cfg.rc_min_quantizer = 2; cfg.rc_max_quantizer = 56; cfg.rc_undershoot_pct = 50; @@ -395,25 +392,25 @@ fn configurer(cfg: &mut vpx_codec_enc_cfg_t, reglages: &Reglages) { cfg.rc_buf_initial_sz = 500; cfg.rc_buf_optimal_sz = 600; cfg.rc_buf_sz = 1000; - // Pas de saut d'image décidé par l'encodeur: la cadence est celle du - // pipeline, et une image identique coûte presque rien. + // No frame dropping decided by the encoder: the cadence is the pipeline's, + // and an identical image costs almost nothing. cfg.rc_dropframe_thresh = 0; cfg.rc_resize_allowed = 0; - // Une image clé de secours toutes les cinq secondes au plus (le défaut de - // libvpx est de 128 images): les demandes explicites (spectateur qui - // rejoint) passent par `VPX_EFLAG_FORCE_KF`. + // A fallback keyframe every five seconds at most (libvpx's default is 128 + // frames): explicit requests (a viewer joining) go through + // `VPX_EFLAG_FORCE_KF`. cfg.kf_mode = vpx_kf_mode::VPX_KF_AUTO; cfg.kf_min_dist = 0; - cfg.kf_max_dist = reglages.fps.max(1) * 5; + cfg.kf_max_dist = settings.fps.max(1) * 5; } -/// Colonnes de tuiles VP9, en log2: une par fil, et au moins 256 pixels de -/// large chacune (minimum imposé par le format). -fn colonnes_log2(reglages: &Reglages) -> c_int { +/// VP9 tile columns, as log2: one per thread, and each at least 256 pixels +/// wide (minimum imposed by the format). +fn tile_columns_log2(settings: &EncoderSettings) -> c_int { let mut log2 = 0; while log2 < 6 - && (1u32 << (log2 + 1)) <= reglages.threads.max(1) - && reglages.width >> (log2 + 1) >= 256 + && (1u32 << (log2 + 1)) <= settings.threads.max(1) + && settings.width >> (log2 + 1) >= 256 { log2 += 1; } @@ -424,8 +421,8 @@ fn colonnes_log2(reglages: &Reglages) -> c_int { mod tests { use super::*; - fn reglages(width: u32, threads: u32) -> Reglages { - Reglages { + fn settings(width: u32, threads: u32) -> EncoderSettings { + EncoderSettings { codec: VideoCodec::Vp9, width, height: 720, @@ -436,10 +433,10 @@ mod tests { } } - /// Les liaisons de `env-libvpx-sys` sont pré-générées: si elles ne - /// décrivent pas les mêmes structures que la libvpx liée, libvpx écrit - /// hors de nos tampons sans rien dire. Tailles relevées sur les en-têtes - /// C de libvpx 1.13.0 (identiques en 1.14 et 1.17), x86_64. + /// The `env-libvpx-sys` bindings are pre-generated: if they do not describe + /// the same structures as the linked libvpx, libvpx writes outside our + /// buffers silently. Sizes taken from the C headers of libvpx 1.13.0 + /// (identical in 1.14 and 1.17), x86_64. #[test] #[cfg(target_pointer_width = "64")] fn bindings_match_the_c_layout() { @@ -449,26 +446,26 @@ mod tests { assert_eq!(std::mem::size_of::(), 136); } - /// Image I420 de bureau qui défile: des bandes de texte qui glissent - /// horizontalement. C'est ce contenu qui fait planter libvpx 1.13 à la - /// vitesse 6 (voir `VITESSE_VP9`). - fn i420_qui_defile(width: usize, height: usize, t: usize, out: &mut Vec) { + /// A scrolling desktop I420 image: bands of text sliding horizontally. + /// This is the content that crashes libvpx 1.13 at speed 6 (see + /// `VP9_SPEED`). + fn scrolling_i420(width: usize, height: usize, t: usize, out: &mut Vec) { out.clear(); for y in 0..height { for x in 0..width { - let texte = ((x + t * 7) / 9).is_multiple_of(4) && (y / 16).is_multiple_of(2); - out.push(if texte { 20 } else { 230 }); + let text = ((x + t * 7) / 9).is_multiple_of(4) && (y / 16).is_multiple_of(2); + out.push(if text { 20 } else { 230 }); } } out.resize(width * height + 2 * (width / 2) * (height / 2), 128); } - /// Garde-fou de `VITESSE_VP9`: avec la vitesse 6, ce test fait tomber - /// le processus de test (SIGSEGV) avec la libvpx du dépôt. + /// Guard for `VP9_SPEED`: at speed 6, this test brings down the test + /// process (SIGSEGV) with the repository's libvpx. #[test] fn vp9_survives_moving_content() { let (w, h) = (1280, 720); - let mut contexte = Contexte::ouvrir(&Reglages { + let mut context = Context::open(&EncoderSettings { codec: VideoCodec::Vp9, width: w, height: h, @@ -477,28 +474,28 @@ mod tests { threads: 4, psnr: false, }) - .expect("ouverture"); + .expect("open"); let mut image = Vec::new(); for t in 0..90 { - i420_qui_defile(w as usize, h as usize, t, &mut image); - let paquets = contexte.encoder(&image, t as i64, false).expect("encodage"); - assert_eq!(paquets.len(), 1, "image {t}"); + scrolling_i420(w as usize, h as usize, t, &mut image); + let packets = context.encode(&image, t as i64, false).expect("encode"); + assert_eq!(packets.len(), 1, "image {t}"); } } #[test] fn tile_columns_respect_the_minimum_width() { - assert_eq!(colonnes_log2(®lages(1280, 1)), 0); - assert_eq!(colonnes_log2(®lages(1280, 4)), 2); - assert_eq!(colonnes_log2(®lages(1280, 16)), 2); - assert_eq!(colonnes_log2(®lages(320, 8)), 0); - assert_eq!(colonnes_log2(®lages(1920, 8)), 2); + assert_eq!(tile_columns_log2(&settings(1280, 1)), 0); + assert_eq!(tile_columns_log2(&settings(1280, 4)), 2); + assert_eq!(tile_columns_log2(&settings(1280, 16)), 2); + assert_eq!(tile_columns_log2(&settings(320, 8)), 0); + assert_eq!(tile_columns_log2(&settings(1920, 8)), 2); } #[test] fn a_short_buffer_is_refused_without_calling_libvpx() { - let mut contexte = Contexte::ouvrir(®lages(320, 1)).expect("ouverture"); - let err = contexte.encoder(&[0; 10], 0, false).unwrap_err(); - assert_eq!(err.appel, "vpx_codec_encode"); + let mut context = Context::open(&settings(320, 1)).expect("open"); + let err = context.encode(&[0; 10], 0, false).unwrap_err(); + assert_eq!(err.call, "vpx_codec_encode"); } } diff --git a/crates/rs-diag/Cargo.toml b/crates/rs-diag/Cargo.toml index bce99c8..74fd524 100644 --- a/crates/rs-diag/Cargo.toml +++ b/crates/rs-diag/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rs-diag" -description = "Journalisation structurée locale et archive de diagnostics, sans télémétrie." +description = "Local structured logging and a diagnostics archive, with no telemetry." version.workspace = true edition.workspace = true rust-version.workspace = true @@ -15,6 +15,6 @@ tracing.workspace = true tracing-subscriber = { version = "0.3.23", features = ["env-filter", "json"] } tracing-appender = "0.2.5" if-addrs = "0.15.0" -# Deflate en pur Rust, sans chiffrement ni autres compressions: une archive que -# n'importe quel système sait ouvrir (ADR 0008). +# Pure Rust deflate, with no encryption or other compression: an archive any +# system can open (ADR 0008). zip = { version = "9.1.2", default-features = false, features = ["deflate-flate2-zlib-rs"] } diff --git a/crates/rs-diag/src/archive.rs b/crates/rs-diag/src/archive.rs index 8c7d360..dac2ad9 100644 --- a/crates/rs-diag/src/archive.rs +++ b/crates/rs-diag/src/archive.rs @@ -1,9 +1,9 @@ -//! L'archive de diagnostics: un zip, un manifeste, des journaux expurgés. +//! The diagnostics archive: a zip, a manifest, redacted logs. //! -//! Ce qu'elle contient est fermé: `manifest.json` et `logs/*.log`, rien -//! d'autre. Pas d'image, pas de titre de fenêtre, pas d'adresse MAC (ADR 0008). -//! Le contenu est construit en mémoire puis écrit d'un bloc: la même archive -//! sert au fichier de `--diagnostics` et au téléchargement du tableau de bord. +//! Its content is closed: `manifest.json` and `logs/*.log`, nothing else. No +//! image, no window title, no MAC address (ADR 0008). The content is built in +//! memory then written in one go: the same archive serves the `--diagnostics` +//! file and the dashboard download. use std::collections::BTreeMap; use std::io::{Cursor, Read, Seek, Write}; @@ -14,184 +14,180 @@ use serde::Serialize; use zip::write::SimpleFileOptions; use crate::DiagError; -use crate::expurger::expurger; -use crate::journal::PREFIXE; +use crate::log::FILE_PREFIX; +use crate::redact::redact; -/// Plafond des journaux embarqués: une archive doit pouvoir partir par -/// courriel. Les plus récents passent en premier. -pub const PLAFOND_JOURNAUX: u64 = 5 * 1024 * 1024; +/// Cap on the embedded logs: an archive must be small enough to go by email. +/// The newest go first. +pub const LOG_CAP_BYTES: u64 = 5 * 1024 * 1024; -/// Le système hôte, sans rien d'identifiant. +/// The host system, with nothing identifying. #[derive(Debug, Clone, Serialize)] -pub struct Systeme { +pub struct SystemInfo { pub os: String, - /// `PRETTY_NAME` de `/etc/os-release`, quand il existe. + /// `PRETTY_NAME` from `/etc/os-release`, when it exists. pub distribution: Option, - pub noyau: Option, + pub kernel: Option, pub architecture: String, - pub processeurs: usize, + pub cpus: usize, } -impl Systeme { - pub fn detecter() -> Self { +impl SystemInfo { + pub fn detect() -> Self { let distribution = std::fs::read_to_string("/etc/os-release") .ok() - .and_then(|texte| { - texte.lines().find_map(|l| { + .and_then(|text| { + text.lines().find_map(|l| { l.strip_prefix("PRETTY_NAME=") .map(|v| v.trim_matches('"').to_string()) }) }); - let noyau = std::fs::read_to_string("/proc/sys/kernel/osrelease") + let kernel = std::fs::read_to_string("/proc/sys/kernel/osrelease") .ok() .map(|v| v.trim().to_string()); Self { os: std::env::consts::OS.to_string(), distribution, - noyau, + kernel, architecture: std::env::consts::ARCH.to_string(), - processeurs: std::thread::available_parallelism().map_or(1, |n| n.get()), + cpus: std::thread::available_parallelism().map_or(1, |n| n.get()), } } } -/// Une interface réseau: son nom et ses adresses IP. Jamais d'adresse MAC. +/// A network interface: its name and IP addresses. Never a MAC address. #[derive(Debug, Clone, Serialize, PartialEq, Eq)] pub struct Interface { - pub nom: String, - pub adresses: Vec, + pub name: String, + pub addresses: Vec, } -/// Les interfaces actives, lues localement (`getifaddrs`), sans paquet émis. +/// The active interfaces, read locally (`getifaddrs`), without sending a +/// packet. pub fn interfaces() -> Vec { - let mut carte: BTreeMap> = BTreeMap::new(); + let mut map: BTreeMap> = BTreeMap::new(); for interface in if_addrs::get_if_addrs().unwrap_or_default() { - carte - .entry(interface.name.clone()) + map.entry(interface.name.clone()) .or_default() .push(interface.ip().to_string()); } - carte - .into_iter() - .map(|(nom, adresses)| Interface { nom, adresses }) + map.into_iter() + .map(|(name, addresses)| Interface { name, addresses }) .collect() } #[derive(Debug, Clone, Serialize)] -struct Manifeste<'a> { +struct Manifest<'a> { format: u32, rustscreen: &'a str, - genere_le: String, - systeme: &'a Systeme, - reseau: &'a [Interface], + generated_at: String, + system: &'a SystemInfo, + network: &'a [Interface], #[serde(flatten)] sections: &'a BTreeMap, - journaux: Vec, + logs: Vec, } -/// Ce que l'appelant sait de lui-même, plus ce que le crate lit du système. -pub struct Rapport { +/// What the caller knows about itself, plus what the crate reads from the +/// system. +pub struct Report { pub version: String, - pub systeme: Systeme, - pub reseau: Vec, - /// Sections libres du manifeste: session graphique, portail, capture, - /// encodage. L'appelant n'y met que des faits techniques, jamais un titre - /// de fenêtre. + pub system: SystemInfo, + pub network: Vec, + /// Free-form manifest sections: graphical session, portal, capture, + /// encoding. The caller only puts technical facts there, never a window + /// title. pub sections: BTreeMap, } -impl Rapport { - pub fn nouveau(version: impl Into) -> Self { +impl Report { + pub fn new(version: impl Into) -> Self { Self { version: version.into(), - systeme: Systeme::detecter(), - reseau: interfaces(), + system: SystemInfo::detect(), + network: interfaces(), sections: BTreeMap::new(), } } - pub fn section(&mut self, nom: &str, valeur: impl Serialize) -> &mut Self { - if let Ok(valeur) = serde_json::to_value(valeur) { - self.sections.insert(nom.to_string(), valeur); + pub fn section(&mut self, name: &str, value: impl Serialize) -> &mut Self { + if let Ok(value) = serde_json::to_value(value) { + self.sections.insert(name.to_string(), value); } self } - /// Construit l'archive en mémoire. - pub fn archive(&self, journaux: Option<&Path>) -> Result, DiagError> { - let mut curseur = Cursor::new(Vec::new()); - self.ecrire(journaux, &mut curseur)?; - Ok(curseur.into_inner()) + /// Builds the archive in memory. + pub fn archive(&self, logs: Option<&Path>) -> Result, DiagError> { + let mut cursor = Cursor::new(Vec::new()); + self.write(logs, &mut cursor)?; + Ok(cursor.into_inner()) } - /// Écrit l'archive dans un fichier, et rend son chemin. - pub fn enregistrer( - &self, - journaux: Option<&Path>, - chemin: &Path, - ) -> Result { - let octets = self.archive(journaux)?; - std::fs::write(chemin, octets)?; - Ok(chemin.to_path_buf()) + /// Writes the archive to a file, and returns its path. + pub fn save(&self, logs: Option<&Path>, path: &Path) -> Result { + let bytes = self.archive(logs)?; + std::fs::write(path, bytes)?; + Ok(path.to_path_buf()) } - fn ecrire(&self, journaux: Option<&Path>, sortie: W) -> Result<(), DiagError> { + fn write(&self, logs: Option<&Path>, out: W) -> Result<(), DiagError> { let zip_err = |e: zip::result::ZipError| DiagError::Archive(e.to_string()); let options = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated); - let mut zip = zip::ZipWriter::new(sortie); + let mut zip = zip::ZipWriter::new(out); - let fichiers = journaux.map(choisir_journaux).unwrap_or_default(); - let mut noms = Vec::new(); - for (chemin, debut) in &fichiers { - let Some(nom) = chemin.file_name().and_then(|n| n.to_str()) else { + let files = logs.map(pick_logs).unwrap_or_default(); + let mut names = Vec::new(); + for (path, start) in &files { + let Some(name) = path.file_name().and_then(|n| n.to_str()) else { continue; }; - let mut texte = String::new(); - let mut fichier = std::fs::File::open(chemin)?; - fichier.seek(std::io::SeekFrom::Start(*debut))?; - // Un journal peut contenir une ligne coupée par une écriture en - // cours: on la garde, lossy plutôt que d'échouer. - let mut octets = Vec::new(); - fichier.read_to_end(&mut octets)?; - texte.push_str(&String::from_utf8_lossy(&octets)); - zip.start_file(format!("logs/{nom}"), options) + let mut text = String::new(); + let mut file = std::fs::File::open(path)?; + file.seek(std::io::SeekFrom::Start(*start))?; + // A log can hold a line cut by a write in progress: keep it, + // lossy rather than failing. + let mut bytes = Vec::new(); + file.read_to_end(&mut bytes)?; + text.push_str(&String::from_utf8_lossy(&bytes)); + zip.start_file(format!("logs/{name}"), options) .map_err(zip_err)?; - zip.write_all(expurger(&texte).as_bytes())?; - noms.push(nom.to_string()); + zip.write_all(redact(&text).as_bytes())?; + names.push(name.to_string()); } - let manifeste = Manifeste { + let manifest = Manifest { format: 1, rustscreen: &self.version, - genere_le: horodatage(SystemTime::now()), - systeme: &self.systeme, - reseau: &self.reseau, + generated_at: timestamp(SystemTime::now()), + system: &self.system, + network: &self.network, sections: &self.sections, - journaux: noms, + logs: names, }; - let json = serde_json::to_string_pretty(&manifeste) + let json = serde_json::to_string_pretty(&manifest) .map_err(|e| DiagError::Archive(e.to_string()))?; zip.start_file("manifest.json", options).map_err(zip_err)?; - zip.write_all(expurger(&json).as_bytes())?; + zip.write_all(redact(&json).as_bytes())?; zip.finish().map_err(zip_err)?; Ok(()) } } -/// Les journaux à embarquer, du plus récent au plus ancien, sous le plafond. -/// Rend pour chacun la position de départ: un fichier trop gros est pris par -/// la fin, qui est ce qu'on cherche. -fn choisir_journaux(dossier: &Path) -> Vec<(PathBuf, u64)> { - let Ok(entrees) = std::fs::read_dir(dossier) else { +/// The logs to embed, newest to oldest, under the cap. Returns the start +/// offset for each: a file that is too large is taken from its end, which is +/// what one is looking for. +fn pick_logs(dir: &Path) -> Vec<(PathBuf, u64)> { + let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new(); }; - let mut fichiers: Vec<(PathBuf, SystemTime, u64)> = entrees + let mut files: Vec<(PathBuf, SystemTime, u64)> = entries .filter_map(Result::ok) .filter(|e| { e.file_name() .to_str() - .is_some_and(|n| n.starts_with(PREFIXE) && n.ends_with(".log")) + .is_some_and(|n| n.starts_with(FILE_PREFIX) && n.ends_with(".log")) }) .filter_map(|e| { let meta = e.metadata().ok()?; @@ -199,52 +195,52 @@ fn choisir_journaux(dossier: &Path) -> Vec<(PathBuf, u64)> { .then(|| (e.path(), meta.modified().unwrap_or(UNIX_EPOCH), meta.len())) }) .collect(); - fichiers.sort_by_key(|f| std::cmp::Reverse(f.1)); + files.sort_by_key(|f| std::cmp::Reverse(f.1)); - let mut reste = PLAFOND_JOURNAUX; - let mut choisis = Vec::new(); - for (chemin, _, taille) in fichiers { - if reste == 0 { + let mut left = LOG_CAP_BYTES; + let mut picked = Vec::new(); + for (path, _, size) in files { + if left == 0 { break; } - let pris = taille.min(reste); - choisis.push((chemin, taille - pris)); - reste -= pris; + let taken = size.min(left); + picked.push((path, size - taken)); + left -= taken; } - choisis + picked } -/// `diag-rustscreen-AAAA-MM-JJ-HHMMSS.zip`, en UTC. -pub fn nom_archive(maintenant: SystemTime) -> String { - let (a, mo, j, h, mi, s) = civil(maintenant); - format!("diag-rustscreen-{a:04}-{mo:02}-{j:02}-{h:02}{mi:02}{s:02}.zip") +/// `diag-rustscreen-YYYY-MM-DD-HHMMSS.zip`, in UTC. +pub fn archive_name(now: SystemTime) -> String { + let (y, mo, d, h, mi, s) = civil(now); + format!("diag-rustscreen-{y:04}-{mo:02}-{d:02}-{h:02}{mi:02}{s:02}.zip") } -fn horodatage(t: SystemTime) -> String { - let (a, mo, j, h, mi, s) = civil(t); - format!("{a:04}-{mo:02}-{j:02}T{h:02}:{mi:02}:{s:02}Z") +fn timestamp(t: SystemTime) -> String { + let (y, mo, d, h, mi, s) = civil(t); + format!("{y:04}-{mo:02}-{d:02}T{h:02}:{mi:02}:{s:02}Z") } -/// Date civile UTC, sans dépendance de calendrier (algorithme de H. Hinnant). +/// UTC civil date, with no calendar dependency (H. Hinnant's algorithm). fn civil(t: SystemTime) -> (i64, u32, u32, u32, u32, u32) { let secs = t.duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs()) as i64; - let (jours, reste) = (secs.div_euclid(86_400), secs.rem_euclid(86_400)); - let z = jours + 719_468; - let ere = z.div_euclid(146_097); - let doe = z - ere * 146_097; + let (days, rest) = (secs.div_euclid(86_400), secs.rem_euclid(86_400)); + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z - era * 146_097; let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); let mp = (5 * doy + 2) / 153; - let jour = (doy - (153 * mp + 2) / 5 + 1) as u32; - let mois = if mp < 10 { mp + 3 } else { mp - 9 } as u32; - let annee = yoe + ere * 400 + i64::from(mois <= 2); + let day = (doy - (153 * mp + 2) / 5 + 1) as u32; + let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32; + let year = yoe + era * 400 + i64::from(month <= 2); ( - annee, - mois, - jour, - (reste / 3600) as u32, - (reste % 3600 / 60) as u32, - (reste % 60) as u32, + year, + month, + day, + (rest / 3600) as u32, + (rest % 3600 / 60) as u32, + (rest % 60) as u32, ) } @@ -253,100 +249,100 @@ mod tests { use super::*; use std::time::Duration; - fn dossier_temporaire(nom: &str) -> PathBuf { - let dossier = std::env::temp_dir().join(format!( - "rs-diag-{nom}-{}-{}", + fn temp_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "rs-diag-{name}-{}-{}", std::process::id(), SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_nanos() )); - std::fs::create_dir_all(&dossier).unwrap(); - dossier + std::fs::create_dir_all(&dir).unwrap(); + dir } - fn lire(archive: &[u8]) -> BTreeMap { + fn read(archive: &[u8]) -> BTreeMap { let mut zip = zip::ZipArchive::new(Cursor::new(archive)).unwrap(); - let mut contenu = BTreeMap::new(); + let mut content = BTreeMap::new(); for i in 0..zip.len() { - let mut entree = zip.by_index(i).unwrap(); - let mut texte = String::new(); - entree.read_to_string(&mut texte).unwrap(); - contenu.insert(entree.name().unwrap().to_string(), texte); + let mut entry = zip.by_index(i).unwrap(); + let mut text = String::new(); + entry.read_to_string(&mut text).unwrap(); + content.insert(entry.name().unwrap().to_string(), text); } - contenu + content } #[test] fn the_archive_holds_only_the_manifest_and_scrubbed_logs() { - let dossier = dossier_temporaire("contenu"); + let dir = temp_dir("content"); std::fs::write( - dossier.join("rustscreen.2026-10-26.log"), + dir.join("rustscreen.2026-10-26.log"), concat!( - r#"{"level":"INFO","fields":{"evenement":"session_ouverte","pair":"192.168.1.30"}}"#, + r#"{"level":"INFO","fields":{"event":"session_opened","peer":"192.168.1.30"}}"#, "\n", - r#"{"level":"WARN","fields":{"message":"voisin 3c:22:fb:01:a2:9e","url":"/r/abc234?t=00112233445566778899aabbccddeeff"}}"#, + r#"{"level":"WARN","fields":{"message":"neighbour 3c:22:fb:01:a2:9e","url":"/r/abc234?t=00112233445566778899aabbccddeeff"}}"#, "\n" ), ) .unwrap(); - // Un fichier étranger au journal ne part pas, même dans le dossier. - std::fs::write(dossier.join("capture.bgra"), [0u8; 64]).unwrap(); + // A file foreign to the log does not go, even in the same directory. + std::fs::write(dir.join("capture.bgra"), [0u8; 64]).unwrap(); - let mut rapport = Rapport::nouveau("0.3.0"); - rapport.section("capture", serde_json::json!({ "chemin": "portail" })); - let archive = rapport.archive(Some(&dossier)).unwrap(); - let contenu = lire(&archive); + let mut report = Report::new("0.3.0"); + report.section("capture", serde_json::json!({ "path": "portal" })); + let archive = report.archive(Some(&dir)).unwrap(); + let content = read(&archive); - let noms: Vec<&str> = contenu.keys().map(String::as_str).collect(); - assert_eq!(noms, ["logs/rustscreen.2026-10-26.log", "manifest.json"]); + let names: Vec<&str> = content.keys().map(String::as_str).collect(); + assert_eq!(names, ["logs/rustscreen.2026-10-26.log", "manifest.json"]); - let journal = &contenu["logs/rustscreen.2026-10-26.log"]; - assert!(journal.contains("session_ouverte")); - assert!(!journal.contains("3c:22:fb:01:a2:9e"), "{journal}"); - assert!(!journal.contains("00112233445566778899"), "{journal}"); + let log = &content["logs/rustscreen.2026-10-26.log"]; + assert!(log.contains("session_opened")); + assert!(!log.contains("3c:22:fb:01:a2:9e"), "{log}"); + assert!(!log.contains("00112233445566778899"), "{log}"); - let manifeste: serde_json::Value = serde_json::from_str(&contenu["manifest.json"]).unwrap(); - assert_eq!(manifeste["rustscreen"], "0.3.0"); - assert_eq!(manifeste["capture"]["chemin"], "portail"); - assert_eq!(manifeste["journaux"][0], "rustscreen.2026-10-26.log"); - assert!(manifeste["systeme"]["architecture"].is_string()); + let manifest: serde_json::Value = serde_json::from_str(&content["manifest.json"]).unwrap(); + assert_eq!(manifest["rustscreen"], "0.3.0"); + assert_eq!(manifest["capture"]["path"], "portal"); + assert_eq!(manifest["logs"][0], "rustscreen.2026-10-26.log"); + assert!(manifest["system"]["architecture"].is_string()); - std::fs::remove_dir_all(dossier).unwrap(); + std::fs::remove_dir_all(dir).unwrap(); } #[test] fn the_manifest_never_carries_a_mac_address() { - // Les interfaces réelles de la machine de test: le manifeste ne doit - // contenir que des noms et des IP. - let archive = Rapport::nouveau("test").archive(None).unwrap(); - let manifeste = &lire(&archive)["manifest.json"]; - assert_eq!(expurger(manifeste), *manifeste, "{manifeste}"); + // The test machine's real interfaces: the manifest must hold only + // names and IPs. + let archive = Report::new("test").archive(None).unwrap(); + let manifest = &read(&archive)["manifest.json"]; + assert_eq!(redact(manifest), *manifest, "{manifest}"); } #[test] fn logs_are_capped_from_the_newest() { - let dossier = dossier_temporaire("plafond"); - let gros = vec![b'a'; (PLAFOND_JOURNAUX + 10) as usize]; - std::fs::write(dossier.join("rustscreen.ancien.log"), b"vieux").unwrap(); + let dir = temp_dir("cap"); + let big = vec![b'a'; (LOG_CAP_BYTES + 10) as usize]; + std::fs::write(dir.join("rustscreen.old.log"), b"old").unwrap(); std::thread::sleep(Duration::from_millis(20)); - std::fs::write(dossier.join("rustscreen.recent.log"), &gros).unwrap(); - let choisis = choisir_journaux(&dossier); - assert_eq!(choisis.len(), 1, "le plus récent remplit tout le plafond"); - assert!(choisis[0].0.ends_with("rustscreen.recent.log")); - assert_eq!(choisis[0].1, 10, "pris par la fin"); - std::fs::remove_dir_all(dossier).unwrap(); + std::fs::write(dir.join("rustscreen.recent.log"), &big).unwrap(); + let picked = pick_logs(&dir); + assert_eq!(picked.len(), 1, "the newest fills the whole cap"); + assert!(picked[0].0.ends_with("rustscreen.recent.log")); + assert_eq!(picked[0].1, 10, "taken from the end"); + std::fs::remove_dir_all(dir).unwrap(); } #[test] fn civil_dates_are_right() { let t = UNIX_EPOCH + Duration::from_secs(1_793_016_000); // 2026-10-26 12:00:00 - assert_eq!(horodatage(t), "2026-10-26T12:00:00Z"); - assert_eq!(nom_archive(t), "diag-rustscreen-2026-10-26-120000.zip"); - assert_eq!(horodatage(UNIX_EPOCH), "1970-01-01T00:00:00Z"); - // 29 février d'une année bissextile. - let bissextile = UNIX_EPOCH + Duration::from_secs(1_709_164_800); - assert_eq!(horodatage(bissextile), "2024-02-29T00:00:00Z"); + assert_eq!(timestamp(t), "2026-10-26T12:00:00Z"); + assert_eq!(archive_name(t), "diag-rustscreen-2026-10-26-120000.zip"); + assert_eq!(timestamp(UNIX_EPOCH), "1970-01-01T00:00:00Z"); + // February 29th of a leap year. + let leap = UNIX_EPOCH + Duration::from_secs(1_709_164_800); + assert_eq!(timestamp(leap), "2024-02-29T00:00:00Z"); } } diff --git a/crates/rs-diag/src/expurger.rs b/crates/rs-diag/src/expurger.rs deleted file mode 100644 index 977b2d1..0000000 --- a/crates/rs-diag/src/expurger.rs +++ /dev/null @@ -1,151 +0,0 @@ -//! Ce qui ne doit pas quitter la machine, même dans une archive envoyée de -//! plein gré. -//! -//! - les **adresses MAC**: elles identifient un appareil durablement, et rien -//! dans un diagnostic de flux n'en a besoin; -//! - les **jetons de session** (`t=…` dans une URL): ils donnent accès à -//! l'écran tant que la session vit. -//! -//! Les titres de fenêtres et les images ne sont pas expurgés ici: ils ne sont -//! jamais écrits dans les journaux (ADR 0008), ce qui est plus sûr que de -//! compter sur un filtre pour les retrouver. - -pub const MAC_MASQUEE: &str = "xx:xx:xx:xx:xx:xx"; -pub const JETON_MASQUE: &str = "t="; - -/// Rend le texte sans adresse MAC ni jeton de session. -pub fn expurger(texte: &str) -> String { - masquer_jetons(&masquer_mac(texte)) -} - -fn est_hex(b: u8) -> bool { - b.is_ascii_hexdigit() -} - -/// Une MAC est six paires hexadécimales séparées par `:` ou `-`, toujours le -/// même séparateur, et isolée: sans chiffre hexadécimal ni séparateur collé -/// avant ou après (sinon c'est un morceau d'autre chose, une IPv6 par exemple). -fn mac_en(octets: &[u8], i: usize) -> bool { - const LONGUEUR: usize = 17; - if i + LONGUEUR > octets.len() { - return false; - } - let sep = octets[i + 2]; - if sep != b':' && sep != b'-' { - return false; - } - for groupe in 0..6 { - let p = i + groupe * 3; - if !est_hex(octets[p]) || !est_hex(octets[p + 1]) { - return false; - } - if groupe < 5 && octets[p + 2] != sep { - return false; - } - } - let colle = |b: u8| est_hex(b) || b == b':' || b == b'-'; - let avant = i == 0 || !colle(octets[i - 1]); - let apres = octets.get(i + LONGUEUR).is_none_or(|&b| !colle(b)); - avant && apres -} - -fn masquer_mac(texte: &str) -> String { - let octets = texte.as_bytes(); - let mut sortie = String::with_capacity(texte.len()); - let mut i = 0; - let mut debut = 0; - while i < octets.len() { - if mac_en(octets, i) { - sortie.push_str(&texte[debut..i]); - sortie.push_str(MAC_MASQUEE); - i += 17; - debut = i; - } else { - i += 1; - } - } - sortie.push_str(&texte[debut..]); - sortie -} - -/// `?t=` ou `&t=` suivi d'une valeur: tout jusqu'au prochain délimiteur d'URL. -fn masquer_jetons(texte: &str) -> String { - let mut sortie = String::with_capacity(texte.len()); - let mut reste = texte; - while let Some(pos) = reste.find("t=") { - let precedent = reste[..pos].chars().next_back(); - if !matches!(precedent, Some('?') | Some('&')) { - sortie.push_str(&reste[..pos + 2]); - reste = &reste[pos + 2..]; - continue; - } - sortie.push_str(&reste[..pos]); - sortie.push_str(JETON_MASQUE); - let valeur = &reste[pos + 2..]; - let fin = valeur - .find(|c: char| c == '&' || c == '#' || c == '"' || c == '\'' || c.is_whitespace()) - .unwrap_or(valeur.len()); - reste = &valeur[fin..]; - } - sortie.push_str(reste); - sortie -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn mac_addresses_are_masked_whatever_the_separator() { - assert_eq!( - expurger("client 3c:22:FB:01:a2:9e vu"), - format!("client {MAC_MASQUEE} vu") - ); - assert_eq!(expurger("3C-22-FB-01-A2-9E"), MAC_MASQUEE); - assert_eq!( - expurger(r#"{"mac":"3c:22:fb:01:a2:9e"}"#), - format!(r#"{{"mac":"{MAC_MASQUEE}"}}"#) - ); - } - - #[test] - fn ipv6_and_times_are_left_alone() { - for intact in [ - "fe80::1c2b:3aff:fe4d:5e6f", - "2001:db8:85a3:0:0:8a2e:370:7334", - "12:34:56", - "3c:22:fb:01:a2", - "3c:22-fb:01:a2:9e", - ] { - assert_eq!(expurger(intact), intact); - } - } - - #[test] - fn session_tokens_are_masked_in_urls() { - let url = "http://192.168.1.20:8099/r/abc234?t=00112233445566778899aabbccddeeff"; - assert_eq!( - expurger(url), - format!("http://192.168.1.20:8099/r/abc234?{JETON_MASQUE}") - ); - assert_eq!( - expurger(r#""url":"/r/x?a=1&t=dead beef""#), - format!(r#""url":"/r/x?a=1&{JETON_MASQUE} beef""#) - ); - } - - #[test] - fn words_ending_in_t_are_not_tokens() { - let texte = "format=BGRx, débit=3000, test=1"; - assert_eq!(expurger(texte), texte); - } - - #[test] - fn non_ascii_text_survives() { - let texte = "échec: écran virtuel indisponible ?t=abc é"; - assert_eq!( - expurger(texte), - format!("échec: écran virtuel indisponible ?{JETON_MASQUE} é") - ); - } -} diff --git a/crates/rs-diag/src/journal.rs b/crates/rs-diag/src/journal.rs deleted file mode 100644 index 078a621..0000000 --- a/crates/rs-diag/src/journal.rs +++ /dev/null @@ -1,142 +0,0 @@ -//! Journalisation: lisible dans la console, structurée dans les fichiers. -//! -//! La console reste au format humain, c'est ce que lit la personne qui lance -//! `rustscreen`. Les fichiers sont en JSON, un événement par ligne: c'est ce -//! qu'on relit quand la session s'est mal passée chez quelqu'un d'autre, et un -//! champ `evenement` nommé se retrouve sans ambiguïté. -//! -//! Les niveaux se règlent par cible, donc par crate, avec `RUST_LOG` -//! (`rs_rtc=debug,str0m=warn`). - -use std::path::{Path, PathBuf}; - -use tracing_appender::non_blocking::WorkerGuard; -use tracing_appender::rolling::{RollingFileAppender, Rotation}; -use tracing_subscriber::layer::SubscriberExt; -use tracing_subscriber::util::SubscriberInitExt; -use tracing_subscriber::{EnvFilter, Layer}; - -use crate::DiagError; - -/// Préfixe des fichiers de journal, suivi de la date. -pub const PREFIXE: &str = "rustscreen"; -/// Une semaine: assez pour remonter à « ça ramait mardi », pas plus. -pub const FICHIERS_GARDES: usize = 7; - -/// Garde le journal en vie: le laisser tomber perd les dernières lignes. -pub struct Journal { - /// Répertoire des fichiers, `None` si l'écriture sur disque a échoué (la - /// console reste active). - pub dossier: Option, - _garde: Option, -} - -/// Où vivent les journaux: `RUSTSCREEN_LOG_DIR`, sinon le répertoire d'état -/// XDG (`~/.local/state/rustscreen/logs`). Des journaux sont de l'état, pas des -/// données: ils se suppriment sans rien perdre d'important. -pub fn dossier_journaux() -> Option { - dossier_depuis(|nom| std::env::var_os(nom).map(PathBuf::from)) -} - -fn dossier_depuis(get: impl Fn(&str) -> Option) -> Option { - if let Some(dossier) = get("RUSTSCREEN_LOG_DIR") { - return Some(dossier); - } - let etat = get("XDG_STATE_HOME") - .filter(|p| p.is_absolute()) - .or_else(|| get("HOME").map(|h| h.join(".local/state")))?; - Some(etat.join("rustscreen").join("logs")) -} - -/// Installe le journal global. `defaut` est le filtre quand `RUST_LOG` est vide. -/// -/// Un répertoire inaccessible n'empêche pas de démarrer: on prévient dans la -/// console et on continue sans fichier. -pub fn initialiser(dossier: Option<&Path>, defaut: &str) -> Journal { - let filtre = || EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(defaut)); - let console = tracing_subscriber::fmt::layer() - .with_writer(std::io::stderr) - .with_filter(filtre()); - - let (fichier, garde, dossier, echec) = match dossier.map(ouvrir) { - Some(Ok((appender, dossier))) => { - let (ecrivain, garde) = tracing_appender::non_blocking(appender); - let couche = tracing_subscriber::fmt::layer() - .json() - .with_current_span(false) - .with_span_list(false) - .with_writer(ecrivain) - .with_filter(filtre()); - (Some(couche), Some(garde), Some(dossier), None) - } - Some(Err(erreur)) => (None, None, None, Some(erreur)), - None => (None, None, None, None), - }; - - // `try_init`: un second appel (tests) ne doit pas paniquer. - let _ = tracing_subscriber::registry() - .with(console) - .with(fichier) - .try_init(); - if let Some(erreur) = echec { - tracing::warn!(%erreur, "journal sur disque désactivé"); - } - Journal { - dossier, - _garde: garde, - } -} - -fn ouvrir(dossier: &Path) -> Result<(RollingFileAppender, PathBuf), DiagError> { - let erreur = |raison: String| DiagError::Dossier { - chemin: dossier.display().to_string(), - raison, - }; - std::fs::create_dir_all(dossier).map_err(|e| erreur(e.to_string()))?; - let appender = RollingFileAppender::builder() - .rotation(Rotation::DAILY) - .filename_prefix(PREFIXE) - .filename_suffix("log") - .max_log_files(FICHIERS_GARDES) - .build(dossier) - .map_err(|e| erreur(e.to_string()))?; - Ok((appender, dossier.to_path_buf())) -} - -#[cfg(test)] -mod tests { - use super::*; - use std::collections::HashMap; - - fn depuis(paires: &[(&str, &str)]) -> Option { - let carte: HashMap<&str, PathBuf> = - paires.iter().map(|(c, v)| (*c, PathBuf::from(v))).collect(); - dossier_depuis(|nom| carte.get(nom).cloned()) - } - - #[test] - fn the_override_wins() { - assert_eq!( - depuis(&[("RUSTSCREEN_LOG_DIR", "/tmp/x"), ("HOME", "/home/a")]), - Some(PathBuf::from("/tmp/x")) - ); - } - - #[test] - fn xdg_state_home_then_home() { - assert_eq!( - depuis(&[("XDG_STATE_HOME", "/etat"), ("HOME", "/home/a")]), - Some(PathBuf::from("/etat/rustscreen/logs")) - ); - assert_eq!( - depuis(&[("HOME", "/home/a")]), - Some(PathBuf::from("/home/a/.local/state/rustscreen/logs")) - ); - // La spécification XDG ignore un chemin relatif. - assert_eq!( - depuis(&[("XDG_STATE_HOME", "relatif"), ("HOME", "/home/a")]), - Some(PathBuf::from("/home/a/.local/state/rustscreen/logs")) - ); - assert_eq!(depuis(&[]), None); - } -} diff --git a/crates/rs-diag/src/lib.rs b/crates/rs-diag/src/lib.rs index 8b78026..15217ab 100644 --- a/crates/rs-diag/src/lib.rs +++ b/crates/rs-diag/src/lib.rs @@ -1,26 +1,27 @@ -//! Diagnostiquer une session qui rame chez quelqu'un d'autre, sans télémétrie -//! et sans accès à sa machine. +//! Diagnose a session that lags on someone else's machine, with no telemetry +//! and no access to that machine. //! -//! - [`journal`]: `tracing` vers la console et vers des fichiers JSON (un -//! événement par ligne), avec rotation quotidienne dans le répertoire d'état. -//! - [`archive`]: un fichier zip unique que l'utilisateur transmet lui-même: -//! un manifeste (versions, système, capacités, réseau) et les journaux, -//! expurgés des adresses MAC et des jetons de session. +//! - [`log`]: `tracing` to the console and to JSON files (one event per line), +//! rotated daily in the state directory. +//! - [`archive`]: a single zip file the user sends themselves: a manifest +//! (versions, system, capabilities, network) and the logs, scrubbed of MAC +//! addresses and session tokens. //! -//! Rien ici n'ouvre de connexion réseau. Le format est décrit par l'ADR 0008. +//! Nothing here opens a network connection. The format is described by +//! ADR 0008. pub mod archive; -pub mod expurger; -pub mod journal; +pub mod log; +pub mod redact; -pub use archive::{Rapport, Systeme, nom_archive}; -pub use expurger::expurger; -pub use journal::{Journal, dossier_journaux, initialiser}; +pub use archive::{Report, SystemInfo, archive_name}; +pub use log::{LogGuard, init, log_dir}; +pub use redact::redact; #[derive(Debug, thiserror::Error)] pub enum DiagError { - #[error("répertoire des journaux {chemin}: {raison}")] - Dossier { chemin: String, raison: String }, + #[error("log directory {path}: {reason}")] + Directory { path: String, reason: String }, #[error("archive: {0}")] Archive(String), #[error("I/O: {0}")] diff --git a/crates/rs-diag/src/log.rs b/crates/rs-diag/src/log.rs new file mode 100644 index 0000000..c8fb8d6 --- /dev/null +++ b/crates/rs-diag/src/log.rs @@ -0,0 +1,140 @@ +//! Logging: human readable on the console, structured in the files. +//! +//! The console keeps the human format, it is what the person running +//! `rustscreen` reads. The files are JSON, one event per line: they are what +//! gets read back when a session went wrong on someone else's machine, and a +//! named `event` field is found without ambiguity. +//! +//! Levels are set per target, hence per crate, with `RUST_LOG` +//! (`rs_rtc=debug,str0m=warn`). + +use std::path::{Path, PathBuf}; + +use tracing_appender::non_blocking::WorkerGuard; +use tracing_appender::rolling::{RollingFileAppender, Rotation}; +use tracing_subscriber::layer::SubscriberExt; +use tracing_subscriber::util::SubscriberInitExt; +use tracing_subscriber::{EnvFilter, Layer}; + +use crate::DiagError; + +/// Log file prefix, followed by the date. +pub const FILE_PREFIX: &str = "rustscreen"; +/// One week: enough to go back to "it lagged on Tuesday", no more. +pub const KEPT_FILES: usize = 7; + +/// Keeps the logger alive: dropping it loses the last lines. +pub struct LogGuard { + /// Directory of the files, `None` if writing to disk failed (the console + /// stays active). + pub dir: Option, + _guard: Option, +} + +/// Where the logs live: `RUSTSCREEN_LOG_DIR`, otherwise the XDG state +/// directory (`~/.local/state/rustscreen/logs`). Logs are state, not data: +/// they can be deleted without losing anything important. +pub fn log_dir() -> Option { + dir_from(|name| std::env::var_os(name).map(PathBuf::from)) +} + +fn dir_from(get: impl Fn(&str) -> Option) -> Option { + if let Some(dir) = get("RUSTSCREEN_LOG_DIR") { + return Some(dir); + } + let state = get("XDG_STATE_HOME") + .filter(|p| p.is_absolute()) + .or_else(|| get("HOME").map(|h| h.join(".local/state")))?; + Some(state.join("rustscreen").join("logs")) +} + +/// Installs the global logger. `default` is the filter when `RUST_LOG` is +/// empty. +/// +/// An unreachable directory does not prevent startup: a warning goes to the +/// console and logging continues without a file. +pub fn init(dir: Option<&Path>, default: &str) -> LogGuard { + let filter = || EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(default)); + let console = tracing_subscriber::fmt::layer() + .with_writer(std::io::stderr) + .with_filter(filter()); + + let (file, guard, dir, failure) = match dir.map(open) { + Some(Ok((appender, dir))) => { + let (writer, guard) = tracing_appender::non_blocking(appender); + let layer = tracing_subscriber::fmt::layer() + .json() + .with_current_span(false) + .with_span_list(false) + .with_writer(writer) + .with_filter(filter()); + (Some(layer), Some(guard), Some(dir), None) + } + Some(Err(error)) => (None, None, None, Some(error)), + None => (None, None, None, None), + }; + + // `try_init`: a second call (tests) must not panic. + let _ = tracing_subscriber::registry() + .with(console) + .with(file) + .try_init(); + if let Some(error) = failure { + tracing::warn!(%error, "on-disk logging disabled"); + } + LogGuard { dir, _guard: guard } +} + +fn open(dir: &Path) -> Result<(RollingFileAppender, PathBuf), DiagError> { + let error = |reason: String| DiagError::Directory { + path: dir.display().to_string(), + reason, + }; + std::fs::create_dir_all(dir).map_err(|e| error(e.to_string()))?; + let appender = RollingFileAppender::builder() + .rotation(Rotation::DAILY) + .filename_prefix(FILE_PREFIX) + .filename_suffix("log") + .max_log_files(KEPT_FILES) + .build(dir) + .map_err(|e| error(e.to_string()))?; + Ok((appender, dir.to_path_buf())) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashMap; + + fn from_pairs(pairs: &[(&str, &str)]) -> Option { + let map: HashMap<&str, PathBuf> = + pairs.iter().map(|(k, v)| (*k, PathBuf::from(v))).collect(); + dir_from(|name| map.get(name).cloned()) + } + + #[test] + fn the_override_wins() { + assert_eq!( + from_pairs(&[("RUSTSCREEN_LOG_DIR", "/tmp/x"), ("HOME", "/home/a")]), + Some(PathBuf::from("/tmp/x")) + ); + } + + #[test] + fn xdg_state_home_then_home() { + assert_eq!( + from_pairs(&[("XDG_STATE_HOME", "/state"), ("HOME", "/home/a")]), + Some(PathBuf::from("/state/rustscreen/logs")) + ); + assert_eq!( + from_pairs(&[("HOME", "/home/a")]), + Some(PathBuf::from("/home/a/.local/state/rustscreen/logs")) + ); + // The XDG specification ignores a relative path. + assert_eq!( + from_pairs(&[("XDG_STATE_HOME", "relative"), ("HOME", "/home/a")]), + Some(PathBuf::from("/home/a/.local/state/rustscreen/logs")) + ); + assert_eq!(from_pairs(&[]), None); + } +} diff --git a/crates/rs-diag/src/redact.rs b/crates/rs-diag/src/redact.rs new file mode 100644 index 0000000..c342c6f --- /dev/null +++ b/crates/rs-diag/src/redact.rs @@ -0,0 +1,152 @@ +//! What must not leave the machine, even in an archive sent willingly. +//! +//! - **MAC addresses**: they identify a device durably, and nothing in a +//! stream diagnostic needs them; +//! - **session tokens** (`t=...` in a URL): they give access to the screen +//! for as long as the session lives. +//! +//! Window titles and images are not redacted here: they are never written to +//! the logs (ADR 0008), which is safer than relying on a filter to find them. + +pub const MASKED_MAC: &str = "xx:xx:xx:xx:xx:xx"; +pub const MASKED_TOKEN: &str = "t="; + +/// Returns the text without MAC addresses or session tokens. +pub fn redact(text: &str) -> String { + mask_tokens(&mask_macs(text)) +} + +fn is_hex(b: u8) -> bool { + b.is_ascii_hexdigit() +} + +/// A MAC is six hexadecimal pairs separated by `:` or `-`, always the same +/// separator, and isolated: no hexadecimal digit or separator glued before or +/// after (otherwise it is a piece of something else, an IPv6 for instance). +fn mac_at(bytes: &[u8], i: usize) -> bool { + const LENGTH: usize = 17; + if i + LENGTH > bytes.len() { + return false; + } + let sep = bytes[i + 2]; + if sep != b':' && sep != b'-' { + return false; + } + for group in 0..6 { + let p = i + group * 3; + if !is_hex(bytes[p]) || !is_hex(bytes[p + 1]) { + return false; + } + if group < 5 && bytes[p + 2] != sep { + return false; + } + } + let glued = |b: u8| is_hex(b) || b == b':' || b == b'-'; + let before = i == 0 || !glued(bytes[i - 1]); + let after = bytes.get(i + LENGTH).is_none_or(|&b| !glued(b)); + before && after +} + +fn mask_macs(text: &str) -> String { + let bytes = text.as_bytes(); + let mut out = String::with_capacity(text.len()); + let mut i = 0; + let mut start = 0; + while i < bytes.len() { + if mac_at(bytes, i) { + out.push_str(&text[start..i]); + out.push_str(MASKED_MAC); + i += 17; + start = i; + } else { + i += 1; + } + } + out.push_str(&text[start..]); + out +} + +/// `?t=` or `&t=` followed by a value: everything up to the next URL +/// delimiter. +fn mask_tokens(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + let mut rest = text; + while let Some(pos) = rest.find("t=") { + let previous = rest[..pos].chars().next_back(); + if !matches!(previous, Some('?') | Some('&')) { + out.push_str(&rest[..pos + 2]); + rest = &rest[pos + 2..]; + continue; + } + out.push_str(&rest[..pos]); + out.push_str(MASKED_TOKEN); + let value = &rest[pos + 2..]; + let end = value + .find(|c: char| c == '&' || c == '#' || c == '"' || c == '\'' || c.is_whitespace()) + .unwrap_or(value.len()); + rest = &value[end..]; + } + out.push_str(rest); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn mac_addresses_are_masked_whatever_the_separator() { + assert_eq!( + redact("client 3c:22:FB:01:a2:9e seen"), + format!("client {MASKED_MAC} seen") + ); + assert_eq!(redact("3C-22-FB-01-A2-9E"), MASKED_MAC); + assert_eq!( + redact(r#"{"mac":"3c:22:fb:01:a2:9e"}"#), + format!(r#"{{"mac":"{MASKED_MAC}"}}"#) + ); + } + + #[test] + fn ipv6_and_times_are_left_alone() { + for intact in [ + "fe80::1c2b:3aff:fe4d:5e6f", + "2001:db8:85a3:0:0:8a2e:370:7334", + "12:34:56", + "3c:22:fb:01:a2", + "3c:22-fb:01:a2:9e", + ] { + assert_eq!(redact(intact), intact); + } + } + + #[test] + fn session_tokens_are_masked_in_urls() { + let url = "http://192.168.1.20:8099/r/abc234?t=00112233445566778899aabbccddeeff"; + assert_eq!( + redact(url), + format!("http://192.168.1.20:8099/r/abc234?{MASKED_TOKEN}") + ); + assert_eq!( + redact(r#""url":"/r/x?a=1&t=dead beef""#), + format!(r#""url":"/r/x?a=1&{MASKED_TOKEN} beef""#) + ); + } + + #[test] + fn words_ending_in_t_are_not_tokens() { + let text = "format=BGRx, bitrate=3000, test=1"; + assert_eq!(redact(text), text); + } + + #[test] + fn non_ascii_text_survives() { + // Logged values can still carry accented text: the scan works on + // bytes and must not split a UTF-8 character. + let text = "échec: écran virtuel indisponible ?t=abc é"; + assert_eq!( + redact(text), + format!("échec: écran virtuel indisponible ?{MASKED_TOKEN} é") + ); + } +} diff --git a/crates/rs-platform/Cargo.toml b/crates/rs-platform/Cargo.toml index a5289f7..a30e9fb 100644 --- a/crates/rs-platform/Cargo.toml +++ b/crates/rs-platform/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rs-platform" -description = "Intégration système: autostart, inhibition de veille, interfaces réseau." +description = "System integration: autostart, sleep inhibition, network interfaces." version.workspace = true edition.workspace = true rust-version.workspace = true diff --git a/crates/rs-platform/src/autostart.rs b/crates/rs-platform/src/autostart.rs new file mode 100644 index 0000000..1bf1f93 --- /dev/null +++ b/crates/rs-platform/src/autostart.rs @@ -0,0 +1,89 @@ +//! Autostart when the session opens, through the XDG mechanism. +//! +//! A `.desktop` file in `~/.config/autostart`: every Linux desktop reads it, +//! with no service and no privilege. Enabling means writing it; disabling +//! means removing it. No other state: the setting and the file cannot drift +//! apart silently, since [`is_enabled`] rereads the file. + +use std::path::{Path, PathBuf}; + +/// File name, unique to the product. +pub const FILE_NAME: &str = "rustscreen.desktop"; + +/// Where the file lives: `$XDG_CONFIG_HOME/autostart`, else `~/.config/autostart`. +pub fn directory() -> Option { + std::env::var_os("XDG_CONFIG_HOME") + .map(PathBuf::from) + .filter(|p| p.is_absolute()) + .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config"))) + .map(|config| config.join("autostart")) +} + +/// The file content that launches `executable` (with its arguments). +pub fn content(executable: &Path, arguments: &str) -> String { + // A path with a space must be quoted (Desktop Entry specification, Exec + // key). + let path = executable.display().to_string(); + let path = if path.contains(' ') { + format!("\"{}\"", path.replace('"', "\\\"")) + } else { + path + }; + let exec = if arguments.is_empty() { + path + } else { + format!("{path} {arguments}") + }; + format!( + "[Desktop Entry]\n\ + Type=Application\n\ + Name=rustscreen\n\ + Comment=Screen sharing over the local network\n\ + Exec={exec}\n\ + Terminal=false\n\ + X-GNOME-Autostart-enabled=true\n" + ) +} + +/// Writes or removes the file in `directory`. +pub fn set( + directory: &Path, + enabled: bool, + executable: &Path, + arguments: &str, +) -> std::io::Result<()> { + let file = directory.join(FILE_NAME); + if enabled { + std::fs::create_dir_all(directory)?; + std::fs::write(file, content(executable, arguments)) + } else { + match std::fs::remove_file(file) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), + other => other, + } + } +} + +pub fn is_enabled(directory: &Path) -> bool { + directory.join(FILE_NAME).is_file() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn enabling_writes_the_file_and_disabling_removes_it() { + let directory = std::env::temp_dir().join(format!("rs-autostart-{}", std::process::id())); + let exe = Path::new("/opt/rust screen/rustscreen-desktop"); + set(&directory, true, exe, "--cache").unwrap(); + assert!(is_enabled(&directory)); + let text = std::fs::read_to_string(directory.join(FILE_NAME)).unwrap(); + assert!(text.contains("Exec=\"/opt/rust screen/rustscreen-desktop\" --cache")); + set(&directory, false, exe, "").unwrap(); + assert!(!is_enabled(&directory)); + // Disabling twice is not an error. + set(&directory, false, exe, "").unwrap(); + let _ = std::fs::remove_dir_all(&directory); + } +} diff --git a/crates/rs-platform/src/demarrage.rs b/crates/rs-platform/src/demarrage.rs deleted file mode 100644 index e7d4d6b..0000000 --- a/crates/rs-platform/src/demarrage.rs +++ /dev/null @@ -1,89 +0,0 @@ -//! Démarrage automatique à l'ouverture de session, par le mécanisme XDG. -//! -//! Un fichier `.desktop` dans `~/.config/autostart`: tous les bureaux Linux le -//! lisent, sans service ni privilège. L'activer, c'est l'écrire; le désactiver, -//! c'est le supprimer. Aucun autre état: le réglage et le fichier ne peuvent -//! pas diverger en silence, puisque [`est_actif`] relit le fichier. - -use std::path::{Path, PathBuf}; - -/// Nom du fichier, unique au produit. -pub const FICHIER: &str = "rustscreen.desktop"; - -/// Où vit le fichier: `$XDG_CONFIG_HOME/autostart`, sinon `~/.config/autostart`. -pub fn dossier() -> Option { - std::env::var_os("XDG_CONFIG_HOME") - .map(PathBuf::from) - .filter(|p| p.is_absolute()) - .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config"))) - .map(|config| config.join("autostart")) -} - -/// Le contenu du fichier pour lancer `executable` (avec ses arguments). -pub fn contenu(executable: &Path, arguments: &str) -> String { - // Un chemin avec espace doit être entre guillemets (spécification Desktop - // Entry, clé Exec). - let chemin = executable.display().to_string(); - let chemin = if chemin.contains(' ') { - format!("\"{}\"", chemin.replace('"', "\\\"")) - } else { - chemin - }; - let exec = if arguments.is_empty() { - chemin - } else { - format!("{chemin} {arguments}") - }; - format!( - "[Desktop Entry]\n\ - Type=Application\n\ - Name=rustscreen\n\ - Comment=Partage d'écran sur le réseau local\n\ - Exec={exec}\n\ - Terminal=false\n\ - X-GNOME-Autostart-enabled=true\n" - ) -} - -/// Écrit ou supprime le fichier dans `dossier`. -pub fn regler( - dossier: &Path, - actif: bool, - executable: &Path, - arguments: &str, -) -> std::io::Result<()> { - let fichier = dossier.join(FICHIER); - if actif { - std::fs::create_dir_all(dossier)?; - std::fs::write(fichier, contenu(executable, arguments)) - } else { - match std::fs::remove_file(fichier) { - Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), - autre => autre, - } - } -} - -pub fn est_actif(dossier: &Path) -> bool { - dossier.join(FICHIER).is_file() -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn enabling_writes_the_file_and_disabling_removes_it() { - let dossier = std::env::temp_dir().join(format!("rs-autostart-{}", std::process::id())); - let exe = Path::new("/opt/rust screen/rustscreen-desktop"); - regler(&dossier, true, exe, "--cache").unwrap(); - assert!(est_actif(&dossier)); - let texte = std::fs::read_to_string(dossier.join(FICHIER)).unwrap(); - assert!(texte.contains("Exec=\"/opt/rust screen/rustscreen-desktop\" --cache")); - regler(&dossier, false, exe, "").unwrap(); - assert!(!est_actif(&dossier)); - // Désactiver deux fois n'est pas une erreur. - regler(&dossier, false, exe, "").unwrap(); - let _ = std::fs::remove_dir_all(&dossier); - } -} diff --git a/crates/rs-platform/src/display.rs b/crates/rs-platform/src/display.rs index 4c0b711..717e025 100644 --- a/crates/rs-platform/src/display.rs +++ b/crates/rs-platform/src/display.rs @@ -1,77 +1,76 @@ -//! Quel bureau, et par quel mécanisme lui ajouter un écran virtuel. +//! Which desktop, and through which mechanism to add a virtual display to it. //! -//! Sous Linux, il n'existe pas une API d'affichage virtuel: il en existe une par -//! famille de compositeurs, et deux d'entre elles demandent les droits root. -//! Décider à l'exécution est donc obligatoire, et cette décision doit être -//! testable sans session graphique: c'est pourquoi la détection lit des -//! variables d'environnement et que les tests les injectent. +//! On Linux, there is no single virtual display API: there is one per family +//! of compositors, and two of them need root rights. Deciding at runtime is +//! therefore mandatory, and that decision must be testable without a +//! graphical session: that is why detection reads environment variables and +//! the tests inject them. use crate::portal::PortalInfo; -/// Type de session graphique. +/// Graphical session type. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SessionType { Wayland, X11, - /// Session sans serveur graphique: capture et écran virtuel impossibles. + /// Session without a display server: capture and virtual display impossible. Headless, } -/// Bureau, quand il est reconnaissable. +/// Desktop, when it can be recognised. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Desktop { Kde, Gnome, - /// Compositeur à base de wlroots (sway, hyprland, river…). + /// wlroots-based compositor (sway, hyprland, river...). Wlroots, - Autre, + Other, } -/// Par quel moyen créer une sortie d'affichage supplémentaire. +/// How to create an additional display output. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum VirtualDisplayBackend { - /// Le portail crée lui-même l'écran (type de source `VIRTUAL`): GNOME 46 et - /// KDE Plasma l'annoncent. Aucun droit particulier, et le même flux - /// PipeWire que pour un moniteur. C'est la voie retenue (ADR 0009). - PortailVirtuel, - /// wlroots: backend headless (`swaymsg create_output`), sortie native, - /// capturée ensuite comme un moniteur. Documenté, pas encore implémenté. + /// The portal creates the display itself (`VIRTUAL` source type): GNOME 46 + /// and KDE Plasma announce it. No special rights, and the same PipeWire + /// stream as for a monitor. This is the chosen path (ADR 0009). + PortalVirtual, + /// wlroots: headless backend (`swaymsg create_output`), native output, + /// then captured like a monitor. Documented, not implemented yet. WlrootsHeadless, - /// X11: `evdi` (module noyau hors arbre) ou pilote factice `xrandr`. Demande - /// les droits root et un module compilé contre le noyau courant. + /// X11: `evdi` (out-of-tree kernel module) or the `xrandr` dummy driver. + /// Needs root rights and a module built against the running kernel. /// - /// **Bonus assumé**: la cible du produit est Wayland. X11 fonctionne s'il - /// n'y a rien d'autre, mais n'est pas testé en continu et ne bloque aucune - /// livraison. + /// **Accepted bonus**: the product targets Wayland. X11 works if there is + /// nothing else, but is not tested continuously and blocks no release. Evdi, - /// Le portail ne sait pas créer d'écran et le compositeur n'offre pas - /// d'autre voie: le partage d'un écran existant reste possible. - NonSupporte, - /// Rien à faire: pas de session graphique. - Aucun, + /// The portal cannot create a display and the compositor offers no other + /// path: sharing an existing display remains possible. + Unsupported, + /// Nothing to do: no graphical session. + NotApplicable, } -/// Ce que dit l'environnement au démarrage. +/// What the environment says at startup. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Environment { pub session: SessionType, pub desktop: Desktop, - /// `XDG_CURRENT_DESKTOP` brut, pour les diagnostics : les valeurs varient - /// (`KDE`, `ubuntu:GNOME`, `sway`…). + /// Raw `XDG_CURRENT_DESKTOP`, for diagnostics: the values vary (`KDE`, + /// `ubuntu:GNOME`, `sway`...). pub desktop_raw: Option, } impl Environment { - /// Lit l'environnement réel du processus. + /// Reads the real environment of the process. pub fn detect() -> Self { - Self::from_vars(|nom| std::env::var(nom).ok()) + Self::from_vars(|name| std::env::var(name).ok()) } - /// Détection injectable, pour les tests. + /// Injectable detection, for tests. /// - /// L'ordre compte: `XDG_SESSION_TYPE` est la source la plus fiable, mais - /// certains lanceurs ne la posent pas et il faut alors déduire du socket - /// présent (`WAYLAND_DISPLAY`, `DISPLAY`). + /// Order matters: `XDG_SESSION_TYPE` is the most reliable source, but some + /// launchers do not set it, and the type must then be inferred from the + /// socket present (`WAYLAND_DISPLAY`, `DISPLAY`). pub fn from_vars(get: impl Fn(&str) -> Option) -> Self { let session = match get("XDG_SESSION_TYPE").as_deref() { Some("wayland") => SessionType::Wayland, @@ -90,17 +89,15 @@ impl Environment { let desktop_raw = get("XDG_CURRENT_DESKTOP"); let desktop = match desktop_raw.as_deref().map(str::to_ascii_lowercase) { - Some(valeur) if valeur.contains("kde") || valeur.contains("plasma") => Desktop::Kde, - Some(valeur) if valeur.contains("gnome") => Desktop::Gnome, - Some(valeur) if valeur.contains("sway") || valeur.contains("wlroots") => { - Desktop::Wlroots - } + Some(value) if value.contains("kde") || value.contains("plasma") => Desktop::Kde, + Some(value) if value.contains("gnome") => Desktop::Gnome, + Some(value) if value.contains("sway") || value.contains("wlroots") => Desktop::Wlroots, _ => { - // `SWAYSOCK` trahit wlroots même quand le bureau n'est pas nommé. + // `SWAYSOCK` gives wlroots away even when the desktop is not named. if get("SWAYSOCK").is_some() { Desktop::Wlroots } else { - Desktop::Autre + Desktop::Other } } }; @@ -112,46 +109,47 @@ impl Environment { } } - /// Le backend utilisable dans cet environnement. + /// The backend usable in this environment. /// - /// Sous Wayland, c'est le portail qui décide: on lui demande ce qu'il sait - /// faire (`AvailableSourceTypes`) au lieu de le deviner d'après le nom du - /// bureau. `None` veut dire portail injoignable ou pas encore interrogé. - pub fn virtual_display_backend(&self, portail: Option<&PortalInfo>) -> VirtualDisplayBackend { + /// Under Wayland, the portal decides: we ask it what it can do + /// (`AvailableSourceTypes`) instead of guessing from the desktop name. + /// `None` means the portal is unreachable or not queried yet. + pub fn virtual_display_backend(&self, portal: Option<&PortalInfo>) -> VirtualDisplayBackend { match self.session { - SessionType::Headless => VirtualDisplayBackend::Aucun, + SessionType::Headless => VirtualDisplayBackend::NotApplicable, SessionType::X11 => VirtualDisplayBackend::Evdi, SessionType::Wayland => { - if portail.is_some_and(PortalInfo::supporte_ecran_virtuel) { - VirtualDisplayBackend::PortailVirtuel + if portal.is_some_and(PortalInfo::supports_virtual_display) { + VirtualDisplayBackend::PortalVirtual } else if self.desktop == Desktop::Wlroots { VirtualDisplayBackend::WlrootsHeadless } else { - VirtualDisplayBackend::NonSupporte + VirtualDisplayBackend::Unsupported } } } } - /// Message pour l'utilisateur, quand il n'y a rien à faire de propre. - pub fn conseil(&self, portail: Option<&PortalInfo>) -> &'static str { - match self.virtual_display_backend(portail) { - VirtualDisplayBackend::PortailVirtuel => { - "écran virtuel possible par le portail: --virtuel étend le bureau sur la tablette" + /// Message for the user, when there is nothing clean to do. + pub fn advice(&self, portal: Option<&PortalInfo>) -> &'static str { + match self.virtual_display_backend(portal) { + VirtualDisplayBackend::PortalVirtual => { + "virtual display available through the portal: --virtuel extends the desktop \ + onto the tablet" } VirtualDisplayBackend::WlrootsHeadless => { - "wlroots: créer une sortie headless (swaymsg create_output), puis la choisir \ - dans le portail" + "wlroots: create a headless output (swaymsg create_output), then pick it \ + in the portal" } VirtualDisplayBackend::Evdi => { - "X11: bonus, non prioritaire. Écran virtuel via evdi, qui demande les droits root \ - et un module noyau; la cible du produit est Wayland" + "X11: bonus, not a priority. Virtual display through evdi, which needs root \ + rights and a kernel module; the product targets Wayland" } - VirtualDisplayBackend::NonSupporte => { - "le portail de ce bureau ne crée pas d'écran virtuel: le partage d'un écran \ - existant reste possible, l'extension non" + VirtualDisplayBackend::Unsupported => { + "this desktop's portal does not create virtual displays: sharing an existing \ + display remains possible, extending it does not" } - VirtualDisplayBackend::Aucun => "pas de session graphique: rien à capturer", + VirtualDisplayBackend::NotApplicable => "no graphical session: nothing to capture", } } } @@ -161,39 +159,39 @@ mod tests { use super::*; use std::collections::HashMap; - fn env(paires: &[(&str, &str)]) -> Environment { - let carte: HashMap = paires + fn env(pairs: &[(&str, &str)]) -> Environment { + let map: HashMap = pairs .iter() .map(|(c, v)| ((*c).to_string(), (*v).to_string())) .collect(); - Environment::from_vars(|nom| carte.get(nom).cloned()) + Environment::from_vars(|name| map.get(name).cloned()) } const GNOME_46: PortalInfo = PortalInfo { version: 5, types: 7, }; - const SANS_VIRTUEL: PortalInfo = PortalInfo { + const NO_VIRTUAL: PortalInfo = PortalInfo { version: 4, types: 3, }; #[test] fn the_portal_decides_for_kde_and_gnome() { - for bureau in ["KDE", "ubuntu:GNOME"] { + for desktop in ["KDE", "ubuntu:GNOME"] { let e = env(&[ ("XDG_SESSION_TYPE", "wayland"), - ("XDG_CURRENT_DESKTOP", bureau), + ("XDG_CURRENT_DESKTOP", desktop), ]); assert_eq!( e.virtual_display_backend(Some(&GNOME_46)), - VirtualDisplayBackend::PortailVirtuel, - "{bureau}" + VirtualDisplayBackend::PortalVirtual, + "{desktop}" ); assert_eq!( - e.virtual_display_backend(Some(&SANS_VIRTUEL)), - VirtualDisplayBackend::NonSupporte, - "{bureau}" + e.virtual_display_backend(Some(&NO_VIRTUAL)), + VirtualDisplayBackend::Unsupported, + "{desktop}" ); } } @@ -206,21 +204,21 @@ mod tests { ]); assert_eq!( e.virtual_display_backend(None), - VirtualDisplayBackend::NonSupporte + VirtualDisplayBackend::Unsupported ); - assert!(e.conseil(None).contains("existant")); + assert!(e.advice(None).contains("existing")); } #[test] fn kde_is_recognised_behind_plasma_suffix() { - // Certaines distributions annoncent `KDE`, d'autres `plasmawayland` - // ou `KDE:Plasma`. Le nom exact ne doit pas décider du support. - for nom in ["plasmawayland", "KDE:Plasma", "kde"] { + // Some distributions announce `KDE`, others `plasmawayland` or + // `KDE:Plasma`. The exact name must not decide support. + for name in ["plasmawayland", "KDE:Plasma", "kde"] { let e = env(&[ ("XDG_SESSION_TYPE", "wayland"), - ("XDG_CURRENT_DESKTOP", nom), + ("XDG_CURRENT_DESKTOP", name), ]); - assert_eq!(e.desktop, Desktop::Kde, "{nom} doit être reconnu comme KDE"); + assert_eq!(e.desktop, Desktop::Kde, "{name} must be recognised as KDE"); } } @@ -232,9 +230,9 @@ mod tests { ("SWAYSOCK", "/run/user/1000/sway-ipc.sock"), ]); assert_eq!(e.desktop, Desktop::Wlroots); - // xdg-desktop-portal-wlr n'annonce pas le type virtuel. + // xdg-desktop-portal-wlr does not announce the virtual type. assert_eq!( - e.virtual_display_backend(Some(&SANS_VIRTUEL)), + e.virtual_display_backend(Some(&NO_VIRTUAL)), VirtualDisplayBackend::WlrootsHeadless ); } @@ -257,7 +255,7 @@ mod tests { #[test] fn session_type_is_inferred_from_sockets_when_missing() { - // Des lanceurs ne posent pas XDG_SESSION_TYPE: le socket fait foi. + // Some launchers do not set XDG_SESSION_TYPE: the socket decides. assert_eq!( env(&[("WAYLAND_DISPLAY", "wayland-1")]).session, SessionType::Wayland @@ -271,7 +269,7 @@ mod tests { assert_eq!(e.session, SessionType::Headless); assert_eq!( e.virtual_display_backend(Some(&GNOME_46)), - VirtualDisplayBackend::Aucun + VirtualDisplayBackend::NotApplicable ); } @@ -279,10 +277,10 @@ mod tests { fn an_empty_environment_does_not_panic() { let e = env(&[]); assert_eq!(e.session, SessionType::Headless); - assert_eq!(e.desktop, Desktop::Autre); + assert_eq!(e.desktop, Desktop::Other); assert_eq!( e.virtual_display_backend(None), - VirtualDisplayBackend::Aucun + VirtualDisplayBackend::NotApplicable ); } } diff --git a/crates/rs-platform/src/lib.rs b/crates/rs-platform/src/lib.rs index ea4bcca..e8ef9a6 100644 --- a/crates/rs-platform/src/lib.rs +++ b/crates/rs-platform/src/lib.rs @@ -1,32 +1,32 @@ -//! Intégration système: environnement graphique, écran virtuel, veille, autostart. +//! System integration: graphical environment, virtual display, sleep, autostart. //! -//! Le cas d'usage du produit est d'étendre le bureau sur une tablette. Sous -//! Linux, cela suppose deux choses distinctes, et aucune des deux n'est -//! triviale: +//! The product's use case is extending the desktop onto a tablet. On Linux, +//! that takes two distinct things, and neither is trivial: //! -//! 1. **une sortie d'affichage qui n'existe pas physiquement** ([`display`]), -//! sinon éteindre le moniteur fait disparaître le bureau à capturer; -//! 2. **la capture de cette sortie** par le portail du bureau (issue #10). +//! 1. **a display output that does not physically exist** ([`display`]), +//! otherwise turning the monitor off makes the desktop to capture vanish; +//! 2. **capturing that output** through the desktop portal (issue #10). //! -//! [`display`] dit quel environnement est en face et par quel mécanisme créer -//! un écran virtuel; [`portal`] négocie la capture avec le bureau, écran -//! existant ou virtuel, jusqu'au descripteur PipeWire que consomme -//! `rs-capture`. Les décisions sont pures et testables sans session graphique. +//! [`display`] tells which environment we face and which mechanism creates a +//! virtual display; [`portal`] negotiates the capture with the desktop, for an +//! existing or virtual display, up to the PipeWire descriptor that +//! `rs-capture` consumes. The decisions are pure and testable without a +//! graphical session. //! -//! [`veille`] empêche la machine de s'endormir et l'écran de s'éteindre pendant -//! un partage (issue #41), et annonce le réveil pour que l'hôte reprenne la -//! capture et les sessions (issue #42). +//! [`sleep`] keeps the machine from sleeping and the screen from blanking +//! during a share (issue #41), and announces the wake-up so the host resumes +//! capture and sessions (issue #42). //! -//! [`reseau`] liste les interfaces sur lesquelles l'hôte peut écouter (#33), et -//! [`demarrage`] lance l'hôte à l'ouverture de session (#32). +//! [`network`] lists the interfaces the host can listen on (#33), and +//! [`autostart`] launches the host when the session opens (#32). -pub mod demarrage; +pub mod autostart; pub mod display; +pub mod network; pub mod portal; -pub mod reseau; -pub mod veille; +pub mod sleep; pub use display::{Desktop, Environment, SessionType, VirtualDisplayBackend}; -pub use portal::{Fermeture, Flux, PortalError, PortalInfo, Session, TypeSource}; -pub use reseau::{InterfaceReseau, interfaces}; -pub use veille::{EvenementVeille, Inhibition, Reprise, VeilleError, surveiller_reprise}; +pub use network::{NetworkInterface, interfaces}; +pub use portal::{PortalError, PortalInfo, Session, SessionClosed, SourceType, Stream}; +pub use sleep::{Inhibition, SleepError, SleepEvent, WakeWatcher, watch_wake}; diff --git a/crates/rs-platform/src/network.rs b/crates/rs-platform/src/network.rs new file mode 100644 index 0000000..1d1b23f --- /dev/null +++ b/crates/rs-platform/src/network.rs @@ -0,0 +1,131 @@ +//! Network interfaces, to choose where the host listens (#33). +//! +//! The motivating case: a machine on the guest Wi-Fi and on the wired LAN at +//! the same time. Listening everywhere exposes the screen to both; listening +//! on one interface exposes it to that one only. The choice is made by +//! **name** (`enp3s0`), not by address: a DHCP address changes, the name +//! stays. + +use std::net::IpAddr; + +use serde::Serialize; + +/// An interface as the host UI offers it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct NetworkInterface { + pub name: String, + /// IPv4 addresses first: those are what a phone reaches in practice. + pub addresses: Vec, + /// Link up (`operstate` is `up`, or unknown but with an address). + pub active: bool, + /// Loopback: never reachable from another device. + pub loopback: bool, +} + +impl NetworkInterface { + /// The address to announce and listen on: the first IPv4, else an IPv6 + /// that is not link-local (an `fe80::` needs a zone identifier that the + /// URL cannot carry). + pub fn primary_address(&self) -> Option { + self.addresses + .iter() + .copied() + .find(IpAddr::is_ipv4) + .or_else(|| { + self.addresses.iter().copied().find(|ip| match ip { + IpAddr::V6(v6) => !v6.is_unicast_link_local(), + IpAddr::V4(_) => false, + }) + }) + } +} + +/// The machine's interfaces, loopback included (flagged). +pub fn interfaces() -> Vec { + let mut list: Vec = Vec::new(); + for interface in if_addrs::get_if_addrs().unwrap_or_default() { + let ip = interface.ip(); + match list.iter_mut().find(|i| i.name == interface.name) { + Some(existing) => existing.addresses.push(ip), + None => list.push(NetworkInterface { + name: interface.name.clone(), + addresses: vec![ip], + active: false, + loopback: interface.is_loopback(), + }), + } + } + for interface in &mut list { + interface.addresses.sort_by_key(|ip| !ip.is_ipv4()); + interface.active = is_up(link_state(&interface.name).as_deref()); + } + list.sort_by(|a, b| (a.loopback, &a.name).cmp(&(b.loopback, &b.name))); + list +} + +/// The interface with this name, if it exists and carries an address. +pub fn interface(name: &str) -> Option { + interfaces().into_iter().find(|i| i.name == name) +} + +/// Kernel `operstate`. Missing outside Linux: we do not know, we do not say no. +fn link_state(name: &str) -> Option { + std::fs::read_to_string(format!("/sys/class/net/{name}/operstate")) + .ok() + .map(|s| s.trim().to_string()) +} + +/// `unknown` is the state of many virtual interfaces (VPN, tun) that work +/// nonetheless: only an interface explicitly `down` (or `dormant`, +/// `lowerlayerdown`) is considered cut off. +fn is_up(state: Option<&str>) -> bool { + !matches!( + state, + Some("down" | "dormant" | "lowerlayerdown" | "notpresent") + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn interface(addresses: &[&str]) -> NetworkInterface { + NetworkInterface { + name: "test0".into(), + addresses: addresses.iter().map(|a| a.parse().unwrap()).collect(), + active: true, + loopback: false, + } + } + + #[test] + fn ipv4_comes_first_and_link_local_v6_is_never_announced() { + assert_eq!( + interface(&["fe80::1", "192.168.1.20"]).primary_address(), + Some("192.168.1.20".parse().unwrap()) + ); + assert_eq!(interface(&["fe80::1"]).primary_address(), None); + assert_eq!( + interface(&["fe80::1", "2001:db8::5"]).primary_address(), + Some("2001:db8::5".parse().unwrap()) + ); + } + + #[test] + fn only_an_explicitly_down_link_is_inactive() { + assert!(is_up(Some("up"))); + assert!(is_up(Some("unknown"))); + assert!(is_up(None)); + assert!(!is_up(Some("down"))); + assert!(!is_up(Some("lowerlayerdown"))); + } + + #[test] + fn this_machine_has_a_loopback_listed_last() { + let list = interfaces(); + let loopback = list.iter().position(|i| i.loopback); + if let Some(position) = loopback { + assert!(list[position..].iter().all(|i| i.loopback)); + } + } +} diff --git a/crates/rs-platform/src/portal.rs b/crates/rs-platform/src/portal.rs index cf47ab1..9fa41c1 100644 --- a/crates/rs-platform/src/portal.rs +++ b/crates/rs-platform/src/portal.rs @@ -1,14 +1,14 @@ -//! Portail du bureau: la seule voie de capture sous Wayland. +//! Desktop portal: the only capture path under Wayland. //! -//! Depuis Wayland, aucune application ne lit l'écran directement: elle demande -//! au portail (`xdg-desktop-portal`), qui affiche un sélecteur à l'utilisateur et -//! rend un flux PipeWire. C'est une contrainte du modèle de sécurité, pas un -//! détail d'implémentation: sans portail, il n'y a pas de capture. +//! Since Wayland, no application reads the screen directly: it asks the portal +//! (`xdg-desktop-portal`), which shows a picker to the user and returns a +//! PipeWire stream. This is a constraint of the security model, not an +//! implementation detail: without a portal, there is no capture. //! -//! Ce module va jusqu'au **descripteur du flux**, et pas plus loin. Consommer les -//! images demande `libpipewire`, une dépendance système que la négociation -//! n'exige pas. Séparer les deux permet de vérifier la négociation seule, sur une -//! machine qui a un bureau, avant d'ajouter le reste. +//! This module goes as far as the **stream descriptor**, and no further. +//! Consuming the frames needs `libpipewire`, a system dependency that the +//! negotiation does not need. Keeping the two apart lets the negotiation be +//! checked alone, on a machine with a desktop, before adding the rest. use std::collections::HashMap; use std::os::fd::OwnedFd; @@ -20,362 +20,362 @@ use zbus::{Connection, MatchRule, MessageStream}; use zbus::{OwnedObjectPath, OwnedVariant, Variant}; const BUS: &str = "org.freedesktop.portal.Desktop"; -const CHEMIN_PORTAIL: &str = "/org/freedesktop/portal/desktop"; -const INTERFACE_PROPRIETES: &str = "org.freedesktop.DBus.Properties"; -const INTERFACE_SCREENCAST: &str = "org.freedesktop.portal.ScreenCast"; -const INTERFACE_REQUEST: &str = "org.freedesktop.portal.Request"; -const INTERFACE_SESSION: &str = "org.freedesktop.portal.Session"; +const PORTAL_PATH: &str = "/org/freedesktop/portal/desktop"; +const PROPERTIES_INTERFACE: &str = "org.freedesktop.DBus.Properties"; +const SCREENCAST_INTERFACE: &str = "org.freedesktop.portal.ScreenCast"; +const REQUEST_INTERFACE: &str = "org.freedesktop.portal.Request"; +const SESSION_INTERFACE: &str = "org.freedesktop.portal.Session"; -/// Types de sources de `SelectSources`, en masque de bits. -pub const TYPE_MONITEUR: u32 = 1; -pub const TYPE_FENETRE: u32 = 2; -pub const TYPE_VIRTUEL: u32 = 4; +/// Source types of `SelectSources`, as a bit mask. +pub const TYPE_MONITOR: u32 = 1; +pub const TYPE_WINDOW: u32 = 2; +pub const TYPE_VIRTUAL: u32 = 4; -/// Compteur des jetons: un objet request par appel. Un jeton réutilisé fait -/// répondre le portail sur un objet déjà consommé, et la réponse se perd. -static COMPTEUR: AtomicU32 = AtomicU32::new(0); +/// Token counter: one request object per call. A reused token makes the +/// portal answer on an already consumed object, and the answer is lost. +static COUNTER: AtomicU32 = AtomicU32::new(0); -/// Jeton unique dans ce processus, valide dans un chemin D-Bus. -fn jeton(prefixe: &str) -> String { - let n = COMPTEUR.fetch_add(1, Ordering::Relaxed); - format!("rustscreen_{}_{prefixe}_{n}", std::process::id()) +/// Token unique within this process, valid in a D-Bus path. +fn token(prefix: &str) -> String { + let n = COUNTER.fetch_add(1, Ordering::Relaxed); + format!("rustscreen_{}_{prefix}_{n}", std::process::id()) } -/// Le portail attend une réponse de l'utilisateur devant un sélecteur. Deux -/// minutes laissent le temps de choisir un écran, sans laisser un service -/// bloqué indéfiniment si personne ne répond. -const DELAI_REPONSE: Duration = Duration::from_secs(120); +/// The portal waits for the user's answer in front of a picker. Two minutes +/// leave time to choose a display, without leaving a service blocked forever +/// if nobody answers. +const RESPONSE_TIMEOUT: Duration = Duration::from_secs(120); #[derive(Debug, thiserror::Error)] pub enum PortalError { - #[error("pas de bus de session D-Bus: {0}")] + #[error("no D-Bus session bus: {0}")] Bus(String), - #[error("portail injoignable: {0}")] - Injoignable(String), - #[error("le portail ne répond pas correctement: {0}")] - Reponse(String), - #[error("demande annulée par l'utilisateur: {0}")] - Refuse(String), - #[error("aucune réponse du portail en {} s", DELAI_REPONSE.as_secs())] - Delai, - #[error("le portail a rendu une réponse sans flux exploitable: {0}")] - SansFlux(String), + #[error("portal unreachable: {0}")] + Unreachable(String), + #[error("the portal does not answer correctly: {0}")] + Response(String), + #[error("request cancelled by the user: {0}")] + Denied(String), + #[error("no answer from the portal within {} s", RESPONSE_TIMEOUT.as_secs())] + Timeout, + #[error("the portal returned an answer without a usable stream: {0}")] + NoStream(String), } -/// Ce que le portail annonce. +/// What the portal announces. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct PortalInfo { - /// Version de l'interface ScreenCast. + /// Version of the ScreenCast interface. pub version: u32, - /// `AvailableSourceTypes`: masque de [`TYPE_MONITEUR`], [`TYPE_FENETRE`], - /// [`TYPE_VIRTUEL`]. C'est lui qui dit si le bureau sait créer un écran - /// virtuel, pas le nom du bureau ni la version de l'interface. + /// `AvailableSourceTypes`: mask of [`TYPE_MONITOR`], [`TYPE_WINDOW`], + /// [`TYPE_VIRTUAL`]. This is what tells whether the desktop can create a + /// virtual display, not the desktop name nor the interface version. pub types: u32, } impl PortalInfo { - /// Le portail sait créer une sortie d'affichage qui n'existe pas - /// physiquement (GNOME 46 et xdg-desktop-portal-kde l'annoncent). - pub fn supporte_ecran_virtuel(&self) -> bool { - self.types & TYPE_VIRTUEL != 0 + /// The portal can create a display output that does not physically exist + /// (GNOME 46 and xdg-desktop-portal-kde announce it). + pub fn supports_virtual_display(&self) -> bool { + self.types & TYPE_VIRTUAL != 0 } - pub fn supporte_fenetre(&self) -> bool { - self.types & TYPE_FENETRE != 0 + pub fn supports_window(&self) -> bool { + self.types & TYPE_WINDOW != 0 } } -/// Ce que l'on demande au sélecteur. +/// What we ask the picker for. #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum TypeSource { - /// Un écran qui existe: le partage montre ce que l'on voit déjà. - Moniteur, - /// Un écran créé pour l'occasion: le bureau s'étend sur la tablette. - Virtuel, - /// Une fenêtre, choisie dans le sélecteur du bureau (#17). Le flux ne - /// contient qu'elle; réduite, elle cesse d'envoyer des images. - Fenetre, +pub enum SourceType { + /// An existing display: the share shows what one already sees. + Monitor, + /// A display created for the occasion: the desktop extends onto the tablet. + Virtual, + /// A window, chosen in the desktop's picker (#17). The stream contains + /// only that window; once minimised, it stops sending frames. + Window, } -impl TypeSource { - fn masque(self) -> u32 { +impl SourceType { + fn mask(self) -> u32 { match self { - Self::Moniteur => TYPE_MONITEUR, - Self::Virtuel => TYPE_VIRTUEL, - Self::Fenetre => TYPE_FENETRE, + Self::Monitor => TYPE_MONITOR, + Self::Virtual => TYPE_VIRTUAL, + Self::Window => TYPE_WINDOW, } } } -/// Un flux capturé: le descripteur PipeWire et son identifiant de nœud. -pub struct Flux { +/// A captured stream: the PipeWire descriptor and its node identifier. +pub struct Stream { pub node_id: u32, pub fd: OwnedFd, - /// Taille annoncée par le portail, quand il la fournit. - pub taille: Option<(u32, u32)>, - /// Jeton qui évite de redemander le choix au prochain lancement, quand le - /// portail en rend un (mode persistant). - pub jeton_restauration: Option, + /// Size announced by the portal, when it provides one. + pub size: Option<(u32, u32)>, + /// Token that avoids asking for the choice again at the next launch, when + /// the portal returns one (persistent mode). + pub restore_token: Option, } -impl std::fmt::Debug for Flux { +impl std::fmt::Debug for Stream { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("Flux") + f.debug_struct("Stream") .field("node_id", &self.node_id) - .field("taille", &self.taille) + .field("size", &self.size) .field("fd", &self.fd) - .field("restaurable", &self.jeton_restauration.is_some()) + .field("restorable", &self.restore_token.is_some()) .finish() } } -/// Une session d'enregistrement ouverte. La garder vivante maintient la capture; -/// la fermer libère le flux et coupe le partage côté portail. +/// An open screencast session. Keeping it alive keeps the capture going; +/// closing it frees the stream and stops the share on the portal side. pub struct Session { - connexion: Connection, - chemin: OwnedObjectPath, + connection: Connection, + path: OwnedObjectPath, } impl Session { - /// Ouvre une session d'enregistrement d'écran. + /// Opens a screencast session. /// - /// N'affiche encore rien: le sélecteur n'apparaît qu'à l'étape `demarrer`, - /// ce qui laisse le temps de choisir les options. - pub async fn ouvrir() -> Result { - let connexion = Connection::session() + /// Shows nothing yet: the picker only appears at the `start` step, which + /// leaves time to choose the options. + pub async fn open() -> Result { + let connection = Connection::session() .await .map_err(|e| PortalError::Bus(e.to_string()))?; let mut options: HashMap = HashMap::new(); - let jeton_session = jeton("session"); + let session_token = token("session"); options.insert( "session_handle_token".into(), - Variant::from(jeton_session.as_str()), + Variant::from(session_token.as_str()), ); - let jeton = jeton("creer"); - options.insert("handle_token".into(), Variant::from(jeton.as_str())); + let token = token("create"); + options.insert("handle_token".into(), Variant::from(token.as_str())); - let resultats = appeler( - &connexion, - CHEMIN_PORTAIL, - INTERFACE_SCREENCAST, + let results = call( + &connection, + PORTAL_PATH, + SCREENCAST_INTERFACE, "CreateSession", &(options,), - &jeton, + &token, ) .await?; - let handle = resultats + let handle = results .get("session_handle") - .ok_or_else(|| PortalError::Reponse("session_handle absent".into()))?; - let chemin = match &**handle { - Variant::Str(chemin) => { - OwnedObjectPath::try_from(chemin.as_str()).map_err(|e| e.to_string()) + .ok_or_else(|| PortalError::Response("session_handle missing".into()))?; + let path = match &**handle { + Variant::Str(path) => { + OwnedObjectPath::try_from(path.as_str()).map_err(|e| e.to_string()) } - // Un ObjectPath se possède sans échec possible. - Variant::ObjectPath(chemin) => Ok::<_, String>(OwnedObjectPath::from(chemin.clone())), - autre => { - return Err(PortalError::Reponse(format!( - "session_handle de type inattendu: {autre:?}" + // An ObjectPath can be owned without any possible failure. + Variant::ObjectPath(path) => Ok::<_, String>(OwnedObjectPath::from(path.clone())), + other => { + return Err(PortalError::Response(format!( + "session_handle of unexpected type: {other:?}" ))); } } - .map_err(PortalError::Reponse)?; + .map_err(PortalError::Response)?; - Ok(Self { connexion, chemin }) + Ok(Self { connection, path }) } - /// Demande le partage d'un écran entier, existant ou virtuel. + /// Asks to share a whole display, existing or virtual. /// - /// `multiple` reste faux: un second écran n'a pas besoin d'être multiple, - /// et un sélecteur simple est moins intimidant. - pub async fn choisir_un_ecran(&self, restaurer: Option<&str>) -> Result<(), PortalError> { - self.choisir(TypeSource::Moniteur, restaurer).await + /// `multiple` stays false: a second display does not need to be multiple, + /// and a simple picker is less intimidating. + pub async fn select_monitor(&self, restore: Option<&str>) -> Result<(), PortalError> { + self.select_source(SourceType::Monitor, restore).await } - /// Demande une source du type donné. Pour un écran virtuel, le sélecteur - /// n'a rien à proposer: GNOME le crée directement, à la taille que fixera - /// le consommateur PipeWire. - pub async fn choisir( + /// Asks for a source of the given type. For a virtual display, the picker + /// has nothing to offer: GNOME creates it directly, at the size the + /// PipeWire consumer will set. + pub async fn select_source( &self, - type_source: TypeSource, - restaurer: Option<&str>, + source_type: SourceType, + restore: Option<&str>, ) -> Result<(), PortalError> { let mut options: HashMap = HashMap::new(); - let jeton = jeton("sources"); - options.insert("handle_token".into(), Variant::from(jeton.as_str())); - options.insert("types".into(), Variant::from(type_source.masque())); + let token = token("sources"); + options.insert("handle_token".into(), Variant::from(token.as_str())); + options.insert("types".into(), Variant::from(source_type.mask())); options.insert("multiple".into(), Variant::from(false)); - // Curseur inclus dans l'image: sans lui, un spectateur ne voit pas où - // l'hôte clique, ce qui rend le partage inutilisable pour expliquer. + // Cursor embedded in the frame: without it, a viewer does not see + // where the host clicks, which makes the share useless for explaining. options.insert("cursor_mode".into(), Variant::from(2u32)); - // Un écran virtuel n'a rien à restaurer: il est recréé à chaque fois. - // Pour un moniteur, 2 = persistant: le portail rend un jeton qui évite - // de revalider le choix à chaque lancement. - if type_source == TypeSource::Moniteur { - if let Some(jeton_restauration) = restaurer { + // A virtual display has nothing to restore: it is recreated every + // time. For a monitor, 2 = persistent: the portal returns a token that + // avoids confirming the choice again at each launch. + if source_type == SourceType::Monitor { + if let Some(restore_token) = restore { options.insert( "restore_token".into(), - Variant::from(jeton_restauration.to_string()), + Variant::from(restore_token.to_string()), ); } options.insert("persist_mode".into(), Variant::from(2u32)); } - appeler( - &self.connexion, - // Les méthodes vivent sur l'objet portail; la session est le - // premier argument, pas la cible de l'appel. - CHEMIN_PORTAIL, - INTERFACE_SCREENCAST, + call( + &self.connection, + // The methods live on the portal object; the session is the first + // argument, not the target of the call. + PORTAL_PATH, + SCREENCAST_INTERFACE, "SelectSources", - &(&self.chemin, options), - &jeton, + &(&self.path, options), + &token, ) .await?; Ok(()) } - /// Démarre la capture. C'est ici que le sélecteur s'affiche. - pub async fn demarrer(&self) -> Result { + /// Starts the capture. This is where the picker shows up. + pub async fn start(&self) -> Result { let mut options: HashMap = HashMap::new(); - let jeton = jeton("demarrer"); - options.insert("handle_token".into(), Variant::from(jeton.as_str())); + let token = token("start"); + options.insert("handle_token".into(), Variant::from(token.as_str())); - // Start prend trois arguments: session, fenêtre parente (vide: pas de - // dialogue modal rattaché à une fenêtre), options. - let resultats = appeler( - &self.connexion, - // Les méthodes vivent sur l'objet portail; la session est le - // premier argument, pas la cible de l'appel. - CHEMIN_PORTAIL, - INTERFACE_SCREENCAST, + // Start takes three arguments: session, parent window (empty: no modal + // dialog attached to a window), options. + let results = call( + &self.connection, + // The methods live on the portal object; the session is the first + // argument, not the target of the call. + PORTAL_PATH, + SCREENCAST_INTERFACE, "Start", - &(&self.chemin, "", options), - &jeton, + &(&self.path, "", options), + &token, ) .await?; - let (node_id, taille) = premier_flux(resultats.get("streams"))?; - let jeton_restauration = resultats + let (node_id, size) = first_stream(results.get("streams"))?; + let restore_token = results .get("restore_token") .and_then(|v| String::try_from(v.clone()).ok()); - // Le descripteur n'est pas dans la réponse de `Start`: il se demande à - // part, par `OpenPipeWireRemote`, une fois la capture accordée. + // The descriptor is not in the answer to `Start`: it is requested + // separately, through `OpenPipeWireRemote`, once the capture is granted. let options: HashMap = HashMap::new(); - let reponse = self - .connexion + let reply = self + .connection .call_method( Some(BUS), - CHEMIN_PORTAIL, - Some(INTERFACE_SCREENCAST), + PORTAL_PATH, + Some(SCREENCAST_INTERFACE), "OpenPipeWireRemote", - &(&self.chemin, options), + &(&self.path, options), ) .await - .map_err(|e| PortalError::SansFlux(format!("OpenPipeWireRemote: {e}")))?; - // La désérialisation duplique le descripteur (`dup`): la copie nous - // appartient et survit au message D-Bus qui portait l'original. - let fd: OwnedFd = reponse + .map_err(|e| PortalError::NoStream(format!("OpenPipeWireRemote: {e}")))?; + // Deserialization duplicates the descriptor (`dup`): the copy belongs + // to us and outlives the D-Bus message that carried the original. + let fd: OwnedFd = reply .body() .deserialize::() - .map_err(|e| PortalError::SansFlux(format!("descripteur illisible: {e}")))? + .map_err(|e| PortalError::NoStream(format!("unreadable descriptor: {e}")))? .into(); - Ok(Flux { + Ok(Stream { node_id, fd, - taille, - jeton_restauration, + size, + restore_token, }) } - /// Ferme la session côté portail. C'est l'objet session qui porte - /// `Close`, pas l'objet request: appeler le second ne ferme rien. - pub async fn fermer(&self) { + /// Closes the session on the portal side. The session object carries + /// `Close`, not the request object: calling the latter closes nothing. + pub async fn close(&self) { let _ = self - .connexion + .connection .call_method( Some(BUS), - self.chemin.as_str(), - Some(INTERFACE_SESSION), + self.path.as_str(), + Some(SESSION_INTERFACE), "Close", &(), ) .await; } - /// Prépare l'écoute de la fermeture de la session par le bureau (bouton - /// « arrêter le partage » de GNOME, révocation). À appeler avant - /// `demarrer`: un signal émis avant l'abonnement serait perdu. - pub async fn surveiller_fermeture(&self) -> Result { - let regle = MatchRule::builder() + /// Prepares to listen for the desktop closing the session (GNOME's "stop + /// sharing" button, revocation). Call it before `start`: a signal emitted + /// before the subscription would be lost. + pub async fn watch_closed(&self) -> Result { + let rule = MatchRule::builder() .msg_type(zbus::message::Type::Signal) - .interface(INTERFACE_SESSION) + .interface(SESSION_INTERFACE) .member("Closed") - .path(self.chemin.as_str()) + .path(self.path.as_str()) .build() - .map_err(|e| PortalError::Reponse(e.to_string()))?; - let flux = MessageStream::for_match_rule(regle, &self.connexion, None) + .map_err(|e| PortalError::Response(e.to_string()))?; + let stream = MessageStream::for_match_rule(rule, &self.connection, None) .await - .map_err(|e| PortalError::Reponse(e.to_string()))?; - Ok(Fermeture { flux }) + .map_err(|e| PortalError::Response(e.to_string()))?; + Ok(SessionClosed { stream }) } - pub fn chemin(&self) -> &str { - self.chemin.as_str() + pub fn path(&self) -> &str { + self.path.as_str() } } -/// Attente de la fermeture d'une session par le bureau. -pub struct Fermeture { - flux: MessageStream, +/// Waiting for the desktop to close a session. +pub struct SessionClosed { + stream: MessageStream, } -impl Fermeture { - /// Rend la main quand le bureau a fermé la session: l'utilisateur a arrêté - /// le partage, ou le compositeur a retiré l'écran. - pub async fn attendre(mut self) { - // Le flux ne se termine qu'avec la connexion: dans les deux cas, la - // capture est finie. - let _ = self.flux.next().await; +impl SessionClosed { + /// Returns when the desktop has closed the session: the user stopped the + /// share, or the compositor removed the display. + pub async fn wait(mut self) { + // The stream only ends with the connection: either way, the capture + // is over. + let _ = self.stream.next().await; } } -/// Extrait l'identifiant et la taille du premier flux de la réponse. +/// Extracts the identifier and size of the first stream in the answer. /// -/// Le portail rend `a(ua{sv})`: un identifiant de nœud, puis des propriétés dont -/// seule la taille nous intéresse pour l'instant. -fn premier_flux(valeur: Option<&OwnedVariant>) -> Result<(u32, Option<(u32, u32)>), PortalError> { - let valeur = valeur.ok_or_else(|| PortalError::SansFlux("streams absent".into()))?; - let liste = match &**valeur { - Variant::Array(liste) => liste, - autre => { - return Err(PortalError::SansFlux(format!( - "streams de type inattendu: {autre:?}" +/// The portal returns `a(ua{sv})`: a node identifier, then properties of which +/// only the size matters to us for now. +fn first_stream(value: Option<&OwnedVariant>) -> Result<(u32, Option<(u32, u32)>), PortalError> { + let value = value.ok_or_else(|| PortalError::NoStream("streams missing".into()))?; + let list = match &**value { + Variant::Array(list) => list, + other => { + return Err(PortalError::NoStream(format!( + "streams of unexpected type: {other:?}" ))); } }; - let premier = liste + let first = list .first() - .ok_or_else(|| PortalError::SansFlux("aucun flux dans streams".into()))?; - let structure = match premier { + .ok_or_else(|| PortalError::NoStream("no stream in streams".into()))?; + let structure = match first { Variant::Structure(structure) => structure, - autre => { - return Err(PortalError::SansFlux(format!( - "flux de type inattendu: {autre:?}" + other => { + return Err(PortalError::NoStream(format!( + "stream of unexpected type: {other:?}" ))); } }; - let champs = structure.fields(); - let node_id = champs + let fields = structure.fields(); + let node_id = fields .first() .and_then(|v| u32::try_from(v.clone()).ok()) - .ok_or_else(|| PortalError::SansFlux("identifiant de nœud illisible".into()))?; + .ok_or_else(|| PortalError::NoStream("unreadable node identifier".into()))?; - // La taille annoncée par le portail sert aux journaux; celle qui fait - // autorité est le format négocié côté PipeWire. - let taille = champs.get(1).and_then(|proprietes| match proprietes { + // The size announced by the portal is for the logs; the authoritative one + // is the format negotiated on the PipeWire side. + let size = fields.get(1).and_then(|properties| match properties { Variant::Dict(dict) => { dict.get::<_, Variant>(&"size") .ok() @@ -392,139 +392,138 @@ fn premier_flux(valeur: Option<&OwnedVariant>) -> Result<(u32, Option<(u32, u32) } _ => None, }); - Ok((node_id, taille)) + Ok((node_id, size)) } -/// Appelle une méthode du portail et attend sa réponse. +/// Calls a portal method and waits for its answer. /// -/// L'abonnement au signal précède l'appel: le signal peut partir avant qu'on ne -/// s'abonne, et une réponse perdue se traduit par un blocage de deux minutes. +/// The signal subscription comes before the call: the signal may leave before +/// we subscribe, and a lost answer turns into a two-minute hang. /// -/// Le corps est la liste des arguments, pas une variante: emballé dans une -/// `Variant`, il part en signature `(v)` et le portail le refuse -/// (`InvalidArgs`), erreur que seule une vraie session révèle. -async fn appeler( - connexion: &Connection, - objet: &str, +/// The body is the argument list, not a variant: wrapped in a `Variant`, it +/// goes out with signature `(v)` and the portal rejects it (`InvalidArgs`), an +/// error that only a real session reveals. +async fn call( + connection: &Connection, + object: &str, interface: &str, - methode: &str, - corps: &B, - jeton: &str, + method: &str, + body: &B, + token: &str, ) -> Result, PortalError> where B: serde::Serialize + zbus::zvariant::DynamicType, { - let chemin_reponse = chemin_request(connexion, jeton)?; - let regle = MatchRule::builder() + let response_path = request_path(connection, token)?; + let rule = MatchRule::builder() .msg_type(zbus::message::Type::Signal) - .interface(INTERFACE_REQUEST) + .interface(REQUEST_INTERFACE) .member("Response") - .path(chemin_reponse.as_str()) + .path(response_path.as_str()) .build() - .map_err(|e| PortalError::Reponse(e.to_string()))?; - let mut flux = MessageStream::for_match_rule(regle, connexion, std::num::NonZeroUsize::new(4)) - .await - .map_err(|e| PortalError::Reponse(e.to_string()))?; + .map_err(|e| PortalError::Response(e.to_string()))?; + let mut stream = + MessageStream::for_match_rule(rule, connection, std::num::NonZeroUsize::new(4)) + .await + .map_err(|e| PortalError::Response(e.to_string()))?; - connexion - .call_method(Some(BUS), objet, Some(interface), methode, corps) + connection + .call_method(Some(BUS), object, Some(interface), method, body) .await - .map_err(|e| PortalError::Injoignable(e.to_string()))?; + .map_err(|e| PortalError::Unreachable(e.to_string()))?; - let message = tokio::time::timeout(DELAI_REPONSE, flux.next()) + let message = tokio::time::timeout(RESPONSE_TIMEOUT, stream.next()) .await - .map_err(|_| PortalError::Delai)? - .ok_or_else(|| PortalError::Reponse("flux de réponses fermé".into()))? - .map_err(|e| PortalError::Reponse(e.to_string()))?; + .map_err(|_| PortalError::Timeout)? + .ok_or_else(|| PortalError::Response("response stream closed".into()))? + .map_err(|e| PortalError::Response(e.to_string()))?; - let (code, resultats): (u32, HashMap) = message + let (code, results): (u32, HashMap) = message .body() .deserialize() - .map_err(|e| PortalError::Reponse(e.to_string()))?; + .map_err(|e| PortalError::Response(e.to_string()))?; match code { - 0 => Ok(resultats), - 1 => Err(PortalError::Refuse( - "demande annulée par l'utilisateur".into(), - )), - // 2 = « autre erreur ». Vu en vrai: le service du bureau - // (xdg-desktop-portal-gnome) s'arrête quand il est inactif, et sa - // première réponse après redémarrage échoue avant que ScreenCast soit - // prêt. Relancer quelques secondes plus tard suffit. - 2 => Err(PortalError::Reponse( - "le portail du bureau a échoué (code 2): il redémarrait peut-être, \ - réessayer dans quelques secondes" + 0 => Ok(results), + 1 => Err(PortalError::Denied("request cancelled by the user".into())), + // 2 = "other error". Seen for real: the desktop service + // (xdg-desktop-portal-gnome) stops when idle, and its first answer + // after a restart fails before ScreenCast is ready. Retrying a few + // seconds later is enough. + 2 => Err(PortalError::Response( + "the desktop portal failed (code 2): it may have been restarting, \ + retry in a few seconds" .into(), )), - autre => Err(PortalError::Reponse(format!( - "le portail a répondu {autre}" + other => Err(PortalError::Response(format!( + "the portal answered {other}" ))), } } -/// Le chemin de l'objet request suit une convention dérivée du nom unique sur le -/// bus: `:1.42` devient `1_42`. -fn chemin_request(connexion: &Connection, jeton: &str) -> Result { - let unique = connexion +/// The request object path follows a convention derived from the unique name +/// on the bus: `:1.42` becomes `1_42`. +fn request_path(connection: &Connection, token: &str) -> Result { + let unique = connection .unique_name() - .ok_or_else(|| PortalError::Bus("pas de nom unique sur le bus".into()))? + .ok_or_else(|| PortalError::Bus("no unique name on the bus".into()))? .as_str() .to_string(); - if !jeton.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') { - // Le jeton finit dans un chemin D-Bus: un caractère interdit doit être - // refusé ici, pas par un message obscur du bus. - return Err(PortalError::Reponse(format!("jeton invalide: {jeton}"))); + if !token.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') { + // The token ends up in a D-Bus path: a forbidden character must be + // rejected here, not by an obscure bus message. + return Err(PortalError::Response(format!("invalid token: {token}"))); } - let expediteur = unique.trim_start_matches(':').replace('.', "_"); - Ok(format!("{CHEMIN_PORTAIL}/request/{expediteur}/{jeton}")) + let sender = unique.trim_start_matches(':').replace('.', "_"); + Ok(format!("{PORTAL_PATH}/request/{sender}/{token}")) } -/// Interroge le portail. +/// Queries the portal. /// -/// Ne déclenche aucune demande de consentement: on lit seulement la version de -/// l'interface, ce qui ne demande pas d'autorisation utilisateur. +/// Triggers no consent request: we only read the interface version, which +/// needs no user authorisation. pub async fn probe() -> Result { - let connexion = Connection::session() + let connection = Connection::session() .await .map_err(|e| PortalError::Bus(e.to_string()))?; - let version = propriete(&connexion, "version").await?; - // Absente des très vieux portails: on la considère alors comme « moniteurs - // seulement », ce qui est la seule chose qu'ils savaient faire. - let types = propriete(&connexion, "AvailableSourceTypes") + let version = property(&connection, "version").await?; + // Missing from very old portals: it is then taken as "monitors only", + // which is the only thing they could do. + let types = property(&connection, "AvailableSourceTypes") .await - .unwrap_or(TYPE_MONITEUR); + .unwrap_or(TYPE_MONITOR); Ok(PortalInfo { version, types }) } -/// Lit une propriété entière de l'interface ScreenCast. -async fn propriete(connexion: &Connection, nom: &str) -> Result { - let reponse = connexion +/// Reads an integer property of the ScreenCast interface. +async fn property(connection: &Connection, name: &str) -> Result { + let reply = connection .call_method( Some(BUS), - CHEMIN_PORTAIL, - Some(INTERFACE_PROPRIETES), + PORTAL_PATH, + Some(PROPERTIES_INTERFACE), "Get", - &(INTERFACE_SCREENCAST, nom), + &(SCREENCAST_INTERFACE, name), ) .await .map_err(|e| match e { - zbus::Error::MethodError(nom, _, _) - if nom.as_str().contains("UnknownInterface") - || nom.as_str().contains("UnknownObject") - || nom.as_str().contains("UnknownService") => + zbus::Error::MethodError(error_name, _, _) + if error_name.as_str().contains("UnknownInterface") + || error_name.as_str().contains("UnknownObject") + || error_name.as_str().contains("UnknownService") => { - PortalError::Injoignable("le service ScreenCast n'est pas exposé".into()) + PortalError::Unreachable("the ScreenCast service is not exposed".into()) } - autre => PortalError::Injoignable(autre.to_string()), + other => PortalError::Unreachable(other.to_string()), })?; - // La propriété arrive empaquetée dans une variante (`v`). - reponse + // The property arrives wrapped in a variant (`v`). + reply .body() .deserialize::() - .map_err(|e| PortalError::Reponse(e.to_string()))? + .map_err(|e| PortalError::Response(e.to_string()))? .downcast::() - .map_err(|_| PortalError::Reponse(format!("{nom} n'est pas un entier"))) + .map_err(|_| PortalError::Response(format!("{name} is not an integer"))) } #[cfg(test)] @@ -533,47 +532,48 @@ mod tests { #[test] fn a_virtual_display_is_read_from_the_source_types() { - // GNOME 46 annonce 7 (moniteur, fenêtre, virtuel) en version 5. La - // version seule ne dit rien: un portail v5 sans type 4 ne crée rien. + // GNOME 46 announces 7 (monitor, window, virtual) in version 5. The + // version alone says nothing: a v5 portal without type 4 creates + // nothing. let gnome = PortalInfo { version: 5, types: 7, }; - assert!(gnome.supporte_ecran_virtuel()); - assert!(gnome.supporte_fenetre()); - let ancien = PortalInfo { + assert!(gnome.supports_virtual_display()); + assert!(gnome.supports_window()); + let old = PortalInfo { version: 5, - types: TYPE_MONITEUR | TYPE_FENETRE, + types: TYPE_MONITOR | TYPE_WINDOW, }; - assert!(!ancien.supporte_ecran_virtuel()); + assert!(!old.supports_virtual_display()); } #[test] fn tokens_are_unique_and_valid_in_a_path() { - let a = jeton("x"); - let b = jeton("x"); - assert_ne!(a, b, "un jeton réutilisé perd la réponse du portail"); - for j in [a, b] { + let a = token("x"); + let b = token("x"); + assert_ne!(a, b, "a reused token loses the portal's answer"); + for t in [a, b] { assert!( - j.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'), - "{j}" + t.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'), + "{t}" ); } } - /// Sur une machine sans portail, l'échec doit être expliqué, pas paniquer. - /// Le test accepte les deux issues: il vérifie le comportement, pas - /// l'environnement de la machine de test. + /// On a machine without a portal, the failure must be explained, not + /// panic. The test accepts both outcomes: it checks the behaviour, not the + /// environment of the test machine. #[tokio::test] async fn probing_never_panics_and_explains_failure() { match probe().await { - Ok(info) => assert!(info.version > 0, "une version nulle n'a pas de sens"), - Err(erreur) => { - let message = erreur.to_string(); - assert!(!message.is_empty(), "l'erreur doit être lisible"); + Ok(info) => assert!(info.version > 0, "a zero version makes no sense"), + Err(error) => { + let message = error.to_string(); + assert!(!message.is_empty(), "the error must be readable"); assert!( - message.contains("portail") || message.contains("D-Bus"), - "message inattendu: {message}" + message.contains("portal") || message.contains("D-Bus"), + "unexpected message: {message}" ); } } @@ -581,15 +581,15 @@ mod tests { #[tokio::test] async fn opening_a_session_without_portal_fails_cleanly() { - // Sans portail, l'ouverture doit rendre une erreur lisible, jamais - // bloquer: c'est le cas de toute machine sans xdg-desktop-portal. - match Session::ouvrir().await { - Ok(session) => assert!(session.chemin().starts_with("/org/freedesktop/portal")), - Err(erreur) => { - let message = erreur.to_string(); + // Without a portal, opening must return a readable error, never hang: + // this is the case of any machine without xdg-desktop-portal. + match Session::open().await { + Ok(session) => assert!(session.path().starts_with("/org/freedesktop/portal")), + Err(error) => { + let message = error.to_string(); assert!( - message.contains("portail") || message.contains("D-Bus"), - "message inattendu: {message}" + message.contains("portal") || message.contains("D-Bus"), + "unexpected message: {message}" ); } } diff --git a/crates/rs-platform/src/reseau.rs b/crates/rs-platform/src/reseau.rs deleted file mode 100644 index 019f399..0000000 --- a/crates/rs-platform/src/reseau.rs +++ /dev/null @@ -1,130 +0,0 @@ -//! Interfaces réseau, pour choisir où l'hôte écoute (#33). -//! -//! Le cas qui motive le choix: une machine sur le Wi-Fi invité et sur le LAN -//! filaire à la fois. Écouter partout expose l'écran aux deux; écouter sur une -//! interface ne l'expose qu'à elle. Le choix se fait par **nom** (`enp3s0`), -//! pas par adresse: une adresse DHCP change, le nom reste. - -use std::net::IpAddr; - -use serde::Serialize; - -/// Une interface telle que l'interface de l'hôte la propose. -#[derive(Debug, Clone, PartialEq, Eq, Serialize)] -pub struct InterfaceReseau { - pub nom: String, - /// Adresses IPv4 d'abord: c'est elles qu'un téléphone joint en pratique. - pub adresses: Vec, - /// Lien actif (`operstate` à `up`, ou inconnu mais avec une adresse). - pub active: bool, - /// Boucle locale: jamais joignable par un autre appareil. - pub boucle: bool, -} - -impl InterfaceReseau { - /// L'adresse à annoncer et sur laquelle écouter: la première IPv4, sinon - /// une IPv6 qui ne soit pas de lien local (une `fe80::` demande un - /// identifiant de zone que l'URL ne sait pas porter). - pub fn adresse_principale(&self) -> Option { - self.adresses - .iter() - .copied() - .find(IpAddr::is_ipv4) - .or_else(|| { - self.adresses.iter().copied().find(|ip| match ip { - IpAddr::V6(v6) => !v6.is_unicast_link_local(), - IpAddr::V4(_) => false, - }) - }) - } -} - -/// Les interfaces de la machine, boucle locale comprise (signalée). -pub fn interfaces() -> Vec { - let mut liste: Vec = Vec::new(); - for interface in if_addrs::get_if_addrs().unwrap_or_default() { - let ip = interface.ip(); - match liste.iter_mut().find(|i| i.nom == interface.name) { - Some(existante) => existante.adresses.push(ip), - None => liste.push(InterfaceReseau { - nom: interface.name.clone(), - adresses: vec![ip], - active: false, - boucle: interface.is_loopback(), - }), - } - } - for interface in &mut liste { - interface.adresses.sort_by_key(|ip| !ip.is_ipv4()); - interface.active = actif(etat_lien(&interface.nom).as_deref()); - } - liste.sort_by(|a, b| (a.boucle, &a.nom).cmp(&(b.boucle, &b.nom))); - liste -} - -/// L'interface de ce nom, si elle existe et porte une adresse. -pub fn interface(nom: &str) -> Option { - interfaces().into_iter().find(|i| i.nom == nom) -} - -/// `operstate` du noyau. Absent hors Linux: on ne sait pas, on ne dit pas non. -fn etat_lien(nom: &str) -> Option { - std::fs::read_to_string(format!("/sys/class/net/{nom}/operstate")) - .ok() - .map(|s| s.trim().to_string()) -} - -/// `unknown` est l'état de beaucoup d'interfaces virtuelles (VPN, tun) qui -/// fonctionnent pourtant: seule une interface explicitement `down` (ou -/// `dormant`, `lowerlayerdown`) est tenue pour coupée. -fn actif(etat: Option<&str>) -> bool { - !matches!( - etat, - Some("down" | "dormant" | "lowerlayerdown" | "notpresent") - ) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn interface(adresses: &[&str]) -> InterfaceReseau { - InterfaceReseau { - nom: "test0".into(), - adresses: adresses.iter().map(|a| a.parse().unwrap()).collect(), - active: true, - boucle: false, - } - } - - #[test] - fn ipv4_comes_first_and_link_local_v6_is_never_announced() { - assert_eq!( - interface(&["fe80::1", "192.168.1.20"]).adresse_principale(), - Some("192.168.1.20".parse().unwrap()) - ); - assert_eq!(interface(&["fe80::1"]).adresse_principale(), None); - assert_eq!( - interface(&["fe80::1", "2001:db8::5"]).adresse_principale(), - Some("2001:db8::5".parse().unwrap()) - ); - } - - #[test] - fn only_an_explicitly_down_link_is_inactive() { - assert!(actif(Some("up"))); - assert!(actif(Some("unknown"))); - assert!(actif(None)); - assert!(!actif(Some("down"))); - assert!(!actif(Some("lowerlayerdown"))); - } - - #[test] - fn this_machine_has_a_loopback_listed_last() { - let liste = interfaces(); - let boucle = liste.iter().position(|i| i.boucle); - if let Some(position) = boucle { - assert!(liste[position..].iter().all(|i| i.boucle)); - } - } -} diff --git a/crates/rs-platform/src/sleep.rs b/crates/rs-platform/src/sleep.rs new file mode 100644 index 0000000..ae36d8d --- /dev/null +++ b/crates/rs-platform/src/sleep.rs @@ -0,0 +1,392 @@ +//! Sleep: prevent it during a share, and know when the machine wakes up. +//! +//! A share often lasts longer than the sleep timeout: a presenting host no +//! longer touches the keyboard, and the desktop ends up blanking the screen, +//! then suspending the machine. The viewer then sees a frozen picture with no +//! explanation (issue #41). +//! +//! On Linux, two distinct locks, because neither covers everything: +//! +//! - **`login1`** (`org.freedesktop.login1.Manager.Inhibit`, system bus): +//! blocks automatic suspend and idle sleep as long as the returned +//! descriptor stays open. Closing the lid (`handle-lid-switch`) is +//! deliberately not blocked: it is an explicit user gesture, and the resume +//! is handled afterwards ([`watch_wake`], issue #42). +//! - **`screensaver`** (`org.freedesktop.ScreenSaver.Inhibit`, session bus): +//! keeps the screen from blanking. GNOME honours it through its ScreenSaver +//! shim. The returned cookie is tied to the connection: the daemon forgets +//! it when the connection closes. +//! +//! One can be missing without the other (no logind in a container, no +//! ScreenSaver daemon under a bare window manager): the inhibition succeeds as +//! soon as one of them holds, and [`Inhibition::active`] says which, so the UI +//! does not display a promise it does not keep. + +use std::fmt; + +use futures_util::StreamExt; +use zbus::{Connection, MatchRule, MessageStream}; + +const LOGIN1_BUS: &str = "org.freedesktop.login1"; +const LOGIN1_PATH: &str = "/org/freedesktop/login1"; +const LOGIN1_INTERFACE: &str = "org.freedesktop.login1.Manager"; + +const SCREENSAVER_BUS: &str = "org.freedesktop.ScreenSaver"; +const SCREENSAVER_PATH: &str = "/org/freedesktop/ScreenSaver"; +const SCREENSAVER_INTERFACE: &str = "org.freedesktop.ScreenSaver"; + +/// Name shown by `systemd-inhibit --list` and by the desktop. +const APPLICATION: &str = "rustscreen"; + +/// What the `login1` lock blocks: suspend and idle sleep, not the lid nor the +/// power keys. +const LOGIN1_WHAT: &str = "sleep:idle"; + +/// Name of the `login1` mechanism in [`Inhibition::active`] and the logs. +pub const MECHANISM_LOGIN1: &str = "login1"; +/// Name of the ScreenSaver mechanism in [`Inhibition::active`] and the logs. +pub const MECHANISM_SCREENSAVER: &str = "screensaver"; + +#[derive(Debug, thiserror::Error)] +pub enum SleepError { + /// Neither lock could be taken. + #[error("cannot prevent sleep (login1: {login1}; screensaver: {screensaver})")] + Inhibition { login1: String, screensaver: String }, + #[error("no D-Bus system bus: {0}")] + Bus(String), + #[error("cannot subscribe to PrepareForSleep: {0}")] + Subscription(String), +} + +/// List of the mechanisms held, in a stable order. +fn active_names(login1: bool, screensaver: bool) -> Vec<&'static str> { + let mut names = Vec::with_capacity(2); + if login1 { + names.push(MECHANISM_LOGIN1); + } + if screensaver { + names.push(MECHANISM_SCREENSAVER); + } + names +} + +/// Locks against sleep, held as long as the value lives. +/// +/// [`Inhibition::release`] frees everything immediately. Failing that, `Drop` +/// closes the `login1` descriptor (synchronous close, no D-Bus call) and drops +/// the session connection: the ScreenSaver daemon then forgets the cookie on +/// its own, without an explicit `UnInhibit`, which may take the time the +/// connection needs to close. +pub struct Inhibition { + /// Descriptor returned by `login1`: the lock lasts as long as it is open. + login1_lock: Option, + /// Session connection and ScreenSaver cookie. The connection is kept alive + /// on purpose: closing it releases the cookie. + screensaver: Option<(Connection, u32)>, +} + +impl fmt::Debug for Inhibition { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Inhibition") + .field("active", &self.active()) + .finish() + } +} + +impl Inhibition { + /// Prevents sleep and screen blanking. + /// + /// `reason` is shown by the desktop and `systemd-inhibit --list`: a fixed + /// text from the caller, never a window title. It is not logged. + /// + /// Fails only if neither lock could be taken. + pub async fn acquire(reason: &str) -> Result { + let login1 = inhibit_login1(reason).await; + let screensaver = inhibit_screensaver(reason).await; + + let (login1_lock, screensaver) = match (login1, screensaver) { + (Err(login1), Err(screensaver)) => { + tracing::warn!( + event = "sleep_not_inhibited", + login1 = %login1, + screensaver = %screensaver, + "no lock against sleep" + ); + return Err(SleepError::Inhibition { + login1, + screensaver, + }); + } + (login1, screensaver) => { + if let Err(error) = &login1 { + tracing::warn!(%error, "login1 lock unavailable"); + } + if let Err(error) = &screensaver { + tracing::warn!(%error, "ScreenSaver lock unavailable"); + } + (login1.ok(), screensaver.ok()) + } + }; + + let inhibition = Self { + login1_lock, + screensaver, + }; + tracing::info!( + event = "sleep_inhibited", + mechanisms = ?inhibition.active(), + "sleep prevented during the share" + ); + Ok(inhibition) + } + + /// Mechanisms actually held: [`MECHANISM_LOGIN1`], + /// [`MECHANISM_SCREENSAVER`], or both. + pub fn active(&self) -> Vec<&'static str> { + active_names(self.login1_lock.is_some(), self.screensaver.is_some()) + } + + /// Frees the locks right away: `UnInhibit`, then closing the `login1` + /// descriptor. + pub async fn release(mut self) { + let active = self.active(); + if let Some((connection, cookie)) = self.screensaver.take() { + // A failure here prevents nothing: the connection closes right + // after, and the daemon forgets the cookie with it. + if let Err(error) = connection + .call_method( + Some(SCREENSAVER_BUS), + SCREENSAVER_PATH, + Some(SCREENSAVER_INTERFACE), + "UnInhibit", + &(cookie,), + ) + .await + { + tracing::debug!(%error, "UnInhibit refused, closing will be enough"); + } + } + // Closing the descriptor is enough to hand the lock back to logind. + drop(self.login1_lock.take()); + tracing::info!( + event = "sleep_released", + mechanisms = ?active, + "sleep allowed again" + ); + } +} + +impl Drop for Inhibition { + fn drop(&mut self) { + // Nothing to do if `release` already ran. + let active = self.active(); + if active.is_empty() { + return; + } + // The descriptor closes with the field, the connection too: no D-Bus + // call is possible in a synchronous `Drop`, and none is needed. + tracing::info!( + event = "sleep_released", + mechanisms = ?active, + "sleep allowed again" + ); + } +} + +/// Takes the `login1` lock and returns its descriptor. +async fn inhibit_login1(reason: &str) -> Result { + let connection = Connection::system().await.map_err(|e| e.to_string())?; + let reply = connection + .call_method( + Some(LOGIN1_BUS), + LOGIN1_PATH, + Some(LOGIN1_INTERFACE), + "Inhibit", + &(LOGIN1_WHAT, APPLICATION, reason, "block"), + ) + .await + .map_err(|e| e.to_string())?; + // Deserialization duplicates the descriptor: the copy belongs to us and + // keeps the lock once the message and the connection are gone. + reply + .body() + .deserialize::() + .map_err(|e| format!("unreadable descriptor: {e}")) +} + +/// Takes the ScreenSaver lock and returns the connection that carries it. +async fn inhibit_screensaver(reason: &str) -> Result<(Connection, u32), String> { + let connection = Connection::session().await.map_err(|e| e.to_string())?; + let reply = connection + .call_method( + Some(SCREENSAVER_BUS), + SCREENSAVER_PATH, + Some(SCREENSAVER_INTERFACE), + "Inhibit", + &(APPLICATION, reason), + ) + .await + .map_err(|e| e.to_string())?; + let cookie = reply + .body() + .deserialize::() + .map_err(|e| format!("unreadable cookie: {e}"))?; + Ok((connection, cookie)) +} + +/// Transition announced by `PrepareForSleep`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SleepEvent { + /// The machine is going to sleep (`PrepareForSleep(true)`). + GoingToSleep, + /// The machine just woke up (`PrepareForSleep(false)`): the viewers' + /// connections are probably dead, and so is the capture. + WokeUp, +} + +impl SleepEvent { + fn from_signal(going_to_sleep: bool) -> Self { + if going_to_sleep { + Self::GoingToSleep + } else { + Self::WokeUp + } + } +} + +/// Listens for the sleeps and wake-ups announced by `login1`. +pub struct WakeWatcher { + stream: MessageStream, +} + +impl fmt::Debug for WakeWatcher { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("WakeWatcher").finish_non_exhaustive() + } +} + +/// Subscribes to `PrepareForSleep` on the system bus. +/// +/// Call it before it is needed: a signal emitted before the subscription is +/// lost, and a missed wake-up leaves the share frozen. +pub async fn watch_wake() -> Result { + let connection = Connection::system() + .await + .map_err(|e| SleepError::Bus(e.to_string()))?; + let rule = MatchRule::builder() + .msg_type(zbus::message::Type::Signal) + // No sender filter: the signal arrives under logind's unique name, not + // under `org.freedesktop.login1`. Only root can emit on this path of + // the system bus. + .interface(LOGIN1_INTERFACE) + .member("PrepareForSleep") + .path(LOGIN1_PATH) + .build() + .map_err(|e| SleepError::Subscription(e.to_string()))?; + let stream = MessageStream::for_match_rule(rule, &connection, None) + .await + .map_err(|e| SleepError::Subscription(e.to_string()))?; + Ok(WakeWatcher { stream }) +} + +impl WakeWatcher { + /// Waits for the next transition. `None` when the connection to the + /// system bus is lost: no wake-up will be announced anymore. + pub async fn next_event(&mut self) -> Option { + loop { + let message = match self.stream.next().await? { + Ok(message) => message, + Err(error) => { + tracing::debug!(%error, "unreadable message on the system bus"); + continue; + } + }; + let Ok(going_to_sleep) = message.body().deserialize::() else { + continue; + }; + let event = SleepEvent::from_signal(going_to_sleep); + match event { + SleepEvent::GoingToSleep => { + tracing::info!(event = "going_to_sleep", "the machine is going to sleep"); + } + SleepEvent::WokeUp => { + tracing::info!(event = "woke_up", "the machine is waking up"); + } + } + return Some(event); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn active_mechanisms_are_named_in_a_stable_order() { + assert_eq!(active_names(true, true), ["login1", "screensaver"]); + assert_eq!(active_names(false, true), ["screensaver"]); + assert_eq!(active_names(true, false), ["login1"]); + assert!(active_names(false, false).is_empty()); + } + + #[test] + fn prepare_for_sleep_maps_true_to_sleep_and_false_to_wake() { + assert_eq!(SleepEvent::from_signal(true), SleepEvent::GoingToSleep); + assert_eq!(SleepEvent::from_signal(false), SleepEvent::WokeUp); + } + + #[test] + fn the_lid_switch_is_never_inhibited() { + // Closing the lid is an explicit gesture: blocking it would surprise. + assert!(!LOGIN1_WHAT.contains("handle-lid-switch")); + assert_eq!(LOGIN1_WHAT, "sleep:idle"); + } + + /// Lines of `systemd-inhibit --list` that come from this process. + fn locks_of_this_process() -> Vec { + let output = std::process::Command::new("systemd-inhibit") + .args(["--list", "--no-pager", "--no-legend"]) + .output() + .expect("systemd-inhibit not found"); + let pid = std::process::id().to_string(); + String::from_utf8_lossy(&output.stdout) + .lines() + .filter(|l| { + let fields: Vec<&str> = l.split_whitespace().collect(); + fields.first() == Some(&APPLICATION) && fields.contains(&pid.as_str()) + }) + .map(str::to_string) + .collect() + } + + /// Takes a real lock on this machine: needs logind and a desktop that + /// exposes ScreenSaver. `cargo test -p rs-platform sleep -- --ignored`. + #[tokio::test] + #[ignore = "needs logind and a desktop session"] + async fn a_real_inhibition_shows_in_systemd_inhibit_then_goes_away() { + let inhibition = Inhibition::acquire("screen sharing in progress (test)") + .await + .expect("no lock taken"); + let active = inhibition.active(); + assert!(active.contains(&MECHANISM_LOGIN1), "{active:?}"); + eprintln!("mechanisms held: {active:?}"); + + let lines = locks_of_this_process(); + assert_eq!(lines.len(), 1, "{lines:?}"); + assert!(lines[0].contains("sleep:idle"), "{}", lines[0]); + assert!(lines[0].contains("block"), "{}", lines[0]); + + inhibition.release().await; + let lines = locks_of_this_process(); + assert!(lines.is_empty(), "lock still held: {lines:?}"); + } + + #[tokio::test] + async fn subscribing_to_resume_never_panics() { + // Without a system bus, the error must be readable, never a panic. + if let Err(error) = watch_wake().await { + assert!(!error.to_string().is_empty()); + } + } +} diff --git a/crates/rs-platform/src/veille.rs b/crates/rs-platform/src/veille.rs deleted file mode 100644 index bcd1aae..0000000 --- a/crates/rs-platform/src/veille.rs +++ /dev/null @@ -1,398 +0,0 @@ -//! Veille: l'empêcher pendant un partage, et savoir quand le poste se réveille. -//! -//! Un partage dure souvent plus longtemps que le délai de mise en veille: un -//! hôte qui présente ne touche plus son clavier, et le bureau finit par éteindre -//! l'écran puis suspendre la machine. Le spectateur voit alors une image figée -//! sans explication (issue #41). -//! -//! Sous Linux, deux verrous distincts, parce qu'aucun ne couvre tout: -//! -//! - **`login1`** (`org.freedesktop.login1.Manager.Inhibit`, bus système): -//! bloque la suspension automatique et la veille sur inactivité tant que le -//! descripteur rendu reste ouvert. La fermeture du capot (`handle-lid-switch`) -//! n'est volontairement pas bloquée: c'est un geste explicite de -//! l'utilisateur, et la reprise se traite après coup ([`surveiller_reprise`], -//! issue #42). -//! - **`screensaver`** (`org.freedesktop.ScreenSaver.Inhibit`, bus de session): -//! empêche l'écran de s'éteindre. GNOME l'honore par sa cale ScreenSaver. Le -//! jeton rendu est lié à la connexion: le démon l'oublie quand elle se ferme. -//! -//! L'un peut manquer sans l'autre (pas de logind dans un conteneur, pas de -//! démon ScreenSaver sous un gestionnaire de fenêtres nu): l'inhibition réussit -//! dès qu'un des deux tient, et [`Inhibition::actives`] dit lesquels, pour que -//! l'interface n'affiche pas une promesse qu'elle ne tient pas. - -use std::fmt; - -use futures_util::StreamExt; -use zbus::{Connection, MatchRule, MessageStream}; - -const BUS_LOGIN1: &str = "org.freedesktop.login1"; -const CHEMIN_LOGIN1: &str = "/org/freedesktop/login1"; -const INTERFACE_LOGIN1: &str = "org.freedesktop.login1.Manager"; - -const BUS_ECONOMISEUR: &str = "org.freedesktop.ScreenSaver"; -const CHEMIN_ECONOMISEUR: &str = "/org/freedesktop/ScreenSaver"; -const INTERFACE_ECONOMISEUR: &str = "org.freedesktop.ScreenSaver"; - -/// Nom affiché par `systemd-inhibit --list` et par le bureau. -const APPLICATION: &str = "rustscreen"; - -/// Ce que bloque le verrou `login1`: la suspension et la veille sur -/// inactivité, pas le capot ni les touches d'alimentation. -const QUOI_LOGIN1: &str = "sleep:idle"; - -/// Nom du mécanisme `login1` dans [`Inhibition::actives`] et les journaux. -pub const MECANISME_LOGIN1: &str = "login1"; -/// Nom du mécanisme ScreenSaver dans [`Inhibition::actives`] et les journaux. -pub const MECANISME_ECONOMISEUR: &str = "screensaver"; - -#[derive(Debug, thiserror::Error)] -pub enum VeilleError { - /// Aucun des deux verrous n'a pu être pris. - #[error("impossible d'empêcher la veille (login1: {login1}; screensaver: {economiseur})")] - Inhibition { login1: String, economiseur: String }, - #[error("pas de bus système D-Bus: {0}")] - Bus(String), - #[error("abonnement à PrepareForSleep impossible: {0}")] - Abonnement(String), -} - -/// Liste des mécanismes tenus, dans un ordre stable. -fn noms_actifs(login1: bool, economiseur: bool) -> Vec<&'static str> { - let mut noms = Vec::with_capacity(2); - if login1 { - noms.push(MECANISME_LOGIN1); - } - if economiseur { - noms.push(MECANISME_ECONOMISEUR); - } - noms -} - -/// Verrous contre la veille, tenus tant que la valeur vit. -/// -/// [`Inhibition::relacher`] libère tout immédiatement. À défaut, `Drop` ferme le -/// descripteur `login1` (fermeture synchrone, sans appel D-Bus) et laisse -/// tomber la connexion de session: le démon ScreenSaver oublie alors le jeton -/// de lui-même, sans `UnInhibit` explicite, ce qui peut prendre l'instant de la -/// fermeture de la connexion. -pub struct Inhibition { - /// Descripteur rendu par `login1`: le verrou dure tant qu'il est ouvert. - verrou_login1: Option, - /// Connexion de session et jeton ScreenSaver. La connexion est gardée - /// vivante exprès: la fermer relâche le jeton. - economiseur: Option<(Connection, u32)>, -} - -impl fmt::Debug for Inhibition { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Inhibition") - .field("actives", &self.actives()) - .finish() - } -} - -impl Inhibition { - /// Empêche la mise en veille et l'extinction de l'écran. - /// - /// `raison` est montrée par le bureau et `systemd-inhibit --list`: un texte - /// fixe de l'appelant, jamais un titre de fenêtre. Elle n'est pas journalisée. - /// - /// Échoue seulement si aucun des deux verrous n'a pu être pris. - pub async fn prendre(raison: &str) -> Result { - let login1 = inhiber_login1(raison).await; - let economiseur = inhiber_economiseur(raison).await; - - let (verrou_login1, economiseur) = match (login1, economiseur) { - (Err(login1), Err(economiseur)) => { - tracing::warn!( - evenement = "veille_non_inhibee", - login1 = %login1, - screensaver = %economiseur, - "aucun verrou contre la veille" - ); - return Err(VeilleError::Inhibition { - login1, - economiseur, - }); - } - (login1, economiseur) => { - if let Err(erreur) = &login1 { - tracing::warn!(%erreur, "verrou login1 indisponible"); - } - if let Err(erreur) = &economiseur { - tracing::warn!(%erreur, "verrou ScreenSaver indisponible"); - } - (login1.ok(), economiseur.ok()) - } - }; - - let inhibition = Self { - verrou_login1, - economiseur, - }; - tracing::info!( - evenement = "veille_inhibee", - mecanismes = ?inhibition.actives(), - "veille empêchée pendant le partage" - ); - Ok(inhibition) - } - - /// Mécanismes effectivement tenus: [`MECANISME_LOGIN1`], - /// [`MECANISME_ECONOMISEUR`], ou les deux. - pub fn actives(&self) -> Vec<&'static str> { - noms_actifs(self.verrou_login1.is_some(), self.economiseur.is_some()) - } - - /// Libère les verrous tout de suite: `UnInhibit` puis fermeture du - /// descripteur `login1`. - pub async fn relacher(mut self) { - let actives = self.actives(); - if let Some((connexion, jeton)) = self.economiseur.take() { - // Un échec ici n'empêche rien: la connexion se ferme juste après, - // et le démon oublie le jeton avec elle. - if let Err(erreur) = connexion - .call_method( - Some(BUS_ECONOMISEUR), - CHEMIN_ECONOMISEUR, - Some(INTERFACE_ECONOMISEUR), - "UnInhibit", - &(jeton,), - ) - .await - { - tracing::debug!(%erreur, "UnInhibit refusé, la fermeture suffira"); - } - } - // Fermer le descripteur suffit à rendre le verrou à logind. - drop(self.verrou_login1.take()); - tracing::info!( - evenement = "veille_relachee", - mecanismes = ?actives, - "veille de nouveau permise" - ); - } -} - -impl Drop for Inhibition { - fn drop(&mut self) { - // Rien à faire si `relacher` est déjà passé. - let actives = self.actives(); - if actives.is_empty() { - return; - } - // Le descripteur se ferme avec le champ, la connexion aussi: pas d'appel - // D-Bus possible dans un `Drop` synchrone, et il n'en faut pas. - tracing::info!( - evenement = "veille_relachee", - mecanismes = ?actives, - "veille de nouveau permise" - ); - } -} - -/// Prend le verrou `login1` et rend son descripteur. -async fn inhiber_login1(raison: &str) -> Result { - let connexion = Connection::system().await.map_err(|e| e.to_string())?; - let reponse = connexion - .call_method( - Some(BUS_LOGIN1), - CHEMIN_LOGIN1, - Some(INTERFACE_LOGIN1), - "Inhibit", - &(QUOI_LOGIN1, APPLICATION, raison, "block"), - ) - .await - .map_err(|e| e.to_string())?; - // La désérialisation duplique le descripteur: la copie nous appartient et - // garde le verrou une fois le message et la connexion disparus. - reponse - .body() - .deserialize::() - .map_err(|e| format!("descripteur illisible: {e}")) -} - -/// Prend le verrou ScreenSaver et rend la connexion qui le porte. -async fn inhiber_economiseur(raison: &str) -> Result<(Connection, u32), String> { - let connexion = Connection::session().await.map_err(|e| e.to_string())?; - let reponse = connexion - .call_method( - Some(BUS_ECONOMISEUR), - CHEMIN_ECONOMISEUR, - Some(INTERFACE_ECONOMISEUR), - "Inhibit", - &(APPLICATION, raison), - ) - .await - .map_err(|e| e.to_string())?; - let jeton = reponse - .body() - .deserialize::() - .map_err(|e| format!("jeton illisible: {e}"))?; - Ok((connexion, jeton)) -} - -/// Transition annoncée par `PrepareForSleep`. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum EvenementVeille { - /// La machine s'endort (`PrepareForSleep(true)`). - Endormissement, - /// La machine vient de se réveiller (`PrepareForSleep(false)`): les - /// connexions des spectateurs sont probablement mortes, la capture aussi. - Reveil, -} - -impl EvenementVeille { - fn depuis_signal(endormissement: bool) -> Self { - if endormissement { - Self::Endormissement - } else { - Self::Reveil - } - } -} - -/// Écoute des mises en veille et des réveils annoncés par `login1`. -pub struct Reprise { - flux: MessageStream, -} - -impl fmt::Debug for Reprise { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Reprise").finish_non_exhaustive() - } -} - -/// S'abonne à `PrepareForSleep` sur le bus système. -/// -/// À appeler avant d'en avoir besoin: un signal émis avant l'abonnement est -/// perdu, et un réveil manqué laisse le partage figé. -pub async fn surveiller_reprise() -> Result { - let connexion = Connection::system() - .await - .map_err(|e| VeilleError::Bus(e.to_string()))?; - let regle = MatchRule::builder() - .msg_type(zbus::message::Type::Signal) - // Pas de filtre sur l'expéditeur: le signal arrive sous le nom unique - // de logind, pas sous `org.freedesktop.login1`. Seul root peut émettre - // sur ce chemin du bus système. - .interface(INTERFACE_LOGIN1) - .member("PrepareForSleep") - .path(CHEMIN_LOGIN1) - .build() - .map_err(|e| VeilleError::Abonnement(e.to_string()))?; - let flux = MessageStream::for_match_rule(regle, &connexion, None) - .await - .map_err(|e| VeilleError::Abonnement(e.to_string()))?; - Ok(Reprise { flux }) -} - -impl Reprise { - /// Attend la prochaine transition. `None` quand la connexion au bus - /// système est perdue: plus aucun réveil ne sera annoncé. - pub async fn suivante(&mut self) -> Option { - loop { - let message = match self.flux.next().await? { - Ok(message) => message, - Err(erreur) => { - tracing::debug!(%erreur, "message illisible sur le bus système"); - continue; - } - }; - let Ok(endormissement) = message.body().deserialize::() else { - continue; - }; - let evenement = EvenementVeille::depuis_signal(endormissement); - match evenement { - EvenementVeille::Endormissement => { - tracing::info!(evenement = "mise_en_veille", "la machine s'endort"); - } - EvenementVeille::Reveil => { - tracing::info!(evenement = "reveil", "la machine se réveille"); - } - } - return Some(evenement); - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn active_mechanisms_are_named_in_a_stable_order() { - assert_eq!(noms_actifs(true, true), ["login1", "screensaver"]); - assert_eq!(noms_actifs(false, true), ["screensaver"]); - assert_eq!(noms_actifs(true, false), ["login1"]); - assert!(noms_actifs(false, false).is_empty()); - } - - #[test] - fn prepare_for_sleep_maps_true_to_sleep_and_false_to_wake() { - assert_eq!( - EvenementVeille::depuis_signal(true), - EvenementVeille::Endormissement - ); - assert_eq!( - EvenementVeille::depuis_signal(false), - EvenementVeille::Reveil - ); - } - - #[test] - fn the_lid_switch_is_never_inhibited() { - // Fermer le capot est un geste explicite: le bloquer surprendrait. - assert!(!QUOI_LOGIN1.contains("handle-lid-switch")); - assert_eq!(QUOI_LOGIN1, "sleep:idle"); - } - - /// Lignes de `systemd-inhibit --list` qui viennent de ce processus. - fn verrous_du_processus() -> Vec { - let sortie = std::process::Command::new("systemd-inhibit") - .args(["--list", "--no-pager", "--no-legend"]) - .output() - .expect("systemd-inhibit introuvable"); - let pid = std::process::id().to_string(); - String::from_utf8_lossy(&sortie.stdout) - .lines() - .filter(|l| { - let champs: Vec<&str> = l.split_whitespace().collect(); - champs.first() == Some(&APPLICATION) && champs.contains(&pid.as_str()) - }) - .map(str::to_string) - .collect() - } - - /// Prend un vrai verrou sur cette machine: demande logind et un bureau qui - /// expose ScreenSaver. `cargo test -p rs-platform veille -- --ignored`. - #[tokio::test] - #[ignore = "demande logind et une session de bureau"] - async fn a_real_inhibition_shows_in_systemd_inhibit_then_goes_away() { - let inhibition = Inhibition::prendre("partage d'écran en cours (test)") - .await - .expect("aucun verrou pris"); - let actives = inhibition.actives(); - assert!(actives.contains(&MECANISME_LOGIN1), "{actives:?}"); - eprintln!("mécanismes tenus: {actives:?}"); - - let lignes = verrous_du_processus(); - assert_eq!(lignes.len(), 1, "{lignes:?}"); - assert!(lignes[0].contains("sleep:idle"), "{}", lignes[0]); - assert!(lignes[0].contains("block"), "{}", lignes[0]); - - inhibition.relacher().await; - let lignes = verrous_du_processus(); - assert!(lignes.is_empty(), "verrou encore tenu: {lignes:?}"); - } - - #[tokio::test] - async fn subscribing_to_resume_never_panics() { - // Sans bus système, l'erreur doit être lisible, jamais une panique. - if let Err(erreur) = surveiller_reprise().await { - assert!(!erreur.to_string().is_empty()); - } - } -} diff --git a/crates/rs-proto/Cargo.toml b/crates/rs-proto/Cargo.toml index b85a4b5..ef650c2 100644 --- a/crates/rs-proto/Cargo.toml +++ b/crates/rs-proto/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rs-proto" -description = "Types partagés: messages de signalement, modèle de session, versions du protocole." +description = "Shared types: signaling messages, session model, protocol versions." version.workspace = true edition.workspace = true rust-version.workspace = true diff --git a/crates/rs-proto/src/appairage.rs b/crates/rs-proto/src/appairage.rs deleted file mode 100644 index 7bb2c48..0000000 --- a/crates/rs-proto/src/appairage.rs +++ /dev/null @@ -1,70 +0,0 @@ -//! Appairage: ce qu'échange le viewer avec l'hôte avant d'avoir un jeton. -//! -//! Deux chemins mènent à une session (#19). Le QR code porte l'URL complète, -//! jeton compris: le scanner suffit. Sans caméra, l'hôte affiche un code court -//! de six caractères, que le spectateur tape sur la page d'accueil du viewer; -//! le serveur l'échange contre la room et le jeton. - -use serde::{Deserialize, Serialize}; -use ts_rs::TS; - -use crate::session::{RoomId, SessionToken}; - -/// Version du format du lien porté par le QR code (paramètre `v`). -/// -/// Le lien est `/r/?t=&v=`, suivi en HTTPS de -/// `#fp=`, l'empreinte SHA-256 du certificat en hexadécimal. Un -/// viewer qui reçoit une version plus récente que la sienne le dit au lieu de -/// mal lire le lien. -pub const LINK_VERSION: u16 = 1; - -/// Le code court tapé par le spectateur. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] -#[ts(export)] -pub struct PairingRequest { - pub code: String, -} - -/// La réponse de l'hôte à un code court. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] -#[serde(tag = "status", rename_all = "snake_case")] -#[ts(export)] -pub enum PairingResponse { - /// Le code est bon: le viewer ouvre `/r/?t=`. - Accepted { room: RoomId, token: SessionToken }, - /// Aucun code de ce nom, ou plus maintenant que l'hôte en a tiré un autre. - Unknown, - /// Le code a existé, mais sa durée de validité est passée. - Expired, - /// Trop d'essais faux depuis cet appareil ou au total: le code est - /// protégé contre qui les essaierait tous. - TooManyAttempts { retry_after_s: u32 }, -} - -/// Normalise un code tapé à la main: minuscules, sans espace ni tiret. Le -/// code s'affiche en majuscules groupées par trois (`K7M 4PQ`). -pub fn normalize_code(saisie: &str) -> String { - saisie - .chars() - .filter(|c| !c.is_whitespace() && *c != '-') - .flat_map(char::to_lowercase) - .collect() -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_typed_code_is_normalized() { - assert_eq!(normalize_code(" K7M-4pq "), "k7m4pq"); - assert_eq!(normalize_code("K7M 4PQ"), "k7m4pq"); - } - - #[test] - fn the_response_is_tagged_for_the_viewer() { - let json = - serde_json::to_string(&PairingResponse::TooManyAttempts { retry_after_s: 30 }).unwrap(); - assert_eq!(json, r#"{"status":"too_many_attempts","retry_after_s":30}"#); - } -} diff --git a/crates/rs-proto/src/lib.rs b/crates/rs-proto/src/lib.rs index d352785..defd32e 100644 --- a/crates/rs-proto/src/lib.rs +++ b/crates/rs-proto/src/lib.rs @@ -1,25 +1,25 @@ -//! Protocole partagé entre l'hôte Rust et le client TypeScript. +//! Protocol shared between the Rust host and the TypeScript client. //! -//! Source unique de vérité: les types TypeScript sont générés depuis ce crate -//! (`cargo test -p rs-proto export_bindings`), jamais écrits à la main deux fois. +//! Single source of truth: the TypeScript types are generated from this crate +//! (`cargo test -p rs-proto export_bindings`), never written twice by hand. -pub mod appairage; pub mod messages; +pub mod pairing; pub mod session; -pub use appairage::{LINK_VERSION, PairingRequest, PairingResponse, normalize_code}; pub use messages::{ClientMessage, ErrorCode, ServerMessage}; +pub use pairing::{LINK_VERSION, PairingRequest, PairingResponse, normalize_code}; pub use session::{ DeviceId, DeviceInfo, QualityPreset, RoomId, SessionToken, SourceId, SourceInfo, SourceKind, StreamSettings, }; -/// Version du protocole, négociée au `hello`. +/// Protocol version, negotiated in `hello`. /// -/// Une rupture de compatibilité incrémente cette valeur: l'hôte et le viewer -/// refusent une session dont les versions diffèrent, avec un message explicite -/// plutôt qu'une négociation qui échoue silencieusement. +/// A compatibility break increments this value: the host and the viewer +/// refuse a session whose versions differ, with an explicit message rather +/// than a negotiation that fails silently. pub const PROTOCOL_VERSION: u16 = 1; -/// Nom de service annoncé en mDNS, et préfixe des identifiants de room. +/// Service name announced over mDNS, and prefix of room identifiers. pub const SERVICE_NAME: &str = "rustscreen"; diff --git a/crates/rs-proto/src/messages.rs b/crates/rs-proto/src/messages.rs index fea5644..4fd45bb 100644 --- a/crates/rs-proto/src/messages.rs +++ b/crates/rs-proto/src/messages.rs @@ -1,8 +1,8 @@ -//! Messages échangés sur le canal de signalement. +//! Messages exchanged on the signaling channel. //! -//! Encodage: JSON, une trame par message WebSocket. Le champ `type` discrimine, -//! ce qui permet d'ignorer proprement un message d'une version plus récente au -//! lieu de fermer la connexion. +//! Encoding: JSON, one frame per WebSocket message. The `type` field is the +//! discriminant, which lets a message from a newer version be ignored cleanly +//! instead of closing the connection. use serde::{Deserialize, Serialize}; use ts_rs::TS; @@ -15,65 +15,65 @@ use crate::session::{DeviceInfo, RoomId, SessionToken, SourceInfo, StreamSetting pub enum ErrorCode { BadVersion, BadToken, - /// Le jeton a été bon, mais sa durée de validité est passée ou l'hôte en a - /// tiré un nouveau: distinct de `BadToken` pour que le spectateur sache - /// qu'il lui faut un QR code récent, pas qu'il s'est trompé (#19). + /// The token was valid, but its validity period is over or the host drew + /// a new one: distinct from `BadToken` so the viewer knows it needs a + /// fresh QR code, not that it made a mistake (#19). TokenExpired, RoomFull, SourceUnavailable, ProtocolViolation, Internal, - /// L'hôte a déconnecté cet appareil: revenir avec le même jeton est refusé. + /// The host disconnected this device: coming back with the same token is refused. Kicked, - /// L'hôte a arrêté le partage: la room n'existe plus. + /// The host stopped sharing: the room no longer exists. ShareEnded, } -/// Ce que le spectateur envoie à l'hôte. +/// What the viewer sends to the host. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)] #[serde(tag = "type", rename_all = "snake_case")] #[ts(export)] pub enum ClientMessage { - /// Premier message: la version décide de la suite, le jeton autorise. + /// First message: the version decides what follows, the token authorizes. Hello { version: u16, room: RoomId, token: SessionToken, device: DeviceInfo, }, - /// Offre SDP du spectateur: une piste vidéo en réception seule. + /// The viewer's SDP offer: one receive-only video track. /// - /// C'est le navigateur qui offre, l'hôte répond. Ce choix vient du spike: - /// le mode passif est le chemin le plus simple et le plus stable. + /// The browser offers, the host answers. This choice comes from the spike: + /// passive mode is the simplest and most stable path. Offer { sdp: String }, - /// Candidat ICE tricklé, quand le viewer le supporte. + /// Trickled ICE candidate, when the viewer supports it. IceCandidate { candidate: String, sdp_mid: Option, sdp_mline_index: Option, }, - /// Demande de changement de profil de qualité. + /// Request to change the quality preset. QualityRequest { settings: StreamSettings }, - /// Départ volontaire, pour libérer la place sans attendre le timeout. + /// Voluntary leave, to free the slot without waiting for the timeout. Bye, } -/// Ce que l'hôte envoie au spectateur. +/// What the host sends to the viewer. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)] #[serde(tag = "type", rename_all = "snake_case")] #[ts(export)] pub enum ServerMessage { - /// Session acceptée: identifiants, source partagée, réglages courants. + /// Session accepted: identifiers, shared source, current settings. Welcome { version: u16, room: RoomId, source: Option, settings: StreamSettings, - /// Nombre de spectateurs déjà connectés, limite incluse. + /// Number of viewers already connected, and the limit. connected: u8, limit: u8, }, - /// Réponse de l'hôte à l'offre du spectateur. + /// The host's answer to the viewer's offer. Answer { sdp: String, }, @@ -82,11 +82,11 @@ pub enum ServerMessage { sdp_mid: Option, sdp_mline_index: Option, }, - /// La source partagée a changé sans coupure de session. + /// The shared source changed without interrupting the session. SourceChanged { source: SourceInfo, }, - /// Réglages appliqués par l'hôte, pour que le viewer affiche l'état réel. + /// Settings applied by the host, so the viewer shows the actual state. SettingsApplied { settings: StreamSettings, }, @@ -107,7 +107,7 @@ mod tests { fn device() -> DeviceInfo { DeviceInfo { id: DeviceId("dev-1".into()), - name: "iPad salon".into(), + name: "Living room iPad".into(), user_agent: Some("Mozilla/5.0".into()), platform: Some("iOS".into()), } diff --git a/crates/rs-proto/src/pairing.rs b/crates/rs-proto/src/pairing.rs new file mode 100644 index 0000000..a5ca673 --- /dev/null +++ b/crates/rs-proto/src/pairing.rs @@ -0,0 +1,70 @@ +//! Pairing: what the viewer exchanges with the host before it has a token. +//! +//! Two paths lead to a session (#19). The QR code carries the full URL, +//! token included: scanning it is enough. Without a camera, the host shows a +//! six-character short code that the viewer types on the viewer's home page; +//! the server exchanges it for the room and the token. + +use serde::{Deserialize, Serialize}; +use ts_rs::TS; + +use crate::session::{RoomId, SessionToken}; + +/// Format version of the link carried by the QR code (`v` parameter). +/// +/// The link is `/r/?t=&v=`, followed over HTTPS by +/// `#fp=`, the SHA-256 fingerprint of the certificate in hex. A +/// viewer that receives a newer version than its own says so instead of +/// misreading the link. +pub const LINK_VERSION: u16 = 1; + +/// The short code typed by the viewer. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] +#[ts(export)] +pub struct PairingRequest { + pub code: String, +} + +/// The host's answer to a short code. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] +#[serde(tag = "status", rename_all = "snake_case")] +#[ts(export)] +pub enum PairingResponse { + /// The code is right: the viewer opens `/r/?t=`. + Accepted { room: RoomId, token: SessionToken }, + /// No such code, or no longer since the host drew another one. + Unknown, + /// The code existed, but its validity period is over. + Expired, + /// Too many wrong attempts from this device or overall: the code is + /// protected against someone trying them all. + TooManyAttempts { retry_after_s: u32 }, +} + +/// Normalizes a hand-typed code: lowercase, without spaces or dashes. The +/// code is displayed in uppercase, grouped by three (`K7M 4PQ`). +pub fn normalize_code(input: &str) -> String { + input + .chars() + .filter(|c| !c.is_whitespace() && *c != '-') + .flat_map(char::to_lowercase) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_typed_code_is_normalized() { + assert_eq!(normalize_code(" K7M-4pq "), "k7m4pq"); + assert_eq!(normalize_code("K7M 4PQ"), "k7m4pq"); + } + + #[test] + fn the_response_is_tagged_for_the_viewer() { + let json = + serde_json::to_string(&PairingResponse::TooManyAttempts { retry_after_s: 30 }).unwrap(); + assert_eq!(json, r#"{"status":"too_many_attempts","retry_after_s":30}"#); + } +} diff --git a/crates/rs-proto/src/session.rs b/crates/rs-proto/src/session.rs index f34e2ff..245142d 100644 --- a/crates/rs-proto/src/session.rs +++ b/crates/rs-proto/src/session.rs @@ -1,10 +1,10 @@ -//! Modèle de session: identifiants, sources partageables, appareils, réglages. +//! Session model: identifiers, shareable sources, devices, settings. use serde::{Deserialize, Serialize}; use ts_rs::TS; -/// Identifiant de room, choisi pour être dictable: six caractères, sans -/// caractères ambigus (pas de `0`, `o`, `1`, `l`, `i`). +/// Room identifier, chosen to be easy to dictate: six characters, without +/// ambiguous characters (no `0`, `o`, `1`, `l`, `i`). #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, TS)] #[ts(export, type = "string")] pub struct RoomId(String); @@ -13,8 +13,8 @@ impl RoomId { pub const LEN: usize = 6; const ALPHABET: &'static [u8] = b"23456789abcdefghjkmnpqrstuvwxyz"; - /// Construit une room à partir d'octets aléatoires. Le refus d'une chaîne - /// invalide est explicite: une room mal formée n'atteint jamais le réseau. + /// Builds a room from random bytes. Rejecting an invalid string is + /// explicit: a malformed room never reaches the network. pub fn from_bytes(bytes: &[u8]) -> Result { if bytes.len() < Self::LEN { return Err(RoomIdError::TooShort); @@ -52,15 +52,15 @@ impl std::fmt::Display for RoomId { #[derive(Debug, thiserror::Error, PartialEq, Eq)] pub enum RoomIdError { - #[error("identifiant trop court")] + #[error("identifier too short")] TooShort, - #[error("longueur attendue {expected}, reçue {0}", expected = RoomId::LEN)] + #[error("expected length {expected}, got {0}", expected = RoomId::LEN)] BadLength(usize), - #[error("caractère interdit dans l'identifiant")] + #[error("forbidden character in identifier")] BadCharacter, } -/// Jeton d'accès à une session. Opaque pour le client, 128 bits d'entropie. +/// Access token to a session. Opaque to the client, 128 bits of entropy. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] #[ts(export, type = "string")] pub struct SessionToken(String); @@ -70,8 +70,8 @@ impl SessionToken { Self(hex.into()) } - /// Comparaison à temps constant: un jeton ne doit pas fuiter par le temps - /// de réponse. + /// Constant-time comparison: a token must not leak through the response + /// time. pub fn matches(&self, candidate: &str) -> bool { if candidate.len() != self.0.len() { return false; @@ -88,8 +88,8 @@ impl SessionToken { } } -/// Ce que l'hôte partage. La distinction n'est pas cosmétique: sous Wayland le -/// portail ne sait pas toujours rendre une fenêtre précise. +/// What the host shares. The distinction is not cosmetic: under Wayland the +/// portal cannot always deliver one specific window. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)] #[serde(rename_all = "snake_case")] #[ts(export)] @@ -110,7 +110,7 @@ pub struct SourceInfo { pub name: String, pub width: u32, pub height: u32, - /// Vrai si la plateforme sait capturer cette source en continu. + /// True if the platform can capture this source continuously. pub available: bool, } @@ -122,13 +122,13 @@ pub struct DeviceId(pub String); #[ts(export)] pub struct DeviceInfo { pub 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. pub name: String, pub user_agent: Option, pub platform: Option, } -/// Profil de qualité, repris du vocabulaire de Deskreen. +/// Quality preset, borrowed from Deskreen's vocabulary. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)] #[serde(rename_all = "snake_case")] #[ts(export)] diff --git a/crates/rs-rtc/Cargo.toml b/crates/rs-rtc/Cargo.toml index ff31105..104f18c 100644 --- a/crates/rs-rtc/Cargo.toml +++ b/crates/rs-rtc/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rs-rtc" -description = "Session WebRTC str0m: ICE, DTLS, SRTP, RTP, statistiques." +description = "str0m WebRTC session: ICE, DTLS, SRTP, RTP, statistics." version.workspace = true edition.workspace = true rust-version.workspace = true diff --git a/crates/rs-rtc/src/driver.rs b/crates/rs-rtc/src/driver.rs index fdf27d0..41e2461 100644 --- a/crates/rs-rtc/src/driver.rs +++ b/crates/rs-rtc/src/driver.rs @@ -1,9 +1,8 @@ -//! Pilote asynchrone: possède le socket UDP et la cadence, la session reste -//! sans I/O. +//! Async driver: owns the UDP socket and the frame pacing, the session stays +//! I/O-free. //! -//! C'est le seul endroit où l'invariant de str0m est orchestré: une commande -//! (ou un datagramme, ou un tick), puis drainage complet jusqu'au prochain -//! timeout. +//! This is the only place where the str0m invariant is orchestrated: one +//! command (or datagram, or tick), then a full drain until the next timeout. use std::net::SocketAddr; use std::sync::Arc; @@ -15,21 +14,21 @@ use tokio::sync::{mpsc, oneshot}; use crate::session::{Poll, Session, SessionError, SessionEvent}; -/// Ce que l'application demande à une session en cours. +/// What the application asks of a running session. pub enum Command { - /// Accepter une offre SDP; la réponse arrive par le canal fourni. + /// Accept an SDP offer; the answer comes back on the given channel. AcceptOffer { sdp: String, reply: oneshot::Sender>, }, - /// Terminer proprement. + /// Shut down cleanly. Stop, } -/// Fait tourner une session jusqu'à `Stop`, une déconnexion, ou une erreur. +/// Runs a session until `Stop`, a disconnection, or an error. /// -/// Les événements sont poussés sur `events`; si le récepteur est fermé, la -/// session continue (l'état reste consultable par les statistiques). +/// Events are pushed on `events`; if the receiver is closed, the session keeps +/// going (its state remains readable through statistics). pub async fn run( mut session: Session, socket: Arc, @@ -42,13 +41,13 @@ pub async fn run( let mut ticker = tokio::time::interval(Duration::from_micros(1_000_000 / fps)); ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); let destination = session.candidate(); - // Adresse du pair vue sur le dernier datagramme: c'est elle que retient - // ICE, et elle vaut mieux qu'un candidat mDNS illisible (AGENTS.md). - let mut pair: Option = None; - let mut premiere_image = true; + // Peer address seen on the last datagram: this is the one ICE keeps, and + // it beats an unresolvable mDNS candidate (AGENTS.md). + let mut peer: Option = None; + let mut first_frame = true; loop { - // Drainage complet. Aucune mutation avant d'avoir atteint le Timeout. + // Full drain. No mutation before reaching the Timeout. let deadline = loop { match session.poll()? { Poll::Transmit { @@ -56,17 +55,17 @@ pub async fn run( destination, } => { if let Err(e) = socket.send_to(&contents, destination).await { - tracing::warn!(%e, "envoi UDP impossible"); + tracing::warn!(%e, "UDP send failed"); } } Poll::Event(event) => { - tracing::debug!(?event, "événement de session"); + tracing::debug!(?event, "session event"); if matches!(event, SessionEvent::Connected) { tracing::info!( - evenement = "candidat_ice_retenu", + event = "ice_candidate_selected", local = %destination, - distant = ?pair, - "ICE et DTLS établis" + remote = ?peer, + "ICE and DTLS established" ); } if matches!(event, SessionEvent::Disconnected) { @@ -87,18 +86,18 @@ pub async fn run( Some(Command::AcceptOffer { sdp, reply }) => { let result = match session.accept_offer(&sdp) { Ok(answer) => { - tracing::info!("offre acceptée"); + tracing::info!("offer accepted"); Ok(answer) } Err(e) => { - tracing::warn!(%e, "offre refusée"); + tracing::warn!(%e, "offer rejected"); Err(e.to_string()) } }; let _ = reply.send(result); } Some(Command::Stop) | None => { - tracing::info!(frames = session.frames_sent(), "session arrêtée"); + tracing::info!(frames = session.frames_sent(), "session stopped"); return Ok(()); } } @@ -107,17 +106,17 @@ pub async fn run( received = socket.recv_from(&mut buf) => { match received { Ok((n, source_addr)) => { - pair = Some(source_addr); + peer = Some(source_addr); if let Err(e) = session.receive( Instant::now(), source_addr, destination, &buf[..n], ) { - tracing::warn!(%e, "datagramme rejeté"); + tracing::warn!(%e, "datagram rejected"); } } - Err(e) => tracing::warn!(%e, "réception UDP en échec"), + Err(e) => tracing::warn!(%e, "UDP receive failed"), } } @@ -126,13 +125,13 @@ pub async fn run( let frame = source.next_frame(); if !frame.is_empty() { match session.write_frame(&frame, Instant::now()) { - Ok(()) if premiere_image => { - premiere_image = false; + Ok(()) if first_frame => { + first_frame = false; tracing::info!( - evenement = "premiere_image", - delai_ms = session.uptime().as_millis() as u64, - octets = frame.len(), - "première image envoyée" + event = "first_frame_sent", + delay_ms = session.uptime().as_millis() as u64, + bytes = frame.len(), + "first frame sent" ); } Ok(()) => {} @@ -150,21 +149,21 @@ pub async fn run( } } -/// Adresse LAN joignable par un navigateur sur cette machine. +/// LAN address of this machine that a browser can reach. /// -/// Un candidat `127.0.0.1` est ignoré par Chrome: on prend l'adresse de -/// l'interface qui porte la route par défaut. +/// Chrome ignores a `127.0.0.1` candidate: take the address of the interface +/// carrying the default route. pub fn local_candidate_address() -> Option { let socket = std::net::UdpSocket::bind("0.0.0.0:0").ok()?; socket.connect("192.0.2.1:9").ok()?; Some(socket.local_addr().ok()?.ip()) } -/// Ouvre le socket média et rend l'adresse annoncée. +/// Opens the media socket and returns the advertised address. /// -/// `ip`: l'adresse de l'interface choisie par l'hôte (#33). Le socket n'écoute -/// alors que sur elle, et c'est elle qu'annonce le candidat. Sans choix, le -/// socket écoute partout et annonce l'interface de la route par défaut. +/// `ip`: the address of the interface chosen by the host (#33). The socket then +/// listens on it only, and the candidate advertises it. Without a choice, the +/// socket listens everywhere and advertises the default route's interface. pub async fn bind_media_socket( port: u16, ip: Option, @@ -177,8 +176,8 @@ pub async fn bind_media_socket( ), }; let socket = UdpSocket::bind((bind, port)).await?; - // Avec le port 0, c'est l'OS qui choisit: l'adresse annoncée doit porter le - // port réellement ouvert, pas celui demandé. + // With port 0 the OS picks: the advertised address must carry the port + // actually opened, not the one requested. let bound_port = socket.local_addr()?.port(); Ok((Arc::new(socket), SocketAddr::new(ip, bound_port))) } diff --git a/crates/rs-rtc/src/lib.rs b/crates/rs-rtc/src/lib.rs index 5318800..6b22c9d 100644 --- a/crates/rs-rtc/src/lib.rs +++ b/crates/rs-rtc/src/lib.rs @@ -1,14 +1,14 @@ -//! Session WebRTC str0m: ICE, DTLS, SRTP, RTP et statistiques. +//! str0m WebRTC session: ICE, DTLS, SRTP, RTP and statistics. //! -//! Deux couches, volontairement séparées: +//! Two layers, deliberately kept apart: //! -//! - [`Session`] est sans I/O. Elle prend le temps et les datagrammes, rend des -//! paquets à envoyer et des événements. C'est elle qu'on teste. -//! - [`driver::run`] possède le socket, la cadence et le cycle de vie. C'est le -//! seul endroit qui orchestre l'invariant de str0m. +//! - [`Session`] is I/O-free. It takes time and datagrams, returns packets to +//! send and events. This is the part under test. +//! - [`driver::run`] owns the socket, the pacing and the lifecycle. It is the +//! only place that orchestrates the str0m invariant. //! -//! Une session par spectateur: cinq spectateurs, cinq sessions, une seule -//! source de frames partagée (voir `rs-codec`). +//! One session per viewer: five viewers, five sessions, a single shared frame +//! source (see `rs-codec`). pub mod driver; pub mod session; diff --git a/crates/rs-rtc/src/session.rs b/crates/rs-rtc/src/session.rs index 220ded5..5be3404 100644 --- a/crates/rs-rtc/src/session.rs +++ b/crates/rs-rtc/src/session.rs @@ -1,10 +1,10 @@ -//! Session média sans I/O, au-dessus de str0m. +//! I/O-free media session on top of str0m. //! -//! Le contrat de str0m est strict: **une mutation, puis drainage complet de -//! `poll_output` jusqu'à `Output::Timeout`**. Cette couche ne fait pas d'I/O -//! (pas de socket, pas d'horloge implicite): l'appelant fournit le temps et les -//! datagrammes, ce qui la rend testable et réutilisable telle quelle côté -//! serveur local comme dans un futur client natif. +//! The str0m contract is strict: **one mutation, then drain `poll_output` +//! completely until `Output::Timeout`**. This layer does no I/O (no socket, no +//! implicit clock): the caller supplies time and datagrams, which makes it +//! testable and reusable as is, in the local server as in a future native +//! client. use std::net::SocketAddr; use std::time::Instant; @@ -14,41 +14,41 @@ use str0m::format::{Codec, PayloadParams, Vp9PacketizerMode}; use str0m::media::{MediaTime, Mid, Pt}; use str0m::{Candidate, Event, IceConnectionState, Input, Output, Rtc, RtcError}; -/// Base de temps RTP de tous les codecs vidéo: 90 kHz. +/// RTP time base of every video codec: 90 kHz. pub const VIDEO_CLOCK: u64 = 90_000; -/// Ce que la session demande à son environnement. +/// What the session asks of its environment. #[derive(Debug)] pub enum Poll { - /// Envoyer ces octets à cette adresse. + /// Send these bytes to this address. Transmit { contents: Vec, destination: SocketAddr, }, - /// Événement à propager à l'appelant. + /// Event to forward to the caller. Event(SessionEvent), - /// Prochaine échéance: rien d'autre à faire avant. + /// Next deadline: nothing else to do before it. Timeout(Instant), } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SessionEvent { - /// ICE et DTLS établis: le média peut circuler. + /// ICE and DTLS established: media can flow. Connected, IceState(IceConnectionState), - /// Une piste a été négociée, on connaît son `mid`. + /// A track was negotiated, its `mid` is known. MediaReady { mid: Mid, }, - /// Le pair a disparu ou a coupé. + /// The peer vanished or hung up. Disconnected, - /// Le navigateur ne peut plus décoder et réclame une image clé (PLI ou - /// FIR RTCP), après une perte par exemple. Sans réponse, il attend - /// l'image clé périodique de l'encodeur. + /// The browser can no longer decode and asks for a keyframe (RTCP PLI or + /// FIR), after a loss for example. Without an answer, it waits for the + /// encoder's periodic keyframe. KeyframeRequest, - /// Événement de str0m sans conséquence pour l'appelant (média entrant, - /// changement de direction, statistiques). Il ne doit surtout pas être - /// confondu avec une déconnexion: c'est le piège qui a coupé des sessions. + /// A str0m event with no consequence for the caller (incoming media, + /// direction change, statistics). It must never be mistaken for a + /// disconnection: that trap used to cut sessions. Noted(&'static str), } @@ -56,23 +56,23 @@ pub enum SessionEvent { pub enum SessionError { #[error("str0m: {0}")] Rtc(#[from] RtcError), - #[error("SDP refusé: {0}")] + #[error("SDP rejected: {0}")] Sdp(String), - #[error("aucun média négocié: attendre Event::MediaAdded")] + #[error("no media negotiated: wait for Event::MediaAdded")] NoMedia, - #[error("aucun type de charge utile vidéo négocié")] + #[error("no video payload type negotiated")] NoPayloadType, - #[error("session non connectée: attendre SessionEvent::Connected")] + #[error("session not connected: wait for SessionEvent::Connected")] NotConnected, #[error("I/O: {0}")] Io(#[from] std::io::Error), } -/// Une session par spectateur. +/// One session per viewer. pub struct Session { rtc: Rtc, candidate: SocketAddr, - /// Le codec réellement encodé: il décide du type de charge utile. + /// The codec actually encoded: it decides the payload type. codec: rs_codec::VideoCodec, fps: u8, mid: Option, @@ -89,26 +89,26 @@ impl Session { codec: rs_codec::VideoCodec, ) -> Result { let started = Instant::now(); - // On n'annonce que ce qu'on encode, et rien d'autre: proposer VP9 et - // envoyer du VP8 (ou l'inverse) donne un écran noir sans erreur, côté - // spectateur seulement. Les codecs par défaut de str0m (VP8, H.264, - // VP9, Opus) sont donc retirés avant d'activer le seul codec produit. + // Advertise only what we encode, nothing else: offering VP9 and + // sending VP8 (or the reverse) gives a black screen with no error, on + // the viewer side only. str0m's default codecs (VP8, H.264, VP9, Opus) + // are therefore cleared before enabling the single codec produced. // - // VP9 part en mode non flexible (F=0, le défaut de str0m): une seule - // couche, image clé signalée par P=0 et une structure de scalabilité, - // ce que libwebrtc émet lui-même pour du VP9 sans SVC. Le mode - // flexible ferait perdre les images inter à Safari. Décodage vérifié - // dans Firefox (`docs/perf.md`). + // VP9 goes out in non-flexible mode (F=0, str0m's default): a single + // layer, keyframe signalled by P=0 and a scalability structure, which + // is what libwebrtc itself emits for VP9 without SVC. Flexible mode + // would make Safari drop inter frames. Decoding checked in Firefox + // (`docs/perf.md`). let config = Rtc::builder() .clear_codecs() .enable_vp8(codec == rs_codec::VideoCodec::Vp8) .enable_vp9(codec == rs_codec::VideoCodec::Vp9) .set_vp9_packetizer_mode(Vp9PacketizerMode::NonFlexible); let mut rtc = config.build(started); - // Le candidat annoncé doit être l'adresse que le navigateur peut - // joindre: une adresse de bind (0.0.0.0) ne l'est pas. + // The advertised candidate must be an address the browser can reach: + // a bind address (0.0.0.0) is not one. let local = Candidate::host(candidate, "udp") - .map_err(|e| SessionError::Sdp(format!("candidat invalide: {e}")))?; + .map_err(|e| SessionError::Sdp(format!("invalid candidate: {e}")))?; rtc.add_local_candidate(local); Ok(Self { rtc, @@ -139,10 +139,10 @@ impl Session { self.started.elapsed() } - /// Accepte l'offre du spectateur et rend la réponse SDP. + /// Accepts the viewer's offer and returns the SDP answer. /// - /// Mode passif: c'est le navigateur qui offre (une piste `recvonly`), l'hôte - /// répond en `sendonly`. C'est le chemin validé par le spike. + /// Passive mode: the browser offers (a `recvonly` track), the host answers + /// `sendonly`. This is the path validated by the spike. pub fn accept_offer(&mut self, sdp: &str) -> Result { let offer = SdpOffer::from_sdp_string(sdp).map_err(|e| SessionError::Sdp(e.to_string()))?; let answer = self @@ -153,7 +153,7 @@ impl Session { Ok(answer.to_sdp_string()) } - /// Prochaine sortie de str0m, sans bloquer. + /// Next str0m output, without blocking. pub fn poll(&mut self) -> Result { match self.rtc.poll_output()? { Output::Transmit(t) => Ok(Poll::Transmit { @@ -185,14 +185,14 @@ impl Session { Event::KeyframeRequest(_) => SessionEvent::KeyframeRequest, Event::MediaData(_) => SessionEvent::Noted("media_data"), Event::MediaChanged(_) => SessionEvent::Noted("media_changed"), - _ => SessionEvent::Noted("autre"), + _ => SessionEvent::Noted("other"), } } - /// Datagramme reçu du réseau. + /// Datagram received from the network. /// - /// `destination` doit être l'adresse locale annoncée dans le SDP, pas - /// l'adresse de bind: sinon ICE reste bloqué en `Checking`. + /// `destination` must be the local address advertised in the SDP, not the + /// bind address: otherwise ICE stays stuck in `Checking`. pub fn receive( &mut self, now: Instant, @@ -202,7 +202,7 @@ impl Session { ) -> Result<(), SessionError> { let contents = datagram .try_into() - .map_err(|_| SessionError::Sdp("datagramme trop grand".into()))?; + .map_err(|_| SessionError::Sdp("datagram too large".into()))?; self.rtc.handle_input(Input::Receive( now, str0m::net::Receive { @@ -215,16 +215,16 @@ impl Session { Ok(()) } - /// Échéance armée par str0m (timers ICE, RTCP, DTLS). + /// Deadline armed by str0m (ICE, RTCP, DTLS timers). pub fn handle_timeout(&mut self, now: Instant) -> Result<(), SessionError> { self.rtc.handle_input(Input::Timeout(now))?; Ok(()) } - /// Écrit une frame encodée sur la piste négociée. + /// Writes an encoded frame on the negotiated track. /// - /// Refuse explicitement avant la connexion: écrire dans le vide donne une - /// session qui a l'air vivante et ne livre rien. + /// Explicitly refused before connection: writing into the void gives a + /// session that looks alive and delivers nothing. pub fn write_frame(&mut self, frame: &[u8], now: Instant) -> Result<(), SessionError> { if !self.connected { return Err(SessionError::NotConnected); @@ -235,13 +235,13 @@ impl Session { None => { let pt = { let writer = self.rtc.writer(mid).ok_or(SessionError::NoMedia)?; - choisir_pt(writer.payload_params(), self.codec) + pick_pt(writer.payload_params(), self.codec) .ok_or(SessionError::NoPayloadType)? }; tracing::info!( codec = self.codec.as_str(), pt = *pt, - "type de charge utile retenu" + "payload type selected" ); self.pt = Some(pt); pt @@ -254,22 +254,22 @@ impl Session { Ok(()) } - /// Horodatage RTP pour la n-ième frame, à la cadence de la session. + /// RTP timestamp of the n-th frame, at the session's frame rate. /// - /// Fonction pure, donc testable: une dérive ici se voit en gigue côté - /// spectateur, jamais dans nos propres logs. + /// A pure function, hence testable: a drift here shows up as jitter on the + /// viewer side, never in our own logs. pub fn rtp_timestamp(&self, frame_index: u64) -> u64 { frame_index * (VIDEO_CLOCK / self.fps as u64) } } -/// Le type de charge utile du codec encodé, parmi ceux que le pair a acceptés. +/// The payload type of the encoded codec, among those the peer accepted. /// -/// Pas le premier venu: c'était `payload_params().next()`, juste en VP8 par -/// le hasard de l'ordre d'annonce, et faux en VP9 (#67). Pour VP9, seul le -/// profil 0 (8 bits, 4:2:0) correspond à ce que produit l'encodeur; un -/// paramètre sans profil vaut profil 0 (RFC 9628). -fn choisir_pt<'a>( +/// Not just the first one: it used to be `payload_params().next()`, right for +/// VP8 by the luck of the advertising order, and wrong for VP9 (#67). For VP9, +/// only profile 0 (8 bits, 4:2:0) matches what the encoder produces; a +/// parameter without a profile means profile 0 (RFC 9628). +fn pick_pt<'a>( params: impl Iterator, codec: rs_codec::VideoCodec, ) -> Option { @@ -336,38 +336,38 @@ mod tests { assert!(matches!(err, SessionError::Sdp(_))); } - /// Une offre comme celle d'un navigateur: piste vidéo en réception seule, - /// avec tous les codecs par défaut (VP8, H.264, VP9 profils 0 et 2). - fn offre_navigateur() -> String { + /// An offer like a browser's: a receive-only video track, with every + /// default codec (VP8, H.264, VP9 profiles 0 and 2). + fn browser_offer() -> String { use str0m::media::{Direction, MediaKind}; - let mut navigateur = Rtc::builder().build(Instant::now()); - let mut changes = navigateur.sdp_api(); + let mut browser = Rtc::builder().build(Instant::now()); + let mut changes = browser.sdp_api(); changes.add_media(MediaKind::Video, Direction::RecvOnly, None, None, None); - let (offre, _) = changes.apply().expect("une offre"); - offre.to_sdp_string() + let (offer, _) = changes.apply().expect("an offer"); + offer.to_sdp_string() } - /// Accepte l'offre et rend la réponse, avec le type de charge utile que - /// la session choisirait pour écrire. - fn negocier(codec: rs_codec::VideoCodec) -> (String, Option) { + /// Accepts the offer and returns the answer, with the payload type the + /// session would pick to write. + fn negotiate(codec: rs_codec::VideoCodec) -> (String, Option) { let mut session = Session::new(candidate(), 30, codec).unwrap(); - let reponse = session - .accept_offer(&offre_navigateur()) - .expect("offre acceptée"); - let mid = reponse + let answer = session + .accept_offer(&browser_offer()) + .expect("offer accepted"); + let mid = answer .lines() .find_map(|l| l.strip_prefix("a=mid:")) .map(Mid::from) - .expect("piste vidéo négociée"); - let writer = session.rtc.writer(mid).expect("piste en écriture"); - (reponse, choisir_pt(writer.payload_params(), codec)) + .expect("video track negotiated"); + let writer = session.rtc.writer(mid).expect("writable track"); + (answer, pick_pt(writer.payload_params(), codec)) } - fn pt_de(reponse: &str, nom: &str) -> Vec { - reponse + fn pts_of(answer: &str, name: &str) -> Vec { + answer .lines() .filter_map(|l| l.strip_prefix("a=rtpmap:")) - .filter(|l| l.contains(&format!(" {nom}/90000"))) + .filter(|l| l.contains(&format!(" {name}/90000"))) .filter_map(|l| l.split(' ').next()?.parse::().ok()) .map(Pt::from) .collect() @@ -375,33 +375,33 @@ mod tests { #[test] fn the_answer_offers_only_the_encoded_codec() { - let (reponse, pt) = negocier(rs_codec::VideoCodec::Vp9); + let (answer, pt) = negotiate(rs_codec::VideoCodec::Vp9); assert!( - pt_de(&reponse, "VP8").is_empty(), - "VP8 annoncé en VP9:\n{reponse}" + pts_of(&answer, "VP8").is_empty(), + "VP8 advertised for VP9:\n{answer}" ); assert!( - pt_de(&reponse, "H264").is_empty(), - "H.264 annoncé:\n{reponse}" + pts_of(&answer, "H264").is_empty(), + "H.264 advertised:\n{answer}" ); - let vp9 = pt_de(&reponse, "VP9"); - assert!(!vp9.is_empty(), "VP9 absent de la réponse:\n{reponse}"); - let pt = pt.expect("type de charge utile VP9"); + let vp9 = pts_of(&answer, "VP9"); + assert!(!vp9.is_empty(), "VP9 missing from the answer:\n{answer}"); + let pt = pt.expect("VP9 payload type"); assert!(vp9.contains(&pt)); - // Profil 0: le seul que produit l'encodeur (8 bits, 4:2:0). + // Profile 0: the only one the encoder produces (8 bits, 4:2:0). let fmtp = format!("a=fmtp:{pt} "); - let ligne = reponse.lines().find(|l| l.starts_with(&fmtp)); + let line = answer.lines().find(|l| l.starts_with(&fmtp)); assert!( - ligne.is_none_or(|l| l.contains("profile-id=0")), - "profil VP9 inattendu: {ligne:?}" + line.is_none_or(|l| l.contains("profile-id=0")), + "unexpected VP9 profile: {line:?}" ); - let (reponse, pt) = negocier(rs_codec::VideoCodec::Vp8); + let (answer, pt) = negotiate(rs_codec::VideoCodec::Vp8); assert!( - pt_de(&reponse, "VP9").is_empty(), - "VP9 annoncé en VP8:\n{reponse}" + pts_of(&answer, "VP9").is_empty(), + "VP9 advertised for VP8:\n{answer}" ); - let vp8 = pt_de(&reponse, "VP8"); + let vp8 = pts_of(&answer, "VP8"); assert_eq!(pt.map(|pt| vp8.contains(&pt)), Some(true)); } @@ -418,24 +418,24 @@ mod tests { ..Default::default() }, }; - // L'ordre d'un navigateur: VP8 d'abord, VP9 profil 2 avant le profil 0. + // A browser's order: VP8 first, VP9 profile 2 before profile 0. let params = [ PayloadParams::new(96.into(), None, spec(Codec::Vp8, None)), PayloadParams::new(100.into(), None, spec(Codec::Vp9, Some(2))), PayloadParams::new(98.into(), None, spec(Codec::Vp9, Some(0))), ]; assert_eq!( - choisir_pt(params.iter(), rs_codec::VideoCodec::Vp9), + pick_pt(params.iter(), rs_codec::VideoCodec::Vp9), Some(98.into()) ); assert_eq!( - choisir_pt(params.iter(), rs_codec::VideoCodec::Vp8), + pick_pt(params.iter(), rs_codec::VideoCodec::Vp8), Some(96.into()) ); assert_eq!( - choisir_pt(params[..1].iter(), rs_codec::VideoCodec::Vp9), + pick_pt(params[..1].iter(), rs_codec::VideoCodec::Vp9), None, - "pas de repli silencieux sur un autre codec" + "no silent fallback to another codec" ); } @@ -452,6 +452,6 @@ mod tests { Poll::Transmit { .. } | Poll::Event(_) => {} } } - assert!(saw_timeout, "str0m doit toujours finir par un timeout"); + assert!(saw_timeout, "str0m must always end with a timeout"); } } diff --git a/crates/rs-session/Cargo.toml b/crates/rs-session/Cargo.toml index 9023a5c..5e13328 100644 --- a/crates/rs-session/Cargo.toml +++ b/crates/rs-session/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rs-session" -description = "Orchestration de l'hôte: partage, capture, serveur, spectateurs, réglages." +description = "Host orchestration: share, capture, server, viewers, settings." version.workspace = true edition.workspace = true rust-version.workspace = true @@ -8,7 +8,7 @@ license.workspace = true repository.workspace = true [features] -# Capture Wayland réelle. Exige libpipewire-0.3 et libclang au build (ADR 0009). +# Real Wayland capture. Needs libpipewire-0.3 and libclang at build time (ADR 0009). pipewire = ["rs-capture/pipewire"] [dependencies] diff --git a/crates/rs-session/examples/pipewire_local.rs b/crates/rs-session/examples/pipewire_local.rs index e1ba40f..078d5fa 100644 --- a/crates/rs-session/examples/pipewire_local.rs +++ b/crates/rs-session/examples/pipewire_local.rs @@ -1,16 +1,16 @@ -//! Banc PipeWire sans portail: branche la capture de production sur un nœud -//! vidéo local, l'encode, et affiche les compteurs du pipeline. +//! PipeWire bench without a portal: plugs the production capture into a local +//! video node, encodes it, and prints the pipeline counters. //! //! ```text //! gst-launch-1.0 videotestsrc is-live=true pattern=ball \ //! ! video/x-raw,format=BGRx,width=1920,height=1080,framerate=30/1 \ //! ! pipewiresink mode=provide client-name=rs-mire \ //! stream-properties="p,media.class=Video/Source" & -//! cargo run -p rs-session --features pipewire --example pipewire_local -- [vp8|vp9] +//! cargo run -p rs-session --features pipewire --example pipewire_local -- [vp8|vp9] //! ``` //! -//! Le portail ne fait que donner un descripteur et un numéro de nœud: ici, le -//! descripteur est une connexion au démon PipeWire de la session. +//! The portal only hands out a descriptor and a node number: here, the +//! descriptor is a connection to the session's PipeWire daemon. #[cfg(feature = "pipewire")] fn main() -> Result<(), Box> { @@ -22,46 +22,46 @@ fn main() -> Result<(), Box> { use rs_codec::{EncodeConfig, LiveSource, SharedMedia, VideoCodec, VpxEncoder}; let mut args = std::env::args().skip(1); - let noeud: u32 = args.next().ok_or("numéro de nœud attendu")?.parse()?; + let node: u32 = args.next().ok_or("node number expected")?.parse()?; let codec = match args.next().as_deref() { Some("vp9") => VideoCodec::Vp9, _ => VideoCodec::Vp8, }; let socket = std::env::var("XDG_RUNTIME_DIR")? + "/pipewire-0"; let fd: OwnedFd = UnixStream::connect(socket)?.into(); - let mut capture = PipeWireCapturer::connecter( + let mut capture = PipeWireCapturer::connect( fd, - noeud, + node, PipeWireOptions { fps: 30, size: None, }, )?; - let (w, h) = capture.attendre_format(std::time::Duration::from_secs(5))?; + let (w, h) = capture.wait_for_format(std::time::Duration::from_secs(5))?; let id = capture.sources()?.remove(0).id; capture.start(&id)?; - let encodeur = VpxEncoder::new(EncodeConfig { + let encoder = VpxEncoder::new(EncodeConfig { width: w & !1, height: h & !1, fps: 30, bitrate_kbps: 3000, codec, })?; - let live = LiveSource::spawn(capture, encodeur); - let mut vue = live.subscribe(); - let mut non_vides = 0; + let live = LiveSource::spawn(capture, encoder); + let mut view = live.subscribe(); + let mut non_empty = 0; for _ in 0..90 { - if !vue.next_frame().is_empty() { - non_vides += 1; + if !view.next_frame().is_empty() { + non_empty += 1; } std::thread::sleep(std::time::Duration::from_millis(33)); } - println!("format {w}x{h}, images non vides servies: {non_vides}"); + println!("format {w}x{h}, non-empty frames served: {non_empty}"); println!("{:?}", live.stats()); Ok(()) } #[cfg(not(feature = "pipewire"))] fn main() { - eprintln!("à compiler avec --features pipewire"); + eprintln!("build with --features pipewire"); } diff --git a/crates/rs-session/src/bin/rustscreen-cli.rs b/crates/rs-session/src/bin/rustscreen-cli.rs new file mode 100644 index 0000000..88b1fd0 --- /dev/null +++ b/crates/rs-session/src/bin/rustscreen-cli.rs @@ -0,0 +1,551 @@ +//! rustscreen-cli, the rustscreen host on the command line (`rustscreen` +//! itself opens the desktop application): captures the screen, serves the +//! viewer, negotiates sessions. +//! +//! The binary only reads its options and drives [`rs_session::Host`], like +//! the desktop shell: both share the same path. +//! +//! ```text +//! rustscreen-cli # the screen, through the portal or X11 +//! rustscreen-cli --virtual # a second screen, created by the portal +//! rustscreen-cli --synthetic # a test pattern, without a screen +//! rustscreen-cli --diagnostics # an archive to send, then exits +//! ``` + +use std::path::PathBuf; + +use rs_capture::{Backend, DisplaySession}; +use rs_platform::SessionType; +use rs_session::{Config, Host, Overrides, SourceChoice, VideoCodec}; + +type Error = Box; + +const USAGE: &str = "\ +rustscreen-cli, screen sharing over the local network, from a terminal +(the desktop application is `rustscreen`) + +usage: + rustscreen-cli [options] share the screen (portal under Wayland, X11 otherwise) + rustscreen-cli --virtual [options] create a second screen and share it + rustscreen-cli --synthetic [options] generated test pattern, to try without a screen + rustscreen-cli [options] replay a VP8 file + rustscreen-cli --diagnostics [FILE] write a diagnostics archive and exit + +options: + --port N listen port (settings, otherwise 8099) + --limit N number of viewers (settings, otherwise 5) + --size WxH size of the test pattern or virtual screen (1280x720, 1920x1080) + --codec CODEC vp8 or vp9 (settings, otherwise vp8; vp9: less bitrate, more CPU) + --viewer DIR directory of the built viewer + --tls serve over HTTPS with a self-signed certificate + --source NAME force the capture backend: portal, x11 or synthetic + --virtual virtual screen (desktop portal, GNOME 46 or KDE Plasma) + --pick-window Wayland: the desktop offers to pick a window + --list list capturable screens and windows, then exit + --x11-source ID X11: capture this source (identifier given by --list) + -S, --synthetic generated test pattern rather than a screen + --test-portal ask the portal for a screen and print the stream obtained + -h, --help this help + -V, --version version + +The port, network interface, limit and quality come from the settings +(~/.config/rustscreen/settings.json), shared with the desktop application. +The --port, --limit and --codec options override them for this launch only. +--codec only applies to a live capture: an IVF test pattern stays VP8. + +environment: + RUST_LOG verbosity per crate, by default rustscreen_cli=info,rs_rtc=info,... + RUSTSCREEN_CAPTURE forced capture backend (like --source) + RUSTSCREEN_CONFIG settings file + RUSTSCREEN_LOG_DIR log directory (~/.local/state/rustscreen/logs) + RUSTSCREEN_VIEWER directory of the built viewer (overridden by --viewer) + +exit code 3: the share was stopped from the desktop. +"; + +const FILTER: &str = "rustscreen_cli=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"; + +/// What the command line says. +#[derive(Debug, Default)] +struct Options { + playback: Option, + synthetic: bool, + source: Option, + virtual_display: bool, + pick_window: bool, + list: bool, + x11_source: Option, + /// `Some(None)`: archive in the current directory, under a dated name. + diagnostics: Option>, + test_portal: bool, + port: Option, + limit: Option, + tls: bool, + viewer: Option, + size: Option<(u32, u32)>, + codec: Option, +} + +fn read_options(args: impl Iterator) -> Result { + let mut options = Options::default(); + let mut args = args.peekable(); + let value = |args: &mut std::iter::Peekable<_>, name: &str| -> Result { + Iterator::next(args).ok_or_else(|| format!("{name} expects a value")) + }; + // A single loop, and no "first argument" handled apart: a package launches + // the binary with `--viewer` first. + while let Some(arg) = args.next() { + match arg.as_str() { + "--port" => { + let v = value(&mut args, "--port")?; + options.port = Some(v.parse().map_err(|_| format!("invalid port: {v}"))?); + } + "--limit" => { + let v = value(&mut args, "--limit")?; + options.limit = Some(v.parse().map_err(|_| format!("invalid limit: {v}"))?); + } + "--size" => { + let v = value(&mut args, "--size")?; + let size = v + .split_once('x') + .and_then(|(w, h)| Some((w.parse().ok()?, h.parse().ok()?))) + .filter(|&(w, h): &(u32, u32)| w >= 16 && h >= 16) + .ok_or_else(|| format!("invalid size: {v} (expected WxH)"))?; + options.size = Some(size); + } + "--codec" => { + let v = value(&mut args, "--codec")?; + options.codec = Some(v.parse()?); + } + "--tls" => options.tls = true, + "--synthetic" | "-S" => options.synthetic = true, + // The French spellings of earlier releases stay accepted: scripts + // and launchers may still use them. + "--virtual" | "--virtuel" => options.virtual_display = true, + "--pick-window" | "--une-fenetre" => options.pick_window = true, + "--list" | "--lister" => options.list = true, + "--test-portal" | "--test-portail" => options.test_portal = true, + "--viewer" => options.viewer = Some(PathBuf::from(value(&mut args, "--viewer")?)), + "--source" => options.source = Some(value(&mut args, "--source")?), + "--x11-source" | "--fenetre" => { + options.x11_source = Some(value(&mut args, arg.as_str())?); + } + "--diagnostics" => { + // The file is optional: the next value is one only if it is + // not an option. + let file = args.next_if(|a| !a.starts_with('-')).map(PathBuf::from); + options.diagnostics = Some(file); + } + other if other.starts_with('-') => return Err(format!("unknown argument: {other}")), + other => { + if options.playback.is_some() { + return Err(format!("one test pattern at a time: {other} is extra")); + } + options.playback = Some(PathBuf::from(other)); + } + } + } + Ok(options) +} + +/// Turns the options into a source to share. +fn choose(options: &Options, session: SessionType) -> Result { + if let Some(playback) = &options.playback { + return Ok(SourceChoice::Playback { + path: playback.display().to_string(), + }); + } + let backend = if options.synthetic { + Backend::Synthetic + } else { + let display = match session { + SessionType::Wayland => DisplaySession::Wayland, + SessionType::X11 => DisplaySession::X11, + SessionType::Headless => DisplaySession::Headless, + }; + let forced = options + .source + .clone() + .or_else(|| std::env::var(rs_capture::backend::OVERRIDE_VAR).ok()); + rs_capture::backend::choose(display, forced.as_deref())? + }; + tracing::info!(backend = backend.as_str(), "capture backend selected"); + Ok(match backend { + Backend::Synthetic => { + let (width, height) = options.size.unwrap_or((1280, 720)); + SourceChoice::Synthetic { width, height } + } + Backend::X11 => SourceChoice::X11 { + id: options + .x11_source + .clone() + .unwrap_or_else(|| "x11:ecran".into()), + }, + Backend::Portal => SourceChoice::Portal { + virtual_display: options.virtual_display, + window: options.pick_window, + size: options.size, + }, + }) +} + +#[tokio::main] +async fn main() -> Result<(), Error> { + // --help and --version come before everything else: an installed package + // must be able to say what it is without starting a server or opening a + // socket. + for arg in std::env::args().skip(1) { + match arg.as_str() { + "-h" | "--help" => { + print!("{USAGE}"); + return Ok(()); + } + "-V" | "--version" => { + println!("rustscreen-cli {}", env!("CARGO_PKG_VERSION")); + return Ok(()); + } + _ => {} + } + } + + let options = match read_options(std::env::args().skip(1)) { + Ok(options) => options, + Err(error) => { + eprintln!("{error}\n\n{USAGE}"); + std::process::exit(2); + } + }; + + let log = rs_diag::init(rs_diag::log_dir().as_deref(), FILTER); + if let Some(dir) = &log.dir { + tracing::info!(dir = %dir.display(), "log on disk"); + } + + if options.test_portal { + return test_portal().await; + } + if options.list { + return list(); + } + + let host = Host::new(Config { + version: env!("CARGO_PKG_VERSION").into(), + viewer_dir: options + .viewer + .clone() + .or_else(|| std::env::var_os("RUSTSCREEN_VIEWER").map(PathBuf::from)), + tls: options.tls, + store: rs_store::Store::user_default(), + overrides: Overrides { + port: options.port, + limit: options.limit, + codec: options.codec, + }, + log_dir: log.dir.clone(), + autostart: None, + }) + .await; + + // The main use case is extending the desktop onto a tablet: might as well + // say at startup what this desktop allows. + let environment = host.environment().clone(); + tracing::info!( + session = ?environment.session, + desktop = ?environment.desktop, + virtual_display = ?environment.virtual_display_backend(host.portal()), + "{}", + environment.advice(host.portal()) + ); + if let Some(message) = host.state().settings_recovered { + eprintln!(" {message}"); + } + + if let Some(file) = &options.diagnostics { + let path = file + .clone() + .unwrap_or_else(|| PathBuf::from(rs_diag::archive_name(std::time::SystemTime::now()))); + let context = host.context(); + let written = context.report().save(context.log_dir.as_deref(), &path)?; + println!("diagnostics written to {}", written.display()); + println!("no image, no window title, no MAC address: the file can be sent"); + return Ok(()); + } + + let choice = choose(&options, environment.session)?; + if matches!(choice, SourceChoice::Portal { .. }) { + println!(" the desktop may ask for permission to share the screen: answer the picker"); + } + if let Err(error) = host.start(choice).await { + eprintln!("\n cannot share: {error}"); + drop(log); + std::process::exit(1); + } + + let state = host.state(); + if let Some(share) = &state.share { + let local = share + .url + .split_once("/r/") + .map(|(_, rest)| rest) + .unwrap_or_default(); + let port = share.listen.rsplit(':').next().unwrap_or("8099"); + let scheme = if options.tls { "https" } else { "http" }; + println!("\n room : {}", share.room); + println!(" viewer: {}", share.url); + let home = share + .url + .split_once("/r/") + .map(|(start, _)| start) + .unwrap_or_default(); + println!( + " code : {} (no camera: open {home}/ and type it)", + displayed_code(&share.code) + ); + if let Some(end) = share.expires_ms { + let minutes = end.saturating_sub(now_ms()).div_ceil(60_000); + println!(" valid {minutes} min for a new device"); + } + if share.interface.is_none() { + println!(" local : {scheme}://127.0.0.1:{port}/r/{local}"); + println!(" host : {scheme}://127.0.0.1:{port}/ (dashboard, diagnostics)"); + } else { + println!(" listen: {} only", share.listen); + } + // The console QR saves opening a browser on the host to scan. + if let Ok(matrix) = rs_signaling::qr::encode(&share.url) { + println!("{}", rs_signaling::qr::render_ascii(&matrix)); + } + if !state.sleep_inhibited.is_empty() { + println!(" sleep suspended while sharing"); + } + } + if options.tls { + println!(" self-signed certificate: accept the warning once\n"); + } else { + println!(" page and signaling in clear text on the network (decision #65)"); + println!(" the video stream stays encrypted by DTLS-SRTP\n"); + } + + let code = tokio::select! { + stop = host.ended() => match stop { + Some(stop) if stop.by_desktop => { + // The user stopped the share from the desktop, or the screen + // went away: no point keeping a server that shows nothing. + eprintln!("\n {}", stop.reason); + eprintln!(" the share was stopped from the desktop, rustscreen-cli exits"); + 3 + } + Some(stop) => { + eprintln!("\n {}", stop.reason); + 1 + } + None => 0, + }, + _ = tokio::signal::ctrl_c() => { + tracing::info!(event = "stop_requested", "stop requested (Ctrl+C)"); + host.stop().await; + 0 + } + }; + + drop(log); + if code != 0 { + std::process::exit(code); + } + Ok(()) +} + +/// Capture diagnostic: opens the portal session, asks for a screen, starts, +/// and prints the descriptor obtained, without consuming the stream. +async fn test_portal() -> Result<(), Error> { + let session = rs_platform::Session::open().await?; + println!("session opened: {}", session.path()); + session.select_monitor(None).await?; + let stream = session.start().await?; + println!( + "stream obtained: node {} descriptor {:?} size {:?}", + stream.node_id, stream.fd, stream.size + ); + session.close().await; + Ok(()) +} + +/// The capturable sources. Window titles go to the console, never to the +/// log: they say what the user is doing (ADR 0008). +fn list() -> Result<(), Error> { + let environment = rs_platform::Environment::detect(); + for source in rs_session::sources::list(&environment, None) { + let id = match &source.choice { + SourceChoice::X11 { id } => id.clone(), + SourceChoice::Synthetic { .. } => "--synthetic".into(), + SourceChoice::Portal { + virtual_display: true, + .. + } => "--virtual".into(), + SourceChoice::Portal { window: true, .. } => "--pick-window".into(), + SourceChoice::Portal { .. } => "(portal)".into(), + SourceChoice::Playback { path } => path.clone(), + }; + println!( + "{:<28} {:<7} {:>5}x{:<5} {}", + id, + match source.kind { + rs_proto::SourceKind::Screen => "screen", + rs_proto::SourceKind::Window => "window", + }, + source.width, + source.height, + source.name + ); + if !source.available + && let Some(note) = source.note + { + println!("{:<28} {}", "", note.describe()); + } + } + if environment.session == SessionType::Wayland { + println!("under Wayland, the desktop itself offers the screens when the share starts"); + } + Ok(()) +} + +/// The short code as it is read and dictated: uppercase, two groups of three +/// (`K7M 4PQ`). +fn displayed_code(code: &str) -> String { + let code = code.to_uppercase(); + match code.char_indices().nth(3) { + Some((middle, _)) => format!("{} {}", &code[..middle], &code[middle..]), + None => code, + } +} + +fn now_ms() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_millis() as u64) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_short_code_is_shown_in_two_groups() { + assert_eq!(displayed_code("k7m4pq"), "K7M 4PQ"); + } + + fn read(args: &[&str]) -> Result { + read_options(args.iter().map(|a| a.to_string())) + } + + #[test] + fn options_are_read_in_any_order() { + let o = read(&[ + "--viewer", + "/v", + "--virtual", + "--size", + "1280x800", + "--port", + "9000", + ]) + .unwrap(); + assert_eq!(o.viewer, Some(PathBuf::from("/v"))); + assert!(o.virtual_display); + assert_eq!(o.size, Some((1280, 800))); + assert_eq!(o.port, Some(9000)); + } + + #[test] + fn the_former_french_options_are_still_accepted() { + let o = read(&[ + "--virtuel", + "--une-fenetre", + "--lister", + "--fenetre", + "0x2a", + ]) + .unwrap(); + assert!(o.virtual_display && o.pick_window && o.list); + assert_eq!(o.x11_source.as_deref(), Some("0x2a")); + assert!(read(&["--test-portail"]).unwrap().test_portal); + } + + #[test] + fn the_diagnostics_file_is_optional() { + assert_eq!(read(&["--diagnostics"]).unwrap().diagnostics, Some(None)); + assert_eq!( + read(&["--diagnostics", "a.zip"]).unwrap().diagnostics, + Some(Some(PathBuf::from("a.zip"))) + ); + let o = read(&["--diagnostics", "--tls"]).unwrap(); + assert_eq!(o.diagnostics, Some(None)); + assert!(o.tls, "the next option is not taken for a file"); + } + + #[test] + fn bad_values_are_refused_by_name() { + assert!(read(&["--port", "x"]).unwrap_err().contains("port")); + assert!(read(&["--size", "12"]).unwrap_err().contains("size")); + assert!(read(&["--source"]).unwrap_err().contains("--source")); + assert!( + read(&["--x11-source"]) + .unwrap_err() + .contains("--x11-source") + ); + assert!(read(&["--teleport"]).unwrap_err().contains("--teleport")); + assert!(read(&["a.ivf", "b.ivf"]).unwrap_err().contains("b.ivf")); + assert!(read(&["--codec", "h264"]).unwrap_err().contains("h264")); + assert!(read(&["--codec"]).unwrap_err().contains("--codec")); + } + + #[test] + fn the_codec_is_vp8_unless_asked() { + assert_eq!(read(&["-S"]).unwrap().codec, None); + assert_eq!( + read(&["--codec", "vp9", "-S"]).unwrap().codec, + Some(VideoCodec::Vp9) + ); + assert_eq!( + read(&["--codec", "VP8"]).unwrap().codec, + Some(VideoCodec::Vp8) + ); + } + + #[test] + fn options_become_a_source() { + let synthetic = read(&["-S", "--size", "640x360"]).unwrap(); + assert_eq!( + choose(&synthetic, SessionType::Wayland).unwrap(), + SourceChoice::Synthetic { + width: 640, + height: 360 + } + ); + let window = read(&["--source", "x11", "--x11-source", "0x2a"]).unwrap(); + assert_eq!( + choose(&window, SessionType::Wayland).unwrap(), + SourceChoice::X11 { id: "0x2a".into() } + ); + let virtual_display = read(&["--virtual"]).unwrap(); + assert_eq!( + choose(&virtual_display, SessionType::Wayland).unwrap(), + SourceChoice::Portal { + virtual_display: true, + window: false, + size: None + } + ); + let pick = read(&["--pick-window"]).unwrap(); + assert_eq!( + choose(&pick, SessionType::Wayland).unwrap(), + SourceChoice::Portal { + virtual_display: false, + window: true, + size: None + } + ); + } +} diff --git a/crates/rs-session/src/bin/rustscreen.rs b/crates/rs-session/src/bin/rustscreen.rs deleted file mode 100644 index 8a51110..0000000 --- a/crates/rs-session/src/bin/rustscreen.rs +++ /dev/null @@ -1,525 +0,0 @@ -//! Hôte rustscreen en ligne de commande: capture l'écran, sert le viewer, -//! négocie les sessions. -//! -//! Le binaire ne fait que lire ses options et piloter [`rs_session::Hote`], -//! comme la coque desktop: les deux partagent le même chemin. -//! -//! ```text -//! rustscreen # l'écran, par le portail ou X11 -//! rustscreen --virtuel # un second écran, créé par le portail -//! rustscreen --synthetic # une mire, sans écran -//! rustscreen --diagnostics # une archive à transmettre, puis sort -//! ``` - -use std::path::PathBuf; - -use rs_capture::{Backend, Graphique}; -use rs_platform::SessionType; -use rs_session::{Config, Hote, SourceChoisie, Surcharges, VideoCodec}; - -type Erreur = Box; - -const USAGE: &str = "\ -rustscreen, partage d'écran sur le réseau local - -usage: - rustscreen [options] partage l'écran (portail sous Wayland, X11 sinon) - rustscreen --virtuel [options] crée un second écran et le partage - rustscreen --synthetic [options] mire générée, pour essayer sans écran - rustscreen [options] rejoue un fichier VP8 - rustscreen --diagnostics [FICHIER] écrit une archive de diagnostics et sort - -options: - --port N port d'écoute (réglages, sinon 8099) - --limit N nombre de spectateurs (réglages, sinon 5) - --size LxH taille de la mire ou de l'écran virtuel (1280x720, 1920x1080) - --codec CODEC vp8 ou vp9 (réglages, sinon vp8; vp9: moins de débit, plus de calcul) - --viewer DIR dossier du viewer compilé - --tls servir en HTTPS avec un certificat auto-signé - --source NOM forcer le chemin de capture: portail, x11 ou synthetique - --virtuel écran virtuel (portail du bureau, GNOME 46 ou KDE Plasma) - --une-fenetre Wayland: le bureau propose de choisir une fenêtre - --lister lister les écrans et fenêtres capturables, puis sortir - --fenetre ID X11: capturer cette source (identifiant donné par --lister) - -S, --synthetic mire générée plutôt qu'un écran - --test-portail demande un écran au portail et affiche le flux obtenu - -h, --help cette aide - -V, --version version - -Le port, l'interface réseau, la limite et la qualité viennent des réglages -(~/.config/rustscreen/reglages.json), partagés avec l'application de bureau. -Les options --port, --limit et --codec les remplacent pour ce lancement seulement. ---codec ne vaut que pour une capture en direct: une mire IVF reste en VP8. - -variables: - RUST_LOG verbosité par crate, par défaut rustscreen=info,rs_rtc=info,... - RUSTSCREEN_CAPTURE chemin de capture forcé (comme --source) - RUSTSCREEN_CONFIG fichier de réglages - RUSTSCREEN_LOG_DIR dossier des journaux (~/.local/state/rustscreen/logs) - RUSTSCREEN_VIEWER dossier du viewer compilé (remplacé par --viewer) - -code de sortie 3: le partage a été arrêté depuis le bureau. -"; - -const FILTRE: &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"; - -/// Ce que dit la ligne de commande. -#[derive(Debug, Default)] -struct Options { - mire: Option, - synthetic: bool, - source: Option, - virtuel: bool, - une_fenetre: bool, - lister: bool, - fenetre: Option, - /// `Some(None)`: archive dans le dossier courant, sous un nom daté. - diagnostics: Option>, - test_portail: bool, - port: Option, - limit: Option, - tls: bool, - viewer: Option, - size: Option<(u32, u32)>, - codec: Option, -} - -fn lire_options(args: impl Iterator) -> Result { - let mut options = Options::default(); - let mut args = args.peekable(); - let valeur = |args: &mut std::iter::Peekable<_>, nom: &str| -> Result { - Iterator::next(args).ok_or_else(|| format!("{nom} attend une valeur")) - }; - // Une seule boucle, et pas de « premier argument » traité à part: un paquet - // lance le binaire avec `--viewer` en tête. - while let Some(arg) = args.next() { - match arg.as_str() { - "--port" => { - let v = valeur(&mut args, "--port")?; - options.port = Some(v.parse().map_err(|_| format!("port invalide: {v}"))?); - } - "--limit" => { - let v = valeur(&mut args, "--limit")?; - options.limit = Some(v.parse().map_err(|_| format!("limite invalide: {v}"))?); - } - "--size" => { - let v = valeur(&mut args, "--size")?; - let taille = v - .split_once('x') - .and_then(|(w, h)| Some((w.parse().ok()?, h.parse().ok()?))) - .filter(|&(w, h): &(u32, u32)| w >= 16 && h >= 16) - .ok_or_else(|| format!("taille invalide: {v} (attendu LxH)"))?; - options.size = Some(taille); - } - "--codec" => { - let v = valeur(&mut args, "--codec")?; - options.codec = Some(v.parse()?); - } - "--tls" => options.tls = true, - "--synthetic" | "-S" => options.synthetic = true, - "--virtuel" => options.virtuel = true, - "--une-fenetre" => options.une_fenetre = true, - "--lister" => options.lister = true, - "--test-portail" => options.test_portail = true, - "--viewer" => options.viewer = Some(PathBuf::from(valeur(&mut args, "--viewer")?)), - "--source" => options.source = Some(valeur(&mut args, "--source")?), - "--fenetre" => options.fenetre = Some(valeur(&mut args, "--fenetre")?), - "--diagnostics" => { - // Le fichier est facultatif: la valeur suivante n'en est un que - // si ce n'est pas une option. - let fichier = args.next_if(|a| !a.starts_with('-')).map(PathBuf::from); - options.diagnostics = Some(fichier); - } - autre if autre.starts_with('-') => return Err(format!("argument inconnu: {autre}")), - autre => { - if options.mire.is_some() { - return Err(format!("une seule mire à la fois: {autre} en trop")); - } - options.mire = Some(PathBuf::from(autre)); - } - } - } - Ok(options) -} - -/// Traduit les options en source à partager. -fn choisir(options: &Options, session: SessionType) -> Result { - if let Some(mire) = &options.mire { - return Ok(SourceChoisie::Mire { - chemin: mire.display().to_string(), - }); - } - let backend = if options.synthetic { - Backend::Synthetique - } else { - let graphique = match session { - SessionType::Wayland => Graphique::Wayland, - SessionType::X11 => Graphique::X11, - SessionType::Headless => Graphique::Aucune, - }; - let forcage = options - .source - .clone() - .or_else(|| std::env::var(rs_capture::backend::FORCAGE).ok()); - rs_capture::backend::choisir(graphique, forcage.as_deref())? - }; - tracing::info!(chemin = backend.as_str(), "chemin de capture retenu"); - Ok(match backend { - Backend::Synthetique => { - let (largeur, hauteur) = options.size.unwrap_or((1280, 720)); - SourceChoisie::Synthetique { largeur, hauteur } - } - Backend::X11 => SourceChoisie::X11 { - id: options - .fenetre - .clone() - .unwrap_or_else(|| "x11:ecran".into()), - }, - Backend::Portail => SourceChoisie::Portail { - virtuel: options.virtuel, - fenetre: options.une_fenetre, - taille: options.size, - }, - }) -} - -#[tokio::main] -async fn main() -> Result<(), Erreur> { - // --help et --version passent avant tout le reste: un paquet installé doit - // pouvoir dire ce qu'il est sans démarrer de serveur ni ouvrir de socket. - for arg in std::env::args().skip(1) { - match arg.as_str() { - "-h" | "--help" => { - print!("{USAGE}"); - return Ok(()); - } - "-V" | "--version" => { - println!("rustscreen {}", env!("CARGO_PKG_VERSION")); - return Ok(()); - } - _ => {} - } - } - - let options = match lire_options(std::env::args().skip(1)) { - Ok(options) => options, - Err(erreur) => { - eprintln!("{erreur}\n\n{USAGE}"); - std::process::exit(2); - } - }; - - let journal = rs_diag::initialiser(rs_diag::dossier_journaux().as_deref(), FILTRE); - if let Some(dossier) = &journal.dossier { - tracing::info!(dossier = %dossier.display(), "journal sur disque"); - } - - if options.test_portail { - return test_portail().await; - } - if options.lister { - return lister(); - } - - let hote = Hote::nouveau(Config { - version: env!("CARGO_PKG_VERSION").into(), - viewer_dir: options - .viewer - .clone() - .or_else(|| std::env::var_os("RUSTSCREEN_VIEWER").map(PathBuf::from)), - tls: options.tls, - magasin: rs_store::Magasin::par_defaut(), - surcharges: Surcharges { - port: options.port, - limite: options.limit, - codec: options.codec, - }, - journaux: journal.dossier.clone(), - demarrage_auto: None, - }) - .await; - - // Le cas d'usage principal est d'étendre le bureau sur une tablette: autant - // dire au démarrage ce que ce bureau permet. - let environnement = hote.environnement().clone(); - tracing::info!( - session = ?environnement.session, - bureau = ?environnement.desktop, - ecran_virtuel = ?environnement.virtual_display_backend(hote.portail()), - "{}", - environnement.conseil(hote.portail()) - ); - if let Some(message) = hote.etat().reglages_recuperes { - eprintln!(" {message}"); - } - - if let Some(fichier) = &options.diagnostics { - let chemin = fichier - .clone() - .unwrap_or_else(|| PathBuf::from(rs_diag::nom_archive(std::time::SystemTime::now()))); - let contexte = hote.contexte(); - let ecrit = contexte - .rapport() - .enregistrer(contexte.journaux.as_deref(), &chemin)?; - println!("diagnostics écrits dans {}", ecrit.display()); - println!("ni image, ni titre de fenêtre, ni adresse MAC: le fichier peut être transmis"); - return Ok(()); - } - - let choix = choisir(&options, environnement.session)?; - if matches!(choix, SourceChoisie::Portail { .. }) { - println!( - " le bureau peut demander l'autorisation de partager l'écran: répondre au sélecteur" - ); - } - if let Err(erreur) = hote.demarrer(choix).await { - eprintln!("\n partage impossible: {erreur}"); - drop(journal); - std::process::exit(1); - } - - let etat = hote.etat(); - if let Some(partage) = &etat.partage { - let locale = partage - .url - .split_once("/r/") - .map(|(_, suite)| suite) - .unwrap_or_default(); - let port = partage.ecoute.rsplit(':').next().unwrap_or("8099"); - let scheme = if options.tls { "https" } else { "http" }; - println!("\n room : {}", partage.room); - println!(" viewer: {}", partage.url); - let accueil = partage - .url - .split_once("/r/") - .map(|(debut, _)| debut) - .unwrap_or_default(); - println!( - " code : {} (sans caméra: ouvrir {accueil}/ et le taper)", - code_affiche(&partage.code) - ); - if let Some(fin) = partage.expire_ms { - let minutes = fin.saturating_sub(maintenant_ms()).div_ceil(60_000); - println!(" valable {minutes} min pour un nouvel appareil"); - } - if partage.interface.is_none() { - println!(" local : {scheme}://127.0.0.1:{port}/r/{locale}"); - println!(" hôte : {scheme}://127.0.0.1:{port}/ (tableau de bord, diagnostics)"); - } else { - println!(" écoute: {} seulement", partage.ecoute); - } - // Le QR de la console évite d'ouvrir un navigateur sur l'hôte pour scanner. - if let Ok(matrice) = rs_signaling::qr::encode(&partage.url) { - println!("{}", rs_signaling::qr::render_ascii(&matrice)); - } - if !etat.veille_inhibee.is_empty() { - println!(" mise en veille suspendue pendant le partage"); - } - } - if options.tls { - println!(" certificat auto-signé: accepter l'avertissement une fois\n"); - } else { - println!(" page et signalement en clair sur le réseau (décision #65)"); - println!(" le flux vidéo reste chiffré par DTLS-SRTP\n"); - } - - let code = tokio::select! { - arret = hote.fin() => match arret { - Some(arret) if arret.par_le_bureau => { - // L'utilisateur a arrêté le partage depuis le bureau, ou l'écran a - // disparu: inutile de garder un serveur qui ne montre plus rien. - eprintln!("\n {}", arret.raison); - eprintln!(" le partage a été arrêté depuis le bureau, rustscreen s'arrête"); - 3 - } - Some(arret) => { - eprintln!("\n {}", arret.raison); - 1 - } - None => 0, - }, - _ = tokio::signal::ctrl_c() => { - tracing::info!(evenement = "arret_demande", "arrêt demandé (Ctrl+C)"); - hote.arreter().await; - 0 - } - }; - - drop(journal); - if code != 0 { - std::process::exit(code); - } - Ok(()) -} - -/// Diagnostic de capture: ouvre la session portail, demande un écran, -/// démarre, et rend le descripteur obtenu, sans consommer le flux. -async fn test_portail() -> Result<(), Erreur> { - let session = rs_platform::Session::ouvrir().await?; - println!("session ouverte: {}", session.chemin()); - session.choisir_un_ecran(None).await?; - let flux = session.demarrer().await?; - println!( - "flux obtenu: nœud {} descripteur {:?} taille {:?}", - flux.node_id, flux.fd, flux.taille - ); - session.fermer().await; - Ok(()) -} - -/// Les sources capturables. Les titres de fenêtres vont à la console, jamais -/// au journal: ils disent ce que fait l'utilisateur (ADR 0008). -fn lister() -> Result<(), Erreur> { - let environnement = rs_platform::Environment::detect(); - for source in rs_session::sources::proposer(&environnement, None) { - let id = match &source.choix { - SourceChoisie::X11 { id } => id.clone(), - SourceChoisie::Synthetique { .. } => "--synthetic".into(), - SourceChoisie::Portail { virtuel: true, .. } => "--virtuel".into(), - SourceChoisie::Portail { fenetre: true, .. } => "--une-fenetre".into(), - SourceChoisie::Portail { .. } => "(portail)".into(), - SourceChoisie::Mire { chemin } => chemin.clone(), - }; - println!( - "{:<28} {:<7} {:>5}x{:<5} {}", - id, - match source.genre { - rs_proto::SourceKind::Screen => "écran", - rs_proto::SourceKind::Window => "fenêtre", - }, - source.largeur, - source.hauteur, - source.nom - ); - if !source.disponible - && let Some(note) = source.note - { - println!("{:<28} {}", "", note.en_francais()); - } - } - if environnement.session == SessionType::Wayland { - println!("sous Wayland, le bureau propose lui-même les écrans au démarrage du partage"); - } - Ok(()) -} - -/// Le code court tel qu'on le lit et le dicte: majuscules, deux groupes de -/// trois (`K7M 4PQ`). -fn code_affiche(code: &str) -> String { - let code = code.to_uppercase(); - match code.char_indices().nth(3) { - Some((milieu, _)) => format!("{} {}", &code[..milieu], &code[milieu..]), - None => code, - } -} - -fn maintenant_ms() -> u64 { - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_or(0, |d| d.as_millis() as u64) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn the_short_code_is_shown_in_two_groups() { - assert_eq!(code_affiche("k7m4pq"), "K7M 4PQ"); - } - - fn lire(args: &[&str]) -> Result { - lire_options(args.iter().map(|a| a.to_string())) - } - - #[test] - fn options_are_read_in_any_order() { - let o = lire(&[ - "--viewer", - "/v", - "--virtuel", - "--size", - "1280x800", - "--port", - "9000", - ]) - .unwrap(); - assert_eq!(o.viewer, Some(PathBuf::from("/v"))); - assert!(o.virtuel); - assert_eq!(o.size, Some((1280, 800))); - assert_eq!(o.port, Some(9000)); - } - - #[test] - fn the_diagnostics_file_is_optional() { - assert_eq!(lire(&["--diagnostics"]).unwrap().diagnostics, Some(None)); - assert_eq!( - lire(&["--diagnostics", "a.zip"]).unwrap().diagnostics, - Some(Some(PathBuf::from("a.zip"))) - ); - let o = lire(&["--diagnostics", "--tls"]).unwrap(); - assert_eq!(o.diagnostics, Some(None)); - assert!(o.tls, "l'option suivante n'est pas prise pour un fichier"); - } - - #[test] - fn bad_values_are_refused_by_name() { - assert!(lire(&["--port", "x"]).unwrap_err().contains("port")); - assert!(lire(&["--size", "12"]).unwrap_err().contains("taille")); - assert!(lire(&["--source"]).unwrap_err().contains("--source")); - assert!(lire(&["--teleport"]).unwrap_err().contains("--teleport")); - assert!(lire(&["a.ivf", "b.ivf"]).unwrap_err().contains("b.ivf")); - assert!(lire(&["--codec", "h264"]).unwrap_err().contains("h264")); - assert!(lire(&["--codec"]).unwrap_err().contains("--codec")); - } - - #[test] - fn the_codec_is_vp8_unless_asked() { - assert_eq!(lire(&["-S"]).unwrap().codec, None); - assert_eq!( - lire(&["--codec", "vp9", "-S"]).unwrap().codec, - Some(VideoCodec::Vp9) - ); - assert_eq!( - lire(&["--codec", "VP8"]).unwrap().codec, - Some(VideoCodec::Vp8) - ); - } - - #[test] - fn options_become_a_source() { - let synthetique = lire(&["-S", "--size", "640x360"]).unwrap(); - assert_eq!( - choisir(&synthetique, SessionType::Wayland).unwrap(), - SourceChoisie::Synthetique { - largeur: 640, - hauteur: 360 - } - ); - let fenetre = lire(&["--source", "x11", "--fenetre", "0x2a"]).unwrap(); - assert_eq!( - choisir(&fenetre, SessionType::Wayland).unwrap(), - SourceChoisie::X11 { id: "0x2a".into() } - ); - let virtuel = lire(&["--virtuel"]).unwrap(); - assert_eq!( - choisir(&virtuel, SessionType::Wayland).unwrap(), - SourceChoisie::Portail { - virtuel: true, - fenetre: false, - taille: None - } - ); - let une = lire(&["--une-fenetre"]).unwrap(); - assert_eq!( - choisir(&une, SessionType::Wayland).unwrap(), - SourceChoisie::Portail { - virtuel: false, - fenetre: true, - taille: None - } - ); - } -} diff --git a/crates/rs-session/src/capture.rs b/crates/rs-session/src/capture.rs index 0d93b10..d91281d 100644 --- a/crates/rs-session/src/capture.rs +++ b/crates/rs-session/src/capture.rs @@ -1,7 +1,7 @@ -//! Ouvrir une capture et son encodeur, quelle que soit la source choisie. +//! Open a capture and its encoder, whatever the chosen source. //! -//! C'était le corps du binaire `rustscreen`; la coque desktop en a besoin -//! aussi, donc il vit ici, une seule fois. +//! This used to be the body of the `rustscreen` binary; the desktop shell +//! needs it too, so it lives here, once. use std::path::PathBuf; use std::sync::Arc; @@ -15,68 +15,68 @@ use rs_platform::PortalInfo; use rs_proto::{SourceId, SourceKind, StreamSettings}; use rs_signaling::SharedMediaSource; -use crate::etat::{Libelle, SourceChoisie, SourcePartagee}; +use crate::state::{Label, SharedSource, SourceChoice}; -/// Taille d'un écran virtuel quand l'utilisateur n'en donne pas. -pub const TAILLE_VIRTUELLE: (u32, u32) = (1920, 1080); +/// Size of a virtual screen when the user gives none. +pub const DEFAULT_VIRTUAL_SIZE: (u32, u32) = (1920, 1080); -/// Une capture ouverte, prête à servir. -pub struct CaptureLancee { +/// An open capture, ready to serve. +pub struct StartedCapture { pub media: SharedMediaSource, - /// La source en direct, absente pour un rejeu de fichier. + /// The live source, absent for a file replay. pub live: Option>, - /// La session portail, à fermer à l'arrêt. - pub portail: Option, - pub source: SourcePartagee, - pub encodage: Option, + /// The portal session, to close on stop. + pub portal: Option, + pub source: SharedSource, + pub encode: Option, } #[derive(Debug, thiserror::Error)] -pub enum CaptureLanceeError { +pub enum StartCaptureError { #[error("{0}")] Capture(#[from] rs_capture::CaptureError), - #[error("portail: {0}")] - Portail(#[from] rs_platform::PortalError), - #[error("encodeur indisponible: {0}")] - Encodeur(#[from] rs_codec::EncodeError), - #[error("mire: {0}")] - Mire(String), + #[error("portal: {0}")] + Portal(#[from] rs_platform::PortalError), + #[error("encoder unavailable: {0}")] + Encoder(#[from] rs_codec::EncodeError), + #[error("test pattern: {0}")] + Playback(String), #[error("{0}")] - Refus(String), + Rejected(String), } -/// Ouvre la source choisie. Les étapes bloquantes (X11, PipeWire, lecture -/// d'un fichier) passent par `spawn_blocking`: l'appelant est une tâche tokio. +/// Opens the chosen source. The blocking steps (X11, PipeWire, reading a +/// file) go through `spawn_blocking`: the caller is a tokio task. /// -/// `codec` vaut pour une capture en direct. Le rejeu d'une mire IVF garde le -/// codec du fichier (VP8), et les sessions l'annoncent tel quel. -pub async fn lancer( - choix: &SourceChoisie, +/// `codec` applies to a live capture. Replaying an IVF test pattern keeps the +/// file's codec (VP8), and sessions announce it as is. +pub async fn start( + choice: &SourceChoice, settings: &StreamSettings, codec: VideoCodec, - #[cfg_attr(not(feature = "pipewire"), allow(unused_variables))] portail: Option< + #[cfg_attr(not(feature = "pipewire"), allow(unused_variables))] portal: Option< &rs_platform::PortalInfo, >, -) -> Result { +) -> Result { let fps = settings.max_fps; - match choix { - SourceChoisie::Synthetique { largeur, hauteur } => { - let (w, h) = rs_capture::pixels::even((*largeur, *hauteur)); + match choice { + SourceChoice::Synthetic { width, height } => { + let (w, h) = rs_capture::pixels::even((*width, *height)); if w < 16 || h < 16 { - return Err(CaptureLanceeError::Refus(format!( - "mire de {largeur}x{hauteur}: trop petite" + return Err(StartCaptureError::Rejected(format!( + "{width}x{height} test pattern: too small" ))); } let capturer = SyntheticCapturer::new(w, h, fps); - let source = SourcePartagee { - genre: SourceKind::Screen, - nom: "Mire de test".into(), - libelle: Libelle::Mire, - chemin: "synthetique".into(), - largeur: w, - hauteur: h, + let source = SharedSource { + kind: SourceKind::Screen, + name: "Test pattern".into(), + label: Label::TestPattern, + backend: "synthetic".into(), + width: w, + height: h, }; - demarrer( + spawn_live( capturer, (w, h), settings, @@ -85,28 +85,28 @@ pub async fn lancer( source, ) } - SourceChoisie::Mire { chemin } => { - let chemin = PathBuf::from(chemin); - let ivf = tokio::task::spawn_blocking(move || IvfFile::load(&chemin)) + SourceChoice::Playback { path } => { + let path = PathBuf::from(path); + let ivf = tokio::task::spawn_blocking(move || IvfFile::load(&path)) .await - .map_err(|e| CaptureLanceeError::Mire(e.to_string()))? - .map_err(|e| CaptureLanceeError::Mire(e.to_string()))?; + .map_err(|e| StartCaptureError::Playback(e.to_string()))? + .map_err(|e| StartCaptureError::Playback(e.to_string()))?; tracing::info!( frames = ivf.frames.len(), width = ivf.width, height = ivf.height, fps = ivf.fps, - "mire IVF chargée (rejeu, pas d'encodage)" + "IVF test pattern loaded (replay, no encoding)" ); - let source = SourcePartagee { - genre: SourceKind::Screen, - nom: "Mire enregistrée".into(), - libelle: Libelle::MireEnregistree, - chemin: "ivf".into(), - largeur: ivf.width, - hauteur: ivf.height, + let source = SharedSource { + kind: SourceKind::Screen, + name: "Recorded test pattern".into(), + label: Label::RecordedPattern, + backend: "ivf".into(), + width: ivf.width, + height: ivf.height, }; - Ok(CaptureLancee { + Ok(StartedCapture { media: Arc::new(SharedPlayback::new( ivf.frames.clone(), ivf.fps, @@ -114,27 +114,27 @@ pub async fn lancer( ivf.height, )), live: None, - portail: None, + portal: None, source, - encodage: None, + encode: None, }) } - SourceChoisie::X11 { id } => x11(id.clone(), settings, codec).await, - SourceChoisie::Portail { - virtuel, - fenetre, - taille, + SourceChoice::X11 { id } => x11(id.clone(), settings, codec).await, + SourceChoice::Portal { + virtual_display, + window, + size, } => { #[cfg(feature = "pipewire")] { - portail_pipewire(*virtuel, *fenetre, *taille, portail, settings, codec).await + portal_pipewire(*virtual_display, *window, *size, portal, settings, codec).await } #[cfg(not(feature = "pipewire"))] { - let _ = (virtuel, fenetre, taille, codec); - Err(CaptureLanceeError::Refus( - "ce binaire est compilé sans PipeWire: la capture Wayland demande la \ - feature `pipewire` (voir ADR 0009)" + let _ = (virtual_display, window, size, codec); + Err(StartCaptureError::Rejected( + "this binary is built without PipeWire: Wayland capture needs the \ + `pipewire` feature (see ADR 0009)" .into(), )) } @@ -147,49 +147,49 @@ async fn x11( id: String, settings: &StreamSettings, codec: VideoCodec, -) -> Result { +) -> Result { let settings = *settings; tokio::task::spawn_blocking(move || { - let mut capturer = rs_capture::x11::X11Capturer::connecter(None, settings.max_fps)?; + let mut capturer = rs_capture::x11::X11Capturer::connect(None, settings.max_fps)?; let sources = capturer.sources()?; - let voulue = sources + let wanted = sources .iter() .find(|s| s.id.0 == id || s.id.0.ends_with(id.as_str())) .ok_or_else(|| { - CaptureLanceeError::Refus(format!("source {id} introuvable: voir --lister")) + StartCaptureError::Rejected(format!("source {id} not found: see --list")) })?; - let taille = rs_capture::pixels::even((voulue.width, voulue.height)); + let size = rs_capture::pixels::even((wanted.width, wanted.height)); tracing::info!( - evenement = "capture_x11", - genre = ?voulue.kind, - largeur = taille.0, - hauteur = taille.1, - shm = capturer.utilise_shm(), - "capture X11" + event = "x11_capture", + kind = ?wanted.kind, + width = size.0, + height = size.1, + shm = capturer.uses_shm(), + "X11 capture" ); - let libelle = match voulue.id.0.strip_prefix("x11:moniteur:") { - Some(sortie) => Libelle::Moniteur { - principal: capturer.moniteur_principal().as_deref() == Some(sortie), - sortie: sortie.to_string(), + let label = match wanted.id.0.strip_prefix("x11:moniteur:") { + Some(output) => Label::Monitor { + primary: capturer.primary_monitor().as_deref() == Some(output), + output: output.to_string(), }, - None if voulue.kind == SourceKind::Window => Libelle::Titre { - texte: voulue.name.clone(), + None if wanted.kind == SourceKind::Window => Label::Title { + text: wanted.name.clone(), }, - None => Libelle::EcranEntier, + None => Label::EntireScreen, }; - let source = SourcePartagee { - genre: voulue.kind, - nom: voulue.name.clone(), - libelle, - chemin: "x11".into(), - largeur: taille.0, - hauteur: taille.1, + let source = SharedSource { + kind: wanted.kind, + name: wanted.name.clone(), + label, + backend: "x11".into(), + width: size.0, + height: size.1, }; - let id = voulue.id.clone(); - demarrer(capturer, taille, &settings, codec, &id, source) + let id = wanted.id.clone(); + spawn_live(capturer, size, &settings, codec, &id, source) }) .await - .map_err(|e| CaptureLanceeError::Refus(e.to_string()))? + .map_err(|e| StartCaptureError::Rejected(e.to_string()))? } #[cfg(not(target_os = "linux"))] @@ -197,33 +197,33 @@ async fn x11( _: String, _: &StreamSettings, _: VideoCodec, -) -> Result { - Err(CaptureLanceeError::Refus( - "X11 n'existe que sous Linux".into(), +) -> Result { + Err(StartCaptureError::Rejected( + "X11 only exists on Linux".into(), )) } -/// Démarre une capture et son encodeur dans le thread dédié. -fn demarrer( +/// Starts a capture and its encoder in the dedicated thread. +fn spawn_live( mut capturer: C, - taille: (u32, u32), + size: (u32, u32), settings: &StreamSettings, codec: VideoCodec, id: &SourceId, - source: SourcePartagee, -) -> Result + source: SharedSource, +) -> Result where C: ScreenCapturer + 'static, { let config = EncodeConfig { - width: taille.0 & !1, - height: taille.1 & !1, + width: size.0 & !1, + height: size.1 & !1, fps: settings.max_fps, bitrate_kbps: settings.max_bitrate_kbps, codec, }; - // Un encodeur qui ne s'initialise pas doit faire échouer le lancement, pas - // la connexion d'un spectateur. + // An encoder that fails to initialize must fail the start, not a viewer's + // connection. let encoder = VpxEncoder::new(config)?; capturer.start(id)?; tracing::info!( @@ -232,112 +232,125 @@ where fps = config.fps, bitrate = config.bitrate_kbps, codec = config.codec.as_str(), - "encodage en direct" + "live encoding" ); let live = Arc::new(LiveSource::spawn(capturer, encoder)); - Ok(CaptureLancee { + Ok(StartedCapture { media: live.clone(), live: Some(live), - portail: None, + portal: None, source, - encodage: Some(config), + encode: Some(config), }) } -/// Dossier d'état, à côté des journaux: le jeton de restauration du portail y -/// vit, pour ne pas redemander l'écran à chaque lancement. +/// State directory, next to the logs: the portal restore token lives there, +/// so the screen is not asked for again at every launch. #[cfg(feature = "pipewire")] -fn fichier_restauration() -> Option { - rs_diag::dossier_journaux() - .and_then(|logs| logs.parent().map(std::path::Path::to_path_buf)) - .map(|etat| etat.join("portail-restauration")) +fn state_dir() -> Option { + rs_diag::log_dir().and_then(|logs| logs.parent().map(std::path::Path::to_path_buf)) +} + +/// File holding the portal restore token. +#[cfg(feature = "pipewire")] +const RESTORE_TOKEN_FILE: &str = "portal-restore-token"; +/// Its former name, still read when the new file is missing: users already +/// have one, and losing it would ask for the screen again. +#[cfg(feature = "pipewire")] +const LEGACY_RESTORE_TOKEN_FILE: &str = "portail-restauration"; + +/// Reads the restore token, from the new file or else the legacy one. +#[cfg(feature = "pipewire")] +fn read_restore_token(dir: &std::path::Path) -> Option { + [RESTORE_TOKEN_FILE, LEGACY_RESTORE_TOKEN_FILE] + .iter() + .find_map(|name| std::fs::read_to_string(dir.join(name)).ok()) + .map(|token| token.trim().to_string()) } #[cfg(feature = "pipewire")] -async fn portail_pipewire( - virtuel: bool, - fenetre: bool, - taille: Option<(u32, u32)>, - portail: Option<&PortalInfo>, +async fn portal_pipewire( + virtual_display: bool, + window: bool, + size: Option<(u32, u32)>, + portal: Option<&PortalInfo>, settings: &StreamSettings, codec: VideoCodec, -) -> Result { +) -> Result { use rs_capture::pipewire::{PipeWireCapturer, PipeWireOptions}; - use rs_platform::TypeSource; + use rs_platform::SourceType; - if virtuel && !portail.is_some_and(PortalInfo::supporte_ecran_virtuel) { - return Err(CaptureLanceeError::Refus( - "le portail de ce bureau ne sait pas créer d'écran virtuel (type VIRTUAL absent \ - de AvailableSourceTypes): partager un écran existant" + if virtual_display && !portal.is_some_and(PortalInfo::supports_virtual_display) { + return Err(StartCaptureError::Rejected( + "this desktop's portal cannot create a virtual screen (no VIRTUAL type in \ + AvailableSourceTypes): share an existing screen" .into(), )); } - if fenetre && !portail.is_some_and(PortalInfo::supporte_fenetre) { - return Err(CaptureLanceeError::Refus( - "le portail de ce bureau ne sait partager qu'un écran entier (type WINDOW absent \ - de AvailableSourceTypes)" + if window && !portal.is_some_and(PortalInfo::supports_window) { + return Err(StartCaptureError::Rejected( + "this desktop's portal can only share an entire screen (no WINDOW type in \ + AvailableSourceTypes)" .into(), )); } - let type_source = if virtuel { - TypeSource::Virtuel - } else if fenetre { - TypeSource::Fenetre + let source_type = if virtual_display { + SourceType::Virtual + } else if window { + SourceType::Window } else { - TypeSource::Moniteur + SourceType::Monitor }; - let session = rs_platform::Session::ouvrir().await?; - // Abonné avant `demarrer`: un signal de fermeture émis entre les deux - // serait perdu. - let fermeture = session.surveiller_fermeture().await?; - let restauration = fichier_restauration(); - let jeton = match (&restauration, type_source) { - (Some(fichier), TypeSource::Moniteur) => std::fs::read_to_string(fichier) - .ok() - .map(|j| j.trim().to_string()), + let session = rs_platform::Session::open().await?; + // Subscribed before `start`: a close signal emitted in between would be + // lost. + let closed = session.watch_closed().await?; + let dir = state_dir(); + let token = match (&dir, source_type) { + (Some(dir), SourceType::Monitor) => read_restore_token(dir), _ => None, }; - session.choisir(type_source, jeton.as_deref()).await?; - let flux = session.demarrer().await?; - if let (Some(fichier), Some(nouveau)) = (&restauration, &flux.jeton_restauration) { - // Un échec ici coûte seulement une question au prochain lancement. - let _ = std::fs::create_dir_all(fichier.parent().unwrap_or(std::path::Path::new("."))); - if let Err(erreur) = std::fs::write(fichier, nouveau) { - tracing::warn!(%erreur, "jeton de restauration non enregistré"); + session.select_source(source_type, token.as_deref()).await?; + let stream = session.start().await?; + if let (Some(dir), Some(new_token)) = (&dir, &stream.restore_token) { + // A failure here only costs one question at the next launch. + let _ = std::fs::create_dir_all(dir); + if let Err(error) = std::fs::write(dir.join(RESTORE_TOKEN_FILE), new_token) { + tracing::warn!(%error, "restore token not saved"); } } tracing::info!( - evenement = "portail_accorde", - noeud = flux.node_id, - taille = ?flux.taille, - virtuel, - fenetre, - restaure = jeton.is_some(), - "le bureau a accordé la capture" + event = "portal_granted", + node = stream.node_id, + size = ?stream.size, + virtual_display, + window, + restored = token.is_some(), + "the desktop granted the capture" ); let pw_options = PipeWireOptions { fps: settings.max_fps, - size: virtuel.then(|| taille.unwrap_or(TAILLE_VIRTUELLE)), + size: virtual_display.then(|| size.unwrap_or(DEFAULT_VIRTUAL_SIZE)), }; - // Connexion et attente du format bloquent: hors du runtime. - let (mut capturer, taille) = tokio::task::spawn_blocking(move || { - let mut capturer = PipeWireCapturer::connecter(flux.fd, flux.node_id, pw_options)?; - let taille = capturer.attendre_format(Duration::from_secs(10))?; - Ok::<_, rs_capture::CaptureError>((capturer, taille)) + // Connecting and waiting for the format block: outside the runtime. + let (mut capturer, size) = tokio::task::spawn_blocking(move || { + let mut capturer = PipeWireCapturer::connect(stream.fd, stream.node_id, pw_options)?; + let size = capturer.wait_for_format(Duration::from_secs(10))?; + Ok::<_, rs_capture::CaptureError>((capturer, size)) }) .await - .map_err(|e| CaptureLanceeError::Refus(e.to_string()))??; + .map_err(|e| StartCaptureError::Rejected(e.to_string()))??; let revocation = capturer.revocation(); tokio::spawn(async move { - fermeture.attendre().await; + closed.wait().await; tracing::warn!( - evenement = "portail_ferme", - "le bureau a fermé la session de capture" + event = "portal_closed", + "the desktop closed the capture session" ); - revocation.revoquer(rs_capture::CaptureError::SourceGone); + revocation.revoke(rs_capture::CaptureError::SourceGone); }); let id = SourceId( @@ -347,33 +360,33 @@ async fn portail_pipewire( .map(|s| s.id.0.clone()) .unwrap_or_default(), ); - let source = SourcePartagee { - genre: if fenetre { + let source = SharedSource { + kind: if window { SourceKind::Window } else { SourceKind::Screen }, - // Le portail ne nomme pas la source: c'est l'utilisateur qui l'a - // choisie, et un titre de fenêtre ne doit pas être deviné. - nom: if virtuel { - "Écran virtuel".into() - } else if fenetre { - "Fenêtre choisie dans le bureau".into() + // The portal does not name the source: the user chose it, and a + // window title must not be guessed. + name: if virtual_display { + "Virtual screen".into() + } else if window { + "Window chosen in the desktop".into() } else { - "Écran choisi dans le bureau".into() + "Screen chosen in the desktop".into() }, - libelle: if virtuel { - Libelle::EcranVirtuel - } else if fenetre { - Libelle::FenetreChoisie + label: if virtual_display { + Label::VirtualScreen + } else if window { + Label::ChosenWindow } else { - Libelle::EcranChoisi + Label::ChosenScreen }, - chemin: "portail".into(), - largeur: taille.0, - hauteur: taille.1, + backend: "portal".into(), + width: size.0, + height: size.1, }; - let mut lancee = demarrer(capturer, taille, settings, codec, &id, source)?; - lancee.portail = Some(session); - Ok(lancee) + let mut started = spawn_live(capturer, size, settings, codec, &id, source)?; + started.portal = Some(session); + Ok(started) } diff --git a/crates/rs-session/src/diagnostics.rs b/crates/rs-session/src/diagnostics.rs index 67d3574..147dfe2 100644 --- a/crates/rs-session/src/diagnostics.rs +++ b/crates/rs-session/src/diagnostics.rs @@ -1,7 +1,6 @@ -//! Ce que l'hôte sait de lui-même, pour l'archive de diagnostics (ADR 0008). +//! What the host knows about itself, for the diagnostics archive (ADR 0008). //! -//! Uniquement des faits techniques: aucun titre de fenêtre, aucun nom de -//! source choisie. +//! Technical facts only: no window title, no name of the chosen source. use std::path::PathBuf; @@ -9,53 +8,53 @@ use rs_codec::{EncodeConfig, VpxEncoder}; use rs_platform::{Environment, PortalInfo}; #[derive(Clone)] -pub struct Contexte { +pub struct DiagnosticsContext { pub version: String, - pub environnement: Environment, - pub portail: Option, - /// Chemin de capture du partage en cours (`portail`, `x11`...). + pub environment: Environment, + pub portal: Option, + /// Capture backend of the current share (`portal`, `x11`...). pub capture: Option, - pub virtuel: bool, - pub encodage: Option, - pub journaux: Option, + pub virtual_display: bool, + pub encode: Option, + pub log_dir: Option, } -impl Contexte { - pub fn rapport(&self) -> rs_diag::Rapport { - let mut rapport = rs_diag::Rapport::nouveau(&self.version); - rapport.section( - "session_graphique", +impl DiagnosticsContext { + pub fn report(&self) -> rs_diag::Report { + let mut report = rs_diag::Report::new(&self.version); + report.section( + "graphical_session", serde_json::json!({ - "type": format!("{:?}", self.environnement.session), - "bureau": format!("{:?}", self.environnement.desktop), - "xdg_current_desktop": self.environnement.desktop_raw, - "ecran_virtuel": format!( + "type": format!("{:?}", self.environment.session), + "desktop": format!("{:?}", self.environment.desktop), + "xdg_current_desktop": self.environment.desktop_raw, + "virtual_display": format!( "{:?}", - self.environnement.virtual_display_backend(self.portail.as_ref()) + self.environment.virtual_display_backend(self.portal.as_ref()) ), }), ); - rapport.section( - "portail", - self.portail.map(|p| { + report.section( + "portal", + self.portal.map(|p| { serde_json::json!({ "version": p.version, - "types_de_sources": p.types, - "ecran_virtuel": p.supporte_ecran_virtuel(), + "source_types": p.types, + "virtual_display": p.supports_virtual_display(), }) }), ); - rapport.section( + report.section( "capture", serde_json::json!({ - "chemin": self.capture, - "virtuel": self.virtuel, - "pipewire_compile": cfg!(feature = "pipewire"), - "x11_compile": cfg!(target_os = "linux"), + "backend": self.capture, + "virtual_display": self.virtual_display, + "pipewire_built": cfg!(feature = "pipewire"), + "x11_built": cfg!(target_os = "linux"), }), ); - rapport.section( - "encodage", + report.section( + "encoding", serde_json::json!({ "vp8": VpxEncoder::new(EncodeConfig { width: 64, @@ -65,27 +64,27 @@ impl Contexte { codec: rs_codec::VideoCodec::Vp8, }) .is_ok(), - "vp9_expose": false, - "materiel": false, - "configuration": self.encodage.map(|c| serde_json::json!({ - "largeur": c.width, - "hauteur": c.height, + "vp9_exposed": false, + "hardware": false, + "config": self.encode.map(|c| serde_json::json!({ + "width": c.width, + "height": c.height, "fps": c.fps, - "debit_kbps": c.bitrate_kbps, + "bitrate_kbps": c.bitrate_kbps, "codec": c.codec.as_str(), })), }), ); - rapport + report } - /// L'archive zip et son nom daté. + /// The zip archive and its dated name. pub fn archive(&self) -> Result<(String, Vec), String> { - let nom = rs_diag::nom_archive(std::time::SystemTime::now()); - let octets = self - .rapport() - .archive(self.journaux.as_deref()) + let name = rs_diag::archive_name(std::time::SystemTime::now()); + let bytes = self + .report() + .archive(self.log_dir.as_deref()) .map_err(|e| e.to_string())?; - Ok((nom, octets)) + Ok((name, bytes)) } } diff --git a/crates/rs-session/src/etat.rs b/crates/rs-session/src/etat.rs deleted file mode 100644 index 1763fc6..0000000 --- a/crates/rs-session/src/etat.rs +++ /dev/null @@ -1,265 +0,0 @@ -//! Ce que l'interface de l'hôte affiche, en un seul objet. -//! -//! L'interface ne déduit rien: elle reçoit l'[`Etat`] complet à chaque -//! changement et l'affiche. C'est ce qui tient le critère de #15, « pas de -//! bouton qui ment »: un bouton n'a pas d'état à lui, il lit celui-ci. -//! -//! Les types sont exportés en TypeScript (`apps/desktop/src/bindings`), jamais -//! réécrits à la main (AGENTS.md). - -use rs_proto::SourceKind; -use serde::{Deserialize, Serialize}; -use ts_rs::TS; - -/// Où en est le partage. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)] -#[serde(rename_all = "snake_case")] -#[ts(export, export_to = "../../../desktop/src/bindings/")] -pub enum Phase { - Arrete, - /// Capture en cours d'ouverture: le bureau peut demander l'autorisation. - Demarrage, - EnCours, -} - -/// Ce que l'utilisateur choisit de partager. L'interface renvoie tel quel le -/// `choix` d'une [`SourceProposee`]. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] -#[serde(tag = "type", rename_all = "snake_case")] -#[ts(export, export_to = "../../../desktop/src/bindings/")] -pub enum SourceChoisie { - /// Une mire générée, sans écran: pour essayer. - Synthetique { largeur: u32, hauteur: u32 }, - /// Un écran, un moniteur ou une fenêtre X11, par identifiant. - X11 { id: String }, - /// Le portail du bureau (Wayland). Le bureau affiche son propre sélecteur: - /// c'est lui qui dit quel écran, ou quelle fenêtre. - Portail { - virtuel: bool, - /// Une fenêtre plutôt qu'un écran (#17), si le portail le permet. - #[serde(default)] - fenetre: bool, - /// Taille d'un écran virtuel. Ignorée pour un écran existant. - taille: Option<(u32, u32)>, - }, - /// Un fichier VP8 rejoué, pour les mesures (ligne de commande seulement). - Mire { chemin: String }, -} - -/// 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. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] -#[serde(tag = "type", rename_all = "snake_case")] -#[ts(export, export_to = "../../../desktop/src/bindings/")] -pub enum Libelle { - /// Un titre de fenêtre, tel que l'application le donne. - Titre { - texte: String, - }, - /// Un moniteur, nommé par sa sortie (`HDMI-1`). - Moniteur { - sortie: String, - principal: bool, - }, - Ecran, - Fenetre, - EcranVirtuel, - Mire, - MireEnregistree, - TousLesEcrans, - EcranEntier, - EcranChoisi, - FenetreChoisie, -} - -/// Ce qu'il faut savoir d'une source avant de la choisir, traduit par -/// l'interface. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)] -#[serde(rename_all = "snake_case")] -#[ts(export, export_to = "../../../desktop/src/bindings/")] -pub enum NoteSource { - /// Le bureau demandera lequel, le choix est retenu. - PortailEcran, - /// Le bureau montre ses fenêtres; recouverte ou réduite, ce qui se passe. - PortailFenetre, - /// Le portail de ce bureau ne sait pas partager une fenêtre (#17). - PortailSansFenetre, - EcranVirtuel, - Mire, - /// Binaire compilé sans PipeWire: rien sous Wayland. - SansPipewire, - /// Fenêtre réduite: la restaurer d'abord. - Reduite, -} - -impl NoteSource { - /// Le texte pour la ligne de commande, qui ne parle que français. - /// L'interface, elle, traduit le code (`locales/*.json`, `desktop.notes`). - pub fn en_francais(self) -> &'static str { - match self { - Self::PortailEcran => { - "le bureau demande lequel partager; le choix est retenu pour la fois suivante" - } - Self::PortailFenetre => "le bureau affiche la liste des fenêtres", - Self::PortailSansFenetre => { - "ce bureau ne sait partager qu'un écran entier (portail sans capture de fenêtre)" - } - Self::EcranVirtuel => "un écran créé pour l'occasion", - Self::Mire => "une image générée, sans écran", - Self::SansPipewire => "binaire compilé sans PipeWire: capture Wayland indisponible", - Self::Reduite => "réduite: la restaurer pour la partager", - } - } -} - -/// Une source proposée dans la liste. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] -#[ts(export, export_to = "../../../desktop/src/bindings/")] -pub struct SourceProposee { - pub choix: SourceChoisie, - pub 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). - pub nom: String, - /// Le nom à afficher, que l'interface traduit. - pub libelle: Libelle, - pub largeur: u32, - pub hauteur: u32, - /// 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. - pub vignette: Option, - /// Ce qu'il faut savoir avant de choisir (« le bureau demandera lequel »). - pub note: Option, - /// 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). - pub disponible: bool, -} - -/// La source en cours de partage. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] -#[ts(export, export_to = "../../../desktop/src/bindings/")] -pub struct SourcePartagee { - pub genre: SourceKind, - pub nom: String, - pub libelle: Libelle, - /// `portail`, `x11`, `synthetique` ou `ivf`. - pub chemin: String, - /// Taille encodée courante: elle suit un changement de résolution. - pub largeur: u32, - pub hauteur: u32, -} - -/// Un spectateur connecté. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] -#[ts(export, export_to = "../../../desktop/src/bindings/")] -pub struct AppareilVu { - /// Numéro à renvoyer pour le déconnecter. - #[ts(type = "number")] - pub connexion: u64, - pub nom: String, - pub plateforme: Option, - pub adresse: String, - /// Arrivée, en millisecondes Unix. - #[ts(type = "number")] - pub depuis_ms: u64, -} - -/// Un partage en cours. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] -#[ts(export, export_to = "../../../desktop/src/bindings/")] -pub struct Partage { - pub source: SourcePartagee, - pub room: String, - /// L'URL à donner, jeton compris, sur l'adresse du LAN. - pub url: String, - /// Le QR code de `url`, en SVG. - pub qr_svg: String, - /// Code court à taper sans caméra, en minuscules: l'interface le groupe. - pub code: String, - /// Échéance du jeton et du code, en millisecondes Unix. `None`: sans - /// limite. - #[ts(type = "number | null")] - pub expire_ms: Option, - /// L'échéance est passée: plus aucun nouvel appareil n'entre tant que - /// l'hôte n'a pas tiré un nouveau code. - pub acces_expire: bool, - /// Empreinte SHA-256 du certificat, en HTTPS seulement. - pub empreinte: Option, - /// Adresse et port d'écoute réels (`0.0.0.0:8099`, `192.168.1.20:9000`). - pub ecoute: String, - /// Interface choisie, `None` si l'hôte écoute partout. - pub interface: Option, - pub appareils: Vec, - pub limite: u8, - #[ts(type = "number")] - pub demarre_ms: u64, -} - -/// Pourquoi le dernier partage s'est arrêté, quand ce n'est pas l'utilisateur. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] -#[ts(export, export_to = "../../../desktop/src/bindings/")] -pub struct Arret { - pub 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. - pub par_le_bureau: bool, -} - -/// Tout l'état de l'hôte. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] -#[ts(export, export_to = "../../../desktop/src/bindings/")] -pub struct Etat { - pub phase: Phase, - pub partage: Option, - /// Échec du dernier démarrage, à afficher tel quel. - pub erreur: Option, - pub arret: Option, - /// Ce qui marche encore mais mérite d'être su (interface coupée, adresse - /// changée). - pub avertissements: Vec, - /// Mécanismes d'inhibition de veille tenus (`login1`, `screensaver`): - /// vide hors partage, ou si aucun n'a pu être pris. - pub veille_inhibee: Vec, - /// Réglages modifiés pendant le partage, appliqués au prochain. - pub reglages_en_attente: Vec, - /// Le fichier de réglages était inutilisable au démarrage: ce qui a été fait. - pub reglages_recuperes: Option, - /// Capacités de cette machine, pour ne proposer que ce qui marche. - pub capacites: Capacites, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] -#[ts(export, export_to = "../../../desktop/src/bindings/")] -pub struct Capacites { - /// `wayland`, `x11` ou `aucune`. - pub session: String, - pub bureau: String, - pub portail: bool, - pub ecran_virtuel: bool, - /// Le binaire sait consommer un flux PipeWire (feature `pipewire`). - pub pipewire: bool, - /// Le démarrage automatique est réglable depuis cette application. - pub demarrage_auto: bool, -} - -/// Ce que produit une modification de réglages. -#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize, TS)] -#[ts(export, export_to = "../../../desktop/src/bindings/")] -pub struct Application { - /// Champs appliqués tout de suite. - pub immediats: Vec, - /// Champs qui attendent le prochain partage, avec la raison. - pub au_prochain_partage: Vec, -} - -/// Une interface réseau proposée dans les réglages. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] -#[ts(export, export_to = "../../../desktop/src/bindings/")] -pub struct InterfaceProposee { - pub nom: String, - pub adresses: Vec, - pub active: bool, -} diff --git a/crates/rs-session/src/host.rs b/crates/rs-session/src/host.rs new file mode 100644 index 0000000..dd685e5 --- /dev/null +++ b/crates/rs-session/src/host.rs @@ -0,0 +1,1081 @@ +//! The host: one share at a time, from its start to its stop. +//! +//! Everything the interface can ask goes through here, and everything it +//! displays comes out through a single channel, [`Host::subscribe`], which +//! yields the full [`HostState`] on every change. The command line and the +//! desktop shell use it the same way. +//! +//! A share is a room (fresh token every time), a capture, a server on the +//! chosen port and interface, and a sleep inhibition. A watch task follows it +//! for its whole life: capture ended by the desktop, network interface down or +//! readdressed, wake-up after sleep. + +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; +use std::path::PathBuf; +use std::sync::{Arc, Mutex, Weak}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use rs_codec::{LiveSource, SharedMedia}; +use rs_platform::{Environment, Inhibition, PortalInfo, SessionType}; +use rs_proto::StreamSettings; +use rs_signaling::{HostConfig, Room, ServerError, TlsMaterial}; +use rs_store::{Origin, Rejection, Settings, Store}; +use tokio::sync::{oneshot, watch}; +use tokio::task::JoinHandle; + +use crate::capture::{self, StartedCapture}; +use crate::diagnostics::DiagnosticsContext; +use crate::media::{Switchable, SwitchableMedia}; +use crate::state::{ + Capabilities, HostState, InterfaceOption, Phase, SettingsOutcome, Share, SharedSource, + SourceChoice, SourceOption, Stop, ViewerDevice, +}; + +/// Interval of a share's watch: capture end, network. +const WATCH_INTERVAL: Duration = Duration::from_secs(1); +/// Time left to the server to dismiss viewers on stop. +const SERVER_STOP_TIMEOUT: Duration = Duration::from_secs(3); +/// Prefix of the warning about a disconnected interface, cleared when it +/// comes back. +const INTERFACE_WARNING: &str = "The interface "; + +/// What the caller sets once and for all. +pub struct Config { + pub version: String, + pub viewer_dir: Option, + pub tls: bool, + /// The settings file. `None`: settings in memory only. + pub store: Option, + /// Command line values: they take precedence over the settings without + /// changing them. + pub overrides: Overrides, + pub log_dir: Option, + /// The executable that autostart launches, with its arguments. `None`: + /// the setting cannot be changed from this application. + pub autostart: Option<(PathBuf, String)>, +} + +#[derive(Debug, Default, Clone, Copy)] +pub struct Overrides { + pub port: Option, + pub limit: Option, + /// Video codec of this launch (`--codec`). `None`: the one in the settings. + pub codec: Option, +} + +/// Handle to the host, free to clone. +#[derive(Clone)] +pub struct Host(Arc); + +struct Inner { + config: Config, + environment: Environment, + portal: Option, + settings: Mutex, + state: watch::Sender, + /// What the state displays, outside the "in progress" part below. + base: Mutex, + /// What is needed to describe the current share, readable without waiting. + view: Mutex>, + /// The current share, which we start and stop: an async lock serializes + /// these operations. + active: tokio::sync::Mutex>, + /// Interrupts a start that is waiting for the desktop. + cancel: Mutex>>, + context: Mutex, + /// Last time the machine went to sleep or woke up: a capture that dies + /// right around it is restarted instead of stopping the share. + sleep: Mutex>, +} + +/// Window around a sleep during which a capture end is blamed on it. +const AFTER_SLEEP: Duration = Duration::from_secs(30); + +#[derive(Default)] +struct Base { + phase: Option, + error: Option, + stop: Option, + warnings: Vec, + sleep_inhibited: Vec, + pending_settings: Vec, + settings_recovered: Option, +} + +struct View { + room: Arc, + live: Option>, + source: SharedSource, + scheme: &'static str, + listen: SocketAddr, + interface: Option, + fingerprint: Option, + started_ms: u64, + /// Last rendered QR and the URL it carries: the state is recomposed every + /// second, the QR only when the URL changes. + qr: Option<(String, String)>, +} + +struct Server { + task: JoinHandle>, + stop: oneshot::Sender<()>, +} + +struct Active { + room: Arc, + media: Arc, + live: Option>, + portal: Option, + choice: SourceChoice, + settings: StreamSettings, + /// Kept to restart the capture after sleep: open sessions negotiated this + /// codec, switching would give them a black screen. + codec: rs_codec::VideoCodec, + server: Server, + tls: Option, + listen: SocketAddr, + inhibition: Option, + watch: JoinHandle<()>, +} + +impl Host { + /// Loads the settings, probes the portal, and waits for orders. No port is + /// opened until a share is started. + pub async fn new(config: Config) -> Self { + let environment = Environment::detect(); + let portal = if environment.session == SessionType::Wayland { + match rs_platform::portal::probe().await { + Ok(portal) => { + tracing::info!( + version = portal.version, + types = portal.types, + virtual_display = portal.supports_virtual_display(), + "screen recording portal available" + ); + Some(portal) + } + Err(error) => { + tracing::warn!(%error, "screen recording portal unavailable"); + None + } + } + } else { + None + }; + + let mut base = Base::default(); + let settings = match &config.store { + Some(store) => { + let (settings, origin) = store.load(); + if let Origin::Recovered { backup, reason } = origin { + base.settings_recovered = Some(match backup { + Some(path) => format!( + "Unreadable settings ({reason}): the old file is kept in {}, \ + safe values are restored.", + path.display() + ), + None => format!("Unreadable settings ({reason}): safe values restored."), + }); + } + settings + } + None => Settings::default(), + }; + + let context = DiagnosticsContext { + version: config.version.clone(), + environment: environment.clone(), + portal, + capture: None, + virtual_display: false, + encode: None, + log_dir: config.log_dir.clone(), + }; + let inner = Arc::new(Inner { + state: watch::Sender::new(empty_state(&environment, portal, &config)), + config, + environment, + portal, + settings: Mutex::new(settings), + base: Mutex::new(base), + view: Mutex::new(None), + active: tokio::sync::Mutex::new(None), + cancel: Mutex::new(None), + context: Mutex::new(context), + sleep: Mutex::new(None), + }); + let host = Self(inner); + host.repair_autostart(); + host.refresh(); + tokio::spawn(watch_sleep(Arc::downgrade(&host.0))); + host + } + + /// Rewrites the autostart file if it is enabled: an update may have moved + /// the executable (Nix path, new AppImage), and a file pointing to nothing + /// no longer launches anything (#32). + fn repair_autostart(&self) { + let Some((executable, arguments)) = &self.0.config.autostart else { + return; + }; + if !self.settings().autostart { + return; + } + let Some(dir) = rs_platform::autostart::directory() else { + return; + }; + if let Err(error) = rs_platform::autostart::set(&dir, true, executable, arguments) { + tracing::warn!(%error, "autostart not updated"); + } + } + + pub fn environment(&self) -> &Environment { + &self.0.environment + } + + pub fn portal(&self) -> Option<&PortalInfo> { + self.0.portal.as_ref() + } + + /// The current state. + pub fn state(&self) -> HostState { + self.0.state.borrow().clone() + } + + /// The state, on every change. + pub fn subscribe(&self) -> watch::Receiver { + self.0.state.subscribe() + } + + /// The sources of this machine, thumbnails included when possible. + pub async fn sources(&self) -> Vec { + let environment = self.0.environment.clone(); + let portal = self.0.portal; + tokio::task::spawn_blocking(move || crate::sources::list(&environment, portal.as_ref())) + .await + .unwrap_or_default() + } + + pub fn settings(&self) -> Settings { + lock(&self.0.settings).clone() + } + + pub fn interfaces(&self) -> Vec { + rs_platform::interfaces() + .into_iter() + .filter(|i| !i.loopback) + .map(|i| InterfaceOption { + name: i.name, + addresses: i.addresses.iter().map(IpAddr::to_string).collect(), + active: i.active, + }) + .collect() + } + + /// The diagnostics archive, name and content. + pub fn diagnostics(&self) -> Result<(String, Vec), String> { + lock(&self.0.context).archive() + } + + pub fn context(&self) -> DiagnosticsContext { + lock(&self.0.context).clone() + } + + /// Starts a share. Returns the error to display, as is. + pub async fn start(&self, choice: SourceChoice) -> Result<(), String> { + let mut active = self.0.active.lock().await; + if active.is_some() { + return Err("a share is already running: stop it first".into()); + } + let (cancel, cancelled) = oneshot::channel(); + *lock(&self.0.cancel) = Some(cancel); + self.update_base(|b| { + b.phase = Some(Phase::Starting); + b.error = None; + b.stop = None; + b.warnings.clear(); + b.pending_settings.clear(); + }); + + let result = tokio::select! { + result = self.open(choice) => result, + _ = cancelled => Err("start cancelled".to_string()), + }; + lock(&self.0.cancel).take(); + + match result { + Ok(opened) => { + *active = Some(opened); + self.update_base(|b| b.phase = Some(Phase::Live)); + Ok(()) + } + Err(error) => { + tracing::warn!(event = "share_refused", %error, "share not started"); + self.update_base(|b| { + b.phase = Some(Phase::Stopped); + b.error = Some(error.clone()); + }); + Err(error) + } + } + } + + /// Stops the share, or interrupts a start in progress. + pub async fn stop(&self) { + if let Some(cancel) = lock(&self.0.cancel).take() { + let _ = cancel.send(()); + } + self.stop_with(None).await; + } + + /// Disconnects a viewer. It does not come back with this token. + pub fn disconnect(&self, connection: u64) -> bool { + let room = lock(&self.0.view).as_ref().map(|v| v.room.clone()); + let done = room.is_some_and(|room| room.kick(connection)); + if done { + tracing::info!(event = "viewer_disconnected", "disconnected by the host"); + } + done + } + + /// Draws a new QR code and a new short code (#19). Viewers already there + /// stay, and a device already admitted comes back with the old one; the + /// others need the new one. + pub fn regenerate_access(&self) -> bool { + let room = lock(&self.0.view).as_ref().map(|v| v.room.clone()); + let Some(room) = room else { + return false; + }; + room.regenerate(validity(self.settings().code_validity_min)); + tracing::info!(event = "access_regenerated", "new access code"); + self.refresh(); + true + } + + /// Validates, saves and applies. Returns what applies right away and what + /// waits for the next share, so the interface can say so. + pub async fn update_settings(&self, new: Settings) -> Result> { + let mut rejections = new.validate(); + let old = self.settings(); + if new.autostart != old.autostart && self.0.config.autostart.is_none() { + rejections.push(Rejection { + field: "autostart".into(), + message: "can only be set from the desktop application".into(), + }); + } + if !rejections.is_empty() { + return Err(rejections); + } + if let Some((executable, arguments)) = &self.0.config.autostart + && new.autostart != old.autostart + { + let result = rs_platform::autostart::directory() + .ok_or_else(|| "configuration directory not found".to_string()) + .and_then(|dir| { + rs_platform::autostart::set(&dir, new.autostart, executable, arguments) + .map_err(|e| e.to_string()) + }); + if let Err(message) = result { + return Err(vec![Rejection { + field: "autostart".into(), + message, + }]); + } + } + if let Some(store) = &self.0.config.store + && let Err(error) = store.save(&new) + { + return Err(match error { + rs_store::StoreError::Rejected(rejections) => rejections, + other => vec![Rejection { + field: "file".into(), + message: other.to_string(), + }], + }); + } + *lock(&self.0.settings) = new.clone(); + + let room = lock(&self.0.view).as_ref().map(|v| v.room.clone()); + let mut outcome = SettingsOutcome::default(); + let mut change = |field: &str, changed: bool, waits: Option<&str>| { + if !changed { + return; + } + match (waits, &room) { + (Some(reason), Some(_)) => outcome.next_share.push(format!("{field}: {reason}")), + _ => outcome.immediate.push(field.to_string()), + } + }; + let overrides = self.0.config.overrides; + change( + "port", + new.port != old.port, + Some("changing the port would cut viewers off"), + ); + change( + "interface", + new.interface != old.interface, + Some("changing the interface would cut viewers off"), + ); + change( + "codec", + new.codec != old.codec, + Some("connected viewers negotiated the codec of the current share"), + ); + change( + "quality", + new.quality != old.quality, + Some("the encoder keeps the quality of the current share"), + ); + change( + "code_validity_min", + new.code_validity_min != old.code_validity_min, + Some("the displayed code keeps its expiry, the next one takes the new duration"), + ); + change("limit", new.limit != old.limit, None); + change("theme", new.theme != old.theme, None); + change("close_action", new.close_action != old.close_action, None); + change("confirm_quit", new.confirm_quit != old.confirm_quit, None); + change("language", new.language != old.language, None); + change("autostart", new.autostart != old.autostart, None); + if new.limit != old.limit + && overrides.limit.is_none() + && let Some(room) = &room + { + room.set_limit(new.limit); + } + tracing::info!( + event = "settings_changed", + immediate = ?outcome.immediate, + pending = ?outcome.next_share, + "settings saved" + ); + let pending = outcome.next_share.clone(); + self.update_base(|b| { + for field in pending { + if !b.pending_settings.contains(&field) { + b.pending_settings.push(field); + } + } + }); + Ok(outcome) + } + + /// Waits for the current share to end, and says why it stopped. + pub async fn ended(&self) -> Option { + let mut receiver = self.subscribe(); + let state = receiver + .wait_for(|s| s.phase == Phase::Stopped) + .await + .ok()? + .clone(); + state.stop + } + + // -- Start and stop --------------------------------------------------------- + + async fn open(&self, choice: SourceChoice) -> Result { + let settings = self.settings(); + let overrides = self.0.config.overrides; + let stream_settings = StreamSettings::for_preset(settings.quality); + let codec = overrides.codec.unwrap_or(match settings.codec { + rs_store::Codec::Vp8 => rs_codec::VideoCodec::Vp8, + rs_store::Codec::Vp9 => rs_codec::VideoCodec::Vp9, + }); + let limit = overrides.limit.unwrap_or(settings.limit); + let port = overrides.port.unwrap_or(settings.port); + + // The port first: a busy port must be reported before the desktop asks + // for permission to share the screen. + let ip = listen_address(settings.interface.as_deref())?; + let listener = + rs_signaling::bind_listener(SocketAddr::new(ip, port)).map_err(|e| e.to_string())?; + let listen = listener.local_addr().map_err(|e| e.to_string())?; + + let started = capture::start(&choice, &stream_settings, codec, self.0.portal.as_ref()) + .await + .map_err(|e| e.to_string())?; + let StartedCapture { + media, + live, + portal, + source, + encode, + } = started; + let media = SwitchableMedia::new(media); + + let tls = if self.0.config.tls { + let dir = std::env::var("XDG_DATA_HOME") + .map(PathBuf::from) + .unwrap_or_else(|_| PathBuf::from(".rustscreen")); + let names = vec![ + "localhost".to_string(), + "rustscreen.local".to_string(), + "127.0.0.1".to_string(), + ]; + let material = TlsMaterial::load_or_create(&dir, &names).map_err(|e| e.to_string())?; + tracing::info!(fingerprint = %material.fingerprint_pairs(), "certificate ready"); + Some(material) + } else { + None + }; + + let room = Arc::new( + Room::new(None, stream_settings, limit) + .with_validity(validity(settings.code_validity_min)), + ); + let server = self.spawn_server(listener, tls.clone(), room.clone(), media.clone()); + + let inhibition = match Inhibition::acquire("screen sharing in progress").await { + Ok(inhibition) => Some(inhibition), + Err(error) => { + tracing::warn!(%error, "sleep not inhibited"); + None + } + }; + let sleep_inhibited: Vec = inhibition + .as_ref() + .map(|i| i.active().iter().map(|m| m.to_string()).collect()) + .unwrap_or_default(); + + { + let mut context = lock(&self.0.context); + context.capture = Some(source.backend.clone()); + context.virtual_display = matches!( + choice, + SourceChoice::Portal { + virtual_display: true, + .. + } + ); + context.encode = encode; + } + let started_ms = now_ms(); + *lock(&self.0.view) = Some(View { + room: room.clone(), + live: live.clone(), + source, + scheme: if tls.is_some() { "https" } else { "http" }, + listen, + interface: settings.interface.clone(), + fingerprint: tls.as_ref().map(TlsMaterial::fingerprint_pairs), + started_ms, + qr: None, + }); + self.update_base(|b| b.sleep_inhibited = sleep_inhibited); + + tracing::info!( + event = "share_started", + listen = %listen, + interface = settings.interface.is_some(), + limit, + "share started" + ); + let watch = tokio::spawn(watch_share(Arc::downgrade(&self.0), room.subscribe())); + Ok(Active { + room, + media, + live, + portal, + choice, + settings: stream_settings, + codec, + server, + tls, + listen, + inhibition, + watch, + }) + } + + fn spawn_server( + &self, + listener: std::net::TcpListener, + tls: Option, + room: Arc, + media: Arc, + ) -> Server { + let (stop, signal) = oneshot::channel::<()>(); + let weak = Arc::downgrade(&self.0); + let factory: rs_signaling::Diagnostics = Arc::new(move || { + let inner = weak.upgrade().ok_or_else(|| "host stopped".to_string())?; + let context = lock(&inner.context).clone(); + context.archive() + }); + let limit = room.limit(); + let task = tokio::spawn(rs_signaling::serve_listener( + listener, + HostConfig { + bind: SocketAddr::new(Ipv4Addr::UNSPECIFIED.into(), 0), + tls, + viewer_dir: self.0.config.viewer_dir.clone(), + limit, + diagnostics: Some(factory), + }, + room, + Arc::new(Switchable(media)), + async move { + let _ = signal.await; + }, + )); + Server { task, stop } + } + + async fn stop_with(&self, stop: Option) { + let mut active = self.0.active.lock().await; + let Some(opened) = active.take() else { + return; + }; + close(opened).await; + *lock(&self.0.view) = None; + if let Some(stop) = &stop { + tracing::warn!( + event = "share_interrupted", + reason = %stop.reason, + by_desktop = stop.by_desktop, + "share stopped" + ); + } else { + tracing::info!(event = "share_ended", "share stopped by the user"); + } + self.update_base(|b| { + b.phase = Some(Phase::Stopped); + b.stop = stop; + b.sleep_inhibited.clear(); + b.pending_settings.clear(); + b.warnings.clear(); + }); + } + + /// Changes the listen address of a running share: same room, same + /// capture, new server. Viewers must scan again, the old address no longer + /// existing. + async fn readdress(&self, new: IpAddr) { + let mut active = self.0.active.lock().await; + let Some(opened) = active.as_mut() else { + return; + }; + let old = opened.listen; + let listener = match rs_signaling::bind_listener(SocketAddr::new(new, old.port())) { + Ok(listener) => listener, + Err(error) => { + self.warn(format!("New address {new} unusable: {error}")); + return; + } + }; + let Ok(listen) = listener.local_addr() else { + return; + }; + let server = self.spawn_server( + listener, + opened.tls.clone(), + opened.room.clone(), + opened.media.clone(), + ); + let old_server = std::mem::replace(&mut opened.server, server); + opened.listen = listen; + drop(active); + stop_server(old_server).await; + if let Some(view) = lock(&self.0.view).as_mut() { + view.listen = listen; + } + tracing::warn!( + event = "address_changed", + before = %old.ip(), + after = %new, + "server restarted on the new address" + ); + self.update_base(|b| { + b.warnings.retain(|w| !w.starts_with(INTERFACE_WARNING)); + b.warnings.push(format!( + "Address changed ({} became {new}): have viewers scan the new QR code.", + old.ip() + )); + }); + } + + /// Restarts the capture of a share whose source stopped during sleep, + /// without changing room: viewers resume on their own. + async fn restart_capture(&self) -> Result<(), String> { + let mut active = self.0.active.lock().await; + let Some(opened) = active.as_mut() else { + return Ok(()); + }; + let started = capture::start( + &opened.choice, + &opened.settings, + opened.codec, + self.0.portal.as_ref(), + ) + .await + .map_err(|e| e.to_string())?; + let old_media = opened.media.replace(started.media); + let old_live = std::mem::replace(&mut opened.live, started.live.clone()); + let old_portal = std::mem::replace(&mut opened.portal, started.portal); + if let Some(view) = lock(&self.0.view).as_mut() { + view.live = started.live; + } + drop(active); + if let Some(session) = old_portal { + session.close().await; + } + // Stopping a capture joins its thread: outside the runtime. + let _ = tokio::task::spawn_blocking(move || drop((old_media, old_live))).await; + tracing::info!( + event = "capture_restarted", + "capture restarted after wake-up" + ); + Ok(()) + } + + // -- State ------------------------------------------------------------------ + + fn note_sleep(&self) { + *lock(&self.0.sleep) = Some(std::time::Instant::now()); + } + + fn recent_sleep(&self) -> bool { + lock(&self.0.sleep).is_some_and(|when| when.elapsed() < AFTER_SLEEP) + } + + fn update_base(&self, f: impl FnOnce(&mut Base)) { + f(&mut lock(&self.0.base)); + self.refresh(); + } + + fn warn(&self, message: String) { + self.update_base(|b| { + if !b.warnings.contains(&message) { + b.warnings.push(message); + } + }); + } + + /// Recomposes the state and only notifies if it changed. + fn refresh(&self) { + let inner = &self.0; + let state = { + let base = lock(&inner.base); + let mut view = lock(&inner.view); + HostState { + phase: base.phase.unwrap_or(Phase::Stopped), + share: view.as_mut().map(describe), + error: base.error.clone(), + stop: base.stop.clone(), + warnings: base.warnings.clone(), + sleep_inhibited: base.sleep_inhibited.clone(), + pending_settings: base.pending_settings.clone(), + settings_recovered: base.settings_recovered.clone(), + capabilities: capabilities(&inner.environment, inner.portal, &inner.config), + } + }; + inner.state.send_if_modified(|current| { + if *current == state { + false + } else { + *current = state; + true + } + }); + } +} + +fn describe(view: &mut View) -> Share { + let advertised = (!view.listen.ip().is_unspecified()).then_some(view.listen.ip()); + let url = rs_signaling::session_url( + view.scheme, + advertised, + view.listen.port(), + &view.room, + view.fingerprint.as_deref(), + ); + let qr_svg = match &view.qr { + Some((carried, svg)) if *carried == url => svg.clone(), + _ => { + let svg = rs_signaling::qr::encode(&url) + .map(|matrix| rs_signaling::qr::render_svg(&matrix, 8)) + .unwrap_or_default(); + view.qr = Some((url.clone(), svg.clone())); + svg + } + }; + let mut source = view.source.clone(); + if let Some(live) = &view.live { + let stats = live.stats(); + source.width = stats.width; + source.height = stats.height; + } + Share { + source, + room: view.room.id.to_string(), + url, + qr_svg, + code: view.room.code(), + expires_ms: view.room.expires_ms(), + access_expired: view.room.access_expired(), + fingerprint: view.fingerprint.clone(), + listen: view.listen.to_string(), + interface: view.interface.clone(), + devices: view + .room + .devices() + .into_iter() + .map(|d| ViewerDevice { + connection: d.connection, + name: d.name, + platform: d.platform, + address: d.address.to_string(), + since_ms: d.since_ms, + }) + .collect(), + limit: view.room.limit(), + started_ms: view.started_ms, + } +} + +fn capabilities( + environment: &Environment, + portal: Option, + config: &Config, +) -> Capabilities { + Capabilities { + session: match environment.session { + SessionType::Wayland => "wayland", + SessionType::X11 => "x11", + SessionType::Headless => "none", + } + .into(), + desktop: format!("{:?}", environment.desktop), + portal: portal.is_some(), + virtual_display: portal.is_some_and(|p| p.supports_virtual_display()), + pipewire: cfg!(feature = "pipewire"), + autostart: config.autostart.is_some(), + } +} + +fn empty_state( + environment: &Environment, + portal: Option, + config: &Config, +) -> HostState { + HostState { + phase: Phase::Stopped, + share: None, + error: None, + stop: None, + warnings: Vec::new(), + sleep_inhibited: Vec::new(), + pending_settings: Vec::new(), + settings_recovered: None, + capabilities: capabilities(environment, portal, config), + } +} + +/// The listen address: the one of the chosen interface, or all of them. +fn listen_address(interface: Option<&str>) -> Result { + let Some(name) = interface else { + return Ok(Ipv4Addr::UNSPECIFIED.into()); + }; + let found = rs_platform::network::interface(name).ok_or_else(|| { + format!( + "the interface {name} has no address: plug it in, or choose \"all interfaces\" \ + in the settings" + ) + })?; + found + .primary_address() + .ok_or_else(|| format!("the interface {name} has no address reachable by another device")) +} + +async fn close(opened: Active) { + let Active { + room, + media, + live, + portal, + server, + inhibition, + watch, + .. + } = opened; + watch.abort(); + stop_server(server).await; + drop(room); + if let Some(session) = portal { + session.close().await; + } + if let Some(inhibition) = inhibition { + inhibition.release().await; + } + // Stopping the capture joins its encoding thread: outside the runtime. + let _ = tokio::task::spawn_blocking(move || drop((media, live))).await; +} + +async fn stop_server(server: Server) { + let Server { mut task, stop } = server; + let _ = stop.send(()); + match tokio::time::timeout(SERVER_STOP_TIMEOUT, &mut task).await { + Ok(Ok(Err(error))) => tracing::warn!(%error, "server stopped on an error"), + Ok(_) => {} + Err(_) => { + tracing::warn!("server too slow to stop: aborted"); + task.abort(); + } + } +} + +/// Follows a share: arrivals and departures, capture end, network. +async fn watch_share(weak: Weak, mut changes: watch::Receiver) { + let mut interval = tokio::time::interval(WATCH_INTERVAL); + let mut default_address = rs_rtc::local_candidate_address(); + // The monotonic clock stops during sleep, the wall clock does not: a large + // gap between two rounds says the machine slept, even without logind. + let mut last_round = SystemTime::now(); + loop { + tokio::select! { + result = changes.changed() => { + if result.is_err() { + return; + } + } + _ = interval.tick() => {} + } + let Some(inner) = weak.upgrade() else { + return; + }; + let host = Host(inner); + let gap = SystemTime::now() + .duration_since(last_round) + .unwrap_or_default(); + last_round = SystemTime::now(); + if gap > WATCH_INTERVAL * 10 { + tracing::info!( + event = "wake_detected", + seconds = gap.as_secs(), + "the machine slept" + ); + host.note_sleep(); + } + host.refresh(); + + let (ended, interface, listen) = { + let view = lock(&host.0.view); + let Some(view) = view.as_ref() else { + return; + }; + ( + view.live.as_ref().and_then(|l| l.ended()), + view.interface.clone(), + view.listen, + ) + }; + + if let Some(cause) = ended { + if host.recent_sleep() { + // The compositor may have closed the stream during sleep: we + // reopen the same source, in the same room. Viewers resume on + // their own (ADR 0007). + match host.restart_capture().await { + Ok(()) => continue, + Err(error) => { + tokio::spawn(async move { + host.stop_with(Some(Stop { + reason: format!( + "capture could not be restarted after sleep: {error}" + ), + by_desktop: false, + })) + .await; + }); + return; + } + } + } + // Stopping aborts this task: it runs in its own. + tokio::spawn(async move { + host.stop_with(Some(Stop { + reason: format!("capture ended: {cause}"), + by_desktop: true, + })) + .await; + }); + return; + } + + match interface { + Some(name) => match rs_platform::network::interface(&name) { + Some(found) if found.active => { + host.update_base(|b| b.warnings.retain(|w| !w.starts_with(INTERFACE_WARNING))); + if let Some(new) = found.primary_address() + && new != listen.ip() + { + let host = host.clone(); + tokio::spawn(async move { host.readdress(new).await }); + } + } + _ => host.warn(format!( + "{INTERFACE_WARNING}{name} is disconnected: viewers can no longer reach \ + the host." + )), + }, + None => { + let current = rs_rtc::local_candidate_address(); + if current != default_address { + tracing::warn!( + event = "address_changed", + before = ?default_address, + after = ?current, + "network address changed" + ); + if let (Some(_), Some(after)) = (default_address, current) { + host.warn(format!( + "Network address changed ({after}): have viewers scan the new QR code." + )); + } + default_address = current; + } + } + } + } +} + +/// Sleep as seen by logind (#42). It only timestamps the event: the share's +/// watch decides whether to restart a capture that died around it. +async fn watch_sleep(weak: Weak) { + let mut wake = match rs_platform::watch_wake().await { + Ok(wake) => wake, + Err(error) => { + tracing::warn!(%error, "wake-up not watched: no logind"); + return; + } + }; + while wake.next_event().await.is_some() { + // Going to sleep as well as waking up: the capture can die on either + // side. + let Some(inner) = weak.upgrade() else { + return; + }; + let host = Host(inner); + host.note_sleep(); + if let Some(active) = host.0.active.lock().await.as_ref() { + // Viewers come back through a fresh session: a keyframe saves them + // waiting for the next one. + Switchable(active.media.clone()).request_keyframe(); + } + } +} + +/// How long an access stays valid, `None` for no limit. +fn validity(minutes: u32) -> Option { + (minutes > 0).then(|| Duration::from_secs(u64::from(minutes) * 60)) +} + +fn now_ms() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_millis() as u64) +} + +fn lock(mutex: &Mutex) -> std::sync::MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(|e| e.into_inner()) +} diff --git a/crates/rs-session/src/hote.rs b/crates/rs-session/src/hote.rs deleted file mode 100644 index b127ec4..0000000 --- a/crates/rs-session/src/hote.rs +++ /dev/null @@ -1,1071 +0,0 @@ -//! L'hôte: un partage à la fois, de son démarrage à son arrêt. -//! -//! Tout ce que l'interface peut demander passe ici, et tout ce qu'elle affiche -//! en sort par un seul canal, [`Hote::abonner`], qui rend l'[`Etat`] complet à -//! chaque changement. La ligne de commande et la coque desktop s'en servent de -//! la même façon. -//! -//! Un partage, c'est une room (jeton neuf à chaque fois), une capture, un -//! serveur sur le port et l'interface choisis, et une inhibition de veille. -//! Une tâche de surveillance le suit pendant toute sa vie: fin de capture -//! décidée par le bureau, interface réseau coupée ou readressée, réveil après -//! une veille. - -use std::net::{IpAddr, Ipv4Addr, SocketAddr}; -use std::path::PathBuf; -use std::sync::{Arc, Mutex, Weak}; -use std::time::{Duration, SystemTime, UNIX_EPOCH}; - -use rs_codec::{LiveSource, SharedMedia}; -use rs_platform::{Environment, Inhibition, PortalInfo, SessionType}; -use rs_proto::StreamSettings; -use rs_signaling::{HostConfig, Room, ServerError, TlsMaterial}; -use rs_store::{Magasin, Origine, Refus, Reglages}; -use tokio::sync::{oneshot, watch}; -use tokio::task::JoinHandle; - -use crate::capture::{self, CaptureLancee}; -use crate::diagnostics::Contexte; -use crate::etat::{ - AppareilVu, Application, Arret, Capacites, Etat, InterfaceProposee, Partage, Phase, - SourceChoisie, SourcePartagee, SourceProposee, -}; -use crate::media::{Commutable, MediaCommutable}; - -/// Intervalle de la surveillance d'un partage: fin de capture, réseau. -const SURVEILLANCE: Duration = Duration::from_secs(1); -/// Délai laissé au serveur pour congédier les spectateurs à l'arrêt. -const ARRET_SERVEUR: Duration = Duration::from_secs(3); - -/// Ce que l'appelant fixe une fois pour toutes. -pub struct Config { - pub version: String, - pub viewer_dir: Option, - pub tls: bool, - /// Le fichier de réglages. `None`: réglages en mémoire seulement. - pub magasin: Option, - /// Valeurs de la ligne de commande: elles priment sur les réglages sans - /// les modifier. - pub surcharges: Surcharges, - pub journaux: Option, - /// L'exécutable que le démarrage automatique lance, avec ses arguments. - /// `None`: le réglage n'est pas modifiable depuis cette application. - pub demarrage_auto: Option<(PathBuf, String)>, -} - -#[derive(Debug, Default, Clone, Copy)] -pub struct Surcharges { - pub port: Option, - pub limite: Option, - /// Codec vidéo de ce lancement (`--codec`). `None`: celui des réglages. - pub codec: Option, -} - -/// Poignée vers l'hôte, à cloner librement. -#[derive(Clone)] -pub struct Hote(Arc); - -struct Interne { - config: Config, - environnement: Environment, - portail: Option, - reglages: Mutex, - etat: watch::Sender, - /// Ce que l'état affiche, hors de la partie « en cours » ci-dessous. - base: Mutex, - /// Ce qu'il faut pour décrire le partage en cours, lisible sans attendre. - vue: Mutex>, - /// Le partage en cours, qu'on démarre et arrête: un verrou asynchrone - /// sérialise ces opérations. - actif: tokio::sync::Mutex>, - /// Interrompt un démarrage qui attend le bureau. - annulation: Mutex>>, - contexte: Mutex, - /// Dernier passage en veille ou réveil: une capture qui meurt juste - /// autour est relancée au lieu d'arrêter le partage. - veille: Mutex>, -} - -/// Fenêtre autour d'une veille pendant laquelle une fin de capture est mise -/// sur son compte. -const APRES_VEILLE: Duration = Duration::from_secs(30); - -#[derive(Default)] -struct Base { - phase: Option, - erreur: Option, - arret: Option, - avertissements: Vec, - veille_inhibee: Vec, - reglages_en_attente: Vec, - reglages_recuperes: Option, -} - -struct Vue { - room: Arc, - live: Option>, - source: SourcePartagee, - scheme: &'static str, - ecoute: SocketAddr, - interface: Option, - empreinte: Option, - demarre_ms: u64, - /// Dernier QR rendu et l'URL qu'il porte: l'état est recomposé chaque - /// seconde, le QR seulement quand l'URL change. - qr: Option<(String, String)>, -} - -struct Serveur { - tache: JoinHandle>, - arret: oneshot::Sender<()>, -} - -struct Actif { - room: Arc, - media: Arc, - live: Option>, - portail: Option, - choix: SourceChoisie, - settings: StreamSettings, - /// Gardé pour relancer la capture après une veille: les sessions ouvertes - /// ont négocié ce codec, en changer leur donnerait un écran noir. - codec: rs_codec::VideoCodec, - serveur: Serveur, - tls: Option, - ecoute: SocketAddr, - inhibition: Option, - surveillance: JoinHandle<()>, -} - -impl Hote { - /// Charge les réglages, interroge le portail, et attend les ordres. Aucun - /// port n'est ouvert tant qu'aucun partage n'est démarré. - pub async fn nouveau(config: Config) -> Self { - let environnement = Environment::detect(); - let portail = if environnement.session == SessionType::Wayland { - match rs_platform::portal::probe().await { - Ok(portail) => { - tracing::info!( - version = portail.version, - types = portail.types, - ecran_virtuel = portail.supporte_ecran_virtuel(), - "portail d'enregistrement d'écran disponible" - ); - Some(portail) - } - Err(erreur) => { - tracing::warn!(%erreur, "portail d'enregistrement d'écran indisponible"); - None - } - } - } else { - None - }; - - let mut base = Base::default(); - let reglages = match &config.magasin { - Some(magasin) => { - let (reglages, origine) = magasin.charger(); - if let Origine::Recupere { sauvegarde, raison } = origine { - base.reglages_recuperes = Some(match sauvegarde { - Some(chemin) => format!( - "Réglages illisibles ({raison}): l'ancien fichier est gardé dans {}, \ - les valeurs sûres sont rétablies.", - chemin.display() - ), - None => format!("Réglages illisibles ({raison}): valeurs sûres rétablies."), - }); - } - reglages - } - None => Reglages::default(), - }; - - let contexte = Contexte { - version: config.version.clone(), - environnement: environnement.clone(), - portail, - capture: None, - virtuel: false, - encodage: None, - journaux: config.journaux.clone(), - }; - let interne = Arc::new(Interne { - etat: watch::Sender::new(etat_vide(&environnement, portail, &config)), - config, - environnement, - portail, - reglages: Mutex::new(reglages), - base: Mutex::new(base), - vue: Mutex::new(None), - actif: tokio::sync::Mutex::new(None), - annulation: Mutex::new(None), - contexte: Mutex::new(contexte), - veille: Mutex::new(None), - }); - let hote = Self(interne); - hote.rafraichir(); - tokio::spawn(surveiller_veille(Arc::downgrade(&hote.0))); - hote - } - - pub fn environnement(&self) -> &Environment { - &self.0.environnement - } - - pub fn portail(&self) -> Option<&PortalInfo> { - self.0.portail.as_ref() - } - - /// L'état courant. - pub fn etat(&self) -> Etat { - self.0.etat.borrow().clone() - } - - /// L'état, à chaque changement. - pub fn abonner(&self) -> watch::Receiver { - self.0.etat.subscribe() - } - - /// Les sources de cette machine, vignettes comprises quand c'est possible. - pub async fn sources(&self) -> Vec { - let environnement = self.0.environnement.clone(); - let portail = self.0.portail; - tokio::task::spawn_blocking(move || { - crate::sources::proposer(&environnement, portail.as_ref()) - }) - .await - .unwrap_or_default() - } - - pub fn reglages(&self) -> Reglages { - verrou(&self.0.reglages).clone() - } - - pub fn interfaces(&self) -> Vec { - rs_platform::interfaces() - .into_iter() - .filter(|i| !i.boucle) - .map(|i| InterfaceProposee { - nom: i.nom, - adresses: i.adresses.iter().map(IpAddr::to_string).collect(), - active: i.active, - }) - .collect() - } - - /// L'archive de diagnostics, nom et contenu. - pub fn diagnostics(&self) -> Result<(String, Vec), String> { - verrou(&self.0.contexte).archive() - } - - pub fn contexte(&self) -> Contexte { - verrou(&self.0.contexte).clone() - } - - /// Démarre un partage. Rend l'erreur à afficher, telle quelle. - pub async fn demarrer(&self, choix: SourceChoisie) -> Result<(), String> { - let mut actif = self.0.actif.lock().await; - if actif.is_some() { - return Err("un partage est déjà en cours: l'arrêter d'abord".into()); - } - let (annuler, annule) = oneshot::channel(); - *verrou(&self.0.annulation) = Some(annuler); - self.modifier_base(|b| { - b.phase = Some(Phase::Demarrage); - b.erreur = None; - b.arret = None; - b.avertissements.clear(); - b.reglages_en_attente.clear(); - }); - - let resultat = tokio::select! { - resultat = self.ouvrir(choix) => resultat, - _ = annule => Err("démarrage annulé".to_string()), - }; - verrou(&self.0.annulation).take(); - - match resultat { - Ok(ouvert) => { - *actif = Some(ouvert); - self.modifier_base(|b| b.phase = Some(Phase::EnCours)); - Ok(()) - } - Err(erreur) => { - tracing::warn!(evenement = "partage_refuse", %erreur, "partage non démarré"); - self.modifier_base(|b| { - b.phase = Some(Phase::Arrete); - b.erreur = Some(erreur.clone()); - }); - Err(erreur) - } - } - } - - /// Arrête le partage, ou interrompt un démarrage en cours. - pub async fn arreter(&self) { - if let Some(annuler) = verrou(&self.0.annulation).take() { - let _ = annuler.send(()); - } - self.arreter_avec(None).await; - } - - /// Déconnecte un spectateur. Il ne revient pas avec ce jeton. - pub fn deconnecter(&self, connexion: u64) -> bool { - let room = verrou(&self.0.vue).as_ref().map(|v| v.room.clone()); - let fait = room.is_some_and(|room| room.expulser(connexion)); - if fait { - tracing::info!(evenement = "spectateur_deconnecte", "déconnecté par l'hôte"); - } - fait - } - - /// Tire un nouveau QR code et un nouveau code court (#19). Les - /// spectateurs présents restent, et un appareil déjà admis revient avec - /// l'ancien; les autres ont besoin du nouveau. - pub fn regenerer_acces(&self) -> bool { - let room = verrou(&self.0.vue).as_ref().map(|v| v.room.clone()); - let Some(room) = room else { - return false; - }; - room.regenerer(validite(self.reglages().validite_code_min)); - tracing::info!(evenement = "acces_regenere", "nouveau code d'accès"); - self.rafraichir(); - true - } - - /// Valide, enregistre et applique. Rend ce qui s'applique tout de suite et - /// ce qui attend le prochain partage, pour que l'interface le dise. - pub async fn modifier_reglages(&self, nouveaux: Reglages) -> Result> { - let mut refus = nouveaux.valider(); - let anciens = self.reglages(); - if nouveaux.demarrage_auto != anciens.demarrage_auto - && self.0.config.demarrage_auto.is_none() - { - refus.push(Refus { - champ: "demarrage_auto".into(), - message: "réglable depuis l'application de bureau seulement".into(), - }); - } - if !refus.is_empty() { - return Err(refus); - } - if let Some((executable, arguments)) = &self.0.config.demarrage_auto - && nouveaux.demarrage_auto != anciens.demarrage_auto - { - let resultat = rs_platform::demarrage::dossier() - .ok_or_else(|| "dossier de configuration introuvable".to_string()) - .and_then(|dossier| { - rs_platform::demarrage::regler( - &dossier, - nouveaux.demarrage_auto, - executable, - arguments, - ) - .map_err(|e| e.to_string()) - }); - if let Err(message) = resultat { - return Err(vec![Refus { - champ: "demarrage_auto".into(), - message, - }]); - } - } - if let Some(magasin) = &self.0.config.magasin - && let Err(erreur) = magasin.enregistrer(&nouveaux) - { - return Err(match erreur { - rs_store::StoreError::Refuses(refus) => refus, - autre => vec![Refus { - champ: "fichier".into(), - message: autre.to_string(), - }], - }); - } - *verrou(&self.0.reglages) = nouveaux.clone(); - - let room = verrou(&self.0.vue).as_ref().map(|v| v.room.clone()); - let mut application = Application::default(); - let mut change = |champ: &str, a_change: bool, attend: Option<&str>| { - if !a_change { - return; - } - match (attend, &room) { - (Some(raison), Some(_)) => application - .au_prochain_partage - .push(format!("{champ}: {raison}")), - _ => application.immediats.push(champ.to_string()), - } - }; - let surcharges = self.0.config.surcharges; - change( - "port", - nouveaux.port != anciens.port, - Some("changer de port couperait les spectateurs"), - ); - change( - "interface", - nouveaux.interface != anciens.interface, - Some("changer d'interface couperait les spectateurs"), - ); - change( - "codec", - nouveaux.codec != anciens.codec, - Some("les spectateurs présents ont négocié le codec du partage en cours"), - ); - change( - "qualite", - nouveaux.qualite != anciens.qualite, - Some("l'encodeur garde la qualité du partage en cours"), - ); - change( - "validite_code_min", - nouveaux.validite_code_min != anciens.validite_code_min, - Some("le code affiché garde son échéance, le prochain prendra la nouvelle durée"), - ); - change("limite", nouveaux.limite != anciens.limite, None); - change("theme", nouveaux.theme != anciens.theme, None); - change("fermeture", nouveaux.fermeture != anciens.fermeture, None); - change("langue", nouveaux.langue != anciens.langue, None); - change( - "demarrage_auto", - nouveaux.demarrage_auto != anciens.demarrage_auto, - None, - ); - if nouveaux.limite != anciens.limite - && surcharges.limite.is_none() - && let Some(room) = &room - { - room.set_limit(nouveaux.limite); - } - tracing::info!( - evenement = "reglages_modifies", - immediats = ?application.immediats, - en_attente = ?application.au_prochain_partage, - "réglages enregistrés" - ); - let en_attente = application.au_prochain_partage.clone(); - self.modifier_base(|b| { - for champ in en_attente { - if !b.reglages_en_attente.contains(&champ) { - b.reglages_en_attente.push(champ); - } - } - }); - Ok(application) - } - - /// Attend la fin du partage en cours, et dit pourquoi il s'est arrêté. - pub async fn fin(&self) -> Option { - let mut abonne = self.abonner(); - let etat = abonne - .wait_for(|e| e.phase == Phase::Arrete) - .await - .ok()? - .clone(); - etat.arret - } - - // -- Démarrage et arrêt ------------------------------------------------- - - async fn ouvrir(&self, choix: SourceChoisie) -> Result { - let reglages = self.reglages(); - let surcharges = self.0.config.surcharges; - let settings = StreamSettings::for_preset(reglages.qualite); - let codec = surcharges.codec.unwrap_or(match reglages.codec { - rs_store::Codec::Vp8 => rs_codec::VideoCodec::Vp8, - rs_store::Codec::Vp9 => rs_codec::VideoCodec::Vp9, - }); - let limite = surcharges.limite.unwrap_or(reglages.limite); - let port = surcharges.port.unwrap_or(reglages.port); - - // Le port d'abord: un port pris doit se dire avant que le bureau ne - // demande l'autorisation de partager l'écran. - let ip = adresse_ecoute(reglages.interface.as_deref())?; - let listener = rs_signaling::lier(SocketAddr::new(ip, port)).map_err(|e| e.to_string())?; - let ecoute = listener.local_addr().map_err(|e| e.to_string())?; - - let lancee = capture::lancer(&choix, &settings, codec, self.0.portail.as_ref()) - .await - .map_err(|e| e.to_string())?; - let CaptureLancee { - media, - live, - portail, - source, - encodage, - } = lancee; - let media = MediaCommutable::new(media); - - let tls = if self.0.config.tls { - let dossier = std::env::var("XDG_DATA_HOME") - .map(PathBuf::from) - .unwrap_or_else(|_| PathBuf::from(".rustscreen")); - let noms = vec![ - "localhost".to_string(), - "rustscreen.local".to_string(), - "127.0.0.1".to_string(), - ]; - let materiel = - TlsMaterial::load_or_create(&dossier, &noms).map_err(|e| e.to_string())?; - tracing::info!(empreinte = %materiel.fingerprint_pairs(), "certificat prêt"); - Some(materiel) - } else { - None - }; - - let room = Arc::new( - Room::new(None, settings, limite).avec_validite(validite(reglages.validite_code_min)), - ); - let serveur = self.lancer_serveur(listener, tls.clone(), room.clone(), media.clone()); - - let inhibition = match Inhibition::prendre("partage d'écran en cours").await { - Ok(inhibition) => Some(inhibition), - Err(erreur) => { - tracing::warn!(%erreur, "veille non inhibée"); - None - } - }; - let veille: Vec = inhibition - .as_ref() - .map(|i| i.actives().iter().map(|m| m.to_string()).collect()) - .unwrap_or_default(); - - { - let mut contexte = verrou(&self.0.contexte); - contexte.capture = Some(source.chemin.clone()); - contexte.virtuel = matches!(choix, SourceChoisie::Portail { virtuel: true, .. }); - contexte.encodage = encodage; - } - let demarre_ms = maintenant_ms(); - *verrou(&self.0.vue) = Some(Vue { - room: room.clone(), - live: live.clone(), - source, - scheme: if tls.is_some() { "https" } else { "http" }, - ecoute, - interface: reglages.interface.clone(), - empreinte: tls.as_ref().map(TlsMaterial::fingerprint_pairs), - demarre_ms, - qr: None, - }); - self.modifier_base(|b| b.veille_inhibee = veille); - - tracing::info!( - evenement = "partage_demarre", - ecoute = %ecoute, - interface = reglages.interface.is_some(), - limite, - "partage démarré" - ); - let surveillance = tokio::spawn(surveiller(Arc::downgrade(&self.0), room.abonner())); - Ok(Actif { - room, - media, - live, - portail, - choix, - settings, - codec, - serveur, - tls, - ecoute, - inhibition, - surveillance, - }) - } - - fn lancer_serveur( - &self, - listener: std::net::TcpListener, - tls: Option, - room: Arc, - media: Arc, - ) -> Serveur { - let (arret, signal) = oneshot::channel::<()>(); - let faible = Arc::downgrade(&self.0); - let fabrique: rs_signaling::Diagnostics = Arc::new(move || { - let interne = faible.upgrade().ok_or_else(|| "hôte arrêté".to_string())?; - let contexte = verrou(&interne.contexte).clone(); - contexte.archive() - }); - let limite = room.limit(); - let tache = tokio::spawn(rs_signaling::servir( - listener, - HostConfig { - bind: SocketAddr::new(Ipv4Addr::UNSPECIFIED.into(), 0), - tls, - viewer_dir: self.0.config.viewer_dir.clone(), - limit: limite, - diagnostics: Some(fabrique), - }, - room, - Arc::new(Commutable(media)), - async move { - let _ = signal.await; - }, - )); - Serveur { tache, arret } - } - - async fn arreter_avec(&self, arret: Option) { - let mut actif = self.0.actif.lock().await; - let Some(ouvert) = actif.take() else { - return; - }; - fermer(ouvert).await; - *verrou(&self.0.vue) = None; - if let Some(arret) = &arret { - tracing::warn!( - evenement = "partage_interrompu", - raison = %arret.raison, - par_le_bureau = arret.par_le_bureau, - "partage arrêté" - ); - } else { - tracing::info!( - evenement = "partage_termine", - "partage arrêté par l'utilisateur" - ); - } - self.modifier_base(|b| { - b.phase = Some(Phase::Arrete); - b.arret = arret; - b.veille_inhibee.clear(); - b.reglages_en_attente.clear(); - b.avertissements.clear(); - }); - } - - /// Change l'adresse d'écoute d'un partage en cours: même room, même - /// capture, nouveau serveur. Les spectateurs doivent rescanner, l'ancienne - /// adresse n'existant plus. - async fn readresser(&self, nouvelle: IpAddr) { - let mut actif = self.0.actif.lock().await; - let Some(ouvert) = actif.as_mut() else { - return; - }; - let ancienne = ouvert.ecoute; - let listener = match rs_signaling::lier(SocketAddr::new(nouvelle, ancienne.port())) { - Ok(listener) => listener, - Err(erreur) => { - self.avertir(format!( - "Nouvelle adresse {nouvelle} inutilisable: {erreur}" - )); - return; - } - }; - let Ok(ecoute) = listener.local_addr() else { - return; - }; - let serveur = self.lancer_serveur( - listener, - ouvert.tls.clone(), - ouvert.room.clone(), - ouvert.media.clone(), - ); - let ancien = std::mem::replace(&mut ouvert.serveur, serveur); - ouvert.ecoute = ecoute; - drop(actif); - arreter_serveur(ancien).await; - if let Some(vue) = verrou(&self.0.vue).as_mut() { - vue.ecoute = ecoute; - } - tracing::warn!( - evenement = "adresse_changee", - avant = %ancienne.ip(), - apres = %nouvelle, - "serveur relancé sur la nouvelle adresse" - ); - self.modifier_base(|b| { - b.avertissements.retain(|a| !a.starts_with("L'interface")); - b.avertissements.push(format!( - "Adresse changée ({} devient {nouvelle}): faire scanner le nouveau QR code.", - ancienne.ip() - )); - }); - } - - /// Relance la capture d'un partage dont la source s'est arrêtée pendant - /// une veille, sans changer de room: les spectateurs reprennent seuls. - async fn relancer_capture(&self) -> Result<(), String> { - let mut actif = self.0.actif.lock().await; - let Some(ouvert) = actif.as_mut() else { - return Ok(()); - }; - let lancee = capture::lancer( - &ouvert.choix, - &ouvert.settings, - ouvert.codec, - self.0.portail.as_ref(), - ) - .await - .map_err(|e| e.to_string())?; - let ancienne = ouvert.media.remplacer(lancee.media); - let ancien_live = std::mem::replace(&mut ouvert.live, lancee.live.clone()); - let ancien_portail = std::mem::replace(&mut ouvert.portail, lancee.portail); - if let Some(vue) = verrou(&self.0.vue).as_mut() { - vue.live = lancee.live; - } - drop(actif); - if let Some(session) = ancien_portail { - session.fermer().await; - } - // L'arrêt d'une capture joint son thread: hors du runtime. - let _ = tokio::task::spawn_blocking(move || drop((ancienne, ancien_live))).await; - tracing::info!( - evenement = "capture_relancee", - "capture relancée après le réveil" - ); - Ok(()) - } - - // -- État ----------------------------------------------------------------- - - fn noter_veille(&self) { - *verrou(&self.0.veille) = Some(std::time::Instant::now()); - } - - fn veille_recente(&self) -> bool { - verrou(&self.0.veille).is_some_and(|quand| quand.elapsed() < APRES_VEILLE) - } - - fn modifier_base(&self, f: impl FnOnce(&mut Base)) { - f(&mut verrou(&self.0.base)); - self.rafraichir(); - } - - fn avertir(&self, message: String) { - self.modifier_base(|b| { - if !b.avertissements.contains(&message) { - b.avertissements.push(message); - } - }); - } - - /// Recompose l'état et ne notifie que s'il a changé. - fn rafraichir(&self) { - let interne = &self.0; - let etat = { - let base = verrou(&interne.base); - let mut vue = verrou(&interne.vue); - Etat { - phase: base.phase.unwrap_or(Phase::Arrete), - partage: vue.as_mut().map(decrire), - erreur: base.erreur.clone(), - arret: base.arret.clone(), - avertissements: base.avertissements.clone(), - veille_inhibee: base.veille_inhibee.clone(), - reglages_en_attente: base.reglages_en_attente.clone(), - reglages_recuperes: base.reglages_recuperes.clone(), - capacites: capacites(&interne.environnement, interne.portail, &interne.config), - } - }; - interne.etat.send_if_modified(|courant| { - if *courant == etat { - false - } else { - *courant = etat; - true - } - }); - } -} - -fn decrire(vue: &mut Vue) -> Partage { - let annonce = (!vue.ecoute.ip().is_unspecified()).then_some(vue.ecoute.ip()); - let url = rs_signaling::url_session( - vue.scheme, - annonce, - vue.ecoute.port(), - &vue.room, - vue.empreinte.as_deref(), - ); - let qr_svg = match &vue.qr { - Some((porte, svg)) if *porte == url => svg.clone(), - _ => { - let svg = rs_signaling::qr::encode(&url) - .map(|matrice| rs_signaling::qr::render_svg(&matrice, 8)) - .unwrap_or_default(); - vue.qr = Some((url.clone(), svg.clone())); - svg - } - }; - let mut source = vue.source.clone(); - if let Some(live) = &vue.live { - let stats = live.stats(); - source.largeur = stats.width; - source.hauteur = stats.height; - } - Partage { - source, - room: vue.room.id.to_string(), - url, - qr_svg, - code: vue.room.code(), - expire_ms: vue.room.expire_ms(), - acces_expire: vue.room.acces_expire(), - empreinte: vue.empreinte.clone(), - ecoute: vue.ecoute.to_string(), - interface: vue.interface.clone(), - appareils: vue - .room - .appareils() - .into_iter() - .map(|a| AppareilVu { - connexion: a.connexion, - nom: a.nom, - plateforme: a.plateforme, - adresse: a.adresse.to_string(), - depuis_ms: a.depuis_ms, - }) - .collect(), - limite: vue.room.limit(), - demarre_ms: vue.demarre_ms, - } -} - -fn capacites( - environnement: &Environment, - portail: Option, - config: &Config, -) -> Capacites { - Capacites { - session: match environnement.session { - SessionType::Wayland => "wayland", - SessionType::X11 => "x11", - SessionType::Headless => "aucune", - } - .into(), - bureau: format!("{:?}", environnement.desktop), - portail: portail.is_some(), - ecran_virtuel: portail.is_some_and(|p| p.supporte_ecran_virtuel()), - pipewire: cfg!(feature = "pipewire"), - demarrage_auto: config.demarrage_auto.is_some(), - } -} - -fn etat_vide(environnement: &Environment, portail: Option, config: &Config) -> Etat { - Etat { - phase: Phase::Arrete, - partage: None, - erreur: None, - arret: None, - avertissements: Vec::new(), - veille_inhibee: Vec::new(), - reglages_en_attente: Vec::new(), - reglages_recuperes: None, - capacites: capacites(environnement, portail, config), - } -} - -/// L'adresse d'écoute: celle de l'interface choisie, ou toutes. -fn adresse_ecoute(interface: Option<&str>) -> Result { - let Some(nom) = interface else { - return Ok(Ipv4Addr::UNSPECIFIED.into()); - }; - let trouvee = rs_platform::reseau::interface(nom).ok_or_else(|| { - format!( - "l'interface {nom} n'a pas d'adresse: la brancher, ou choisir « toutes les \ - interfaces » dans les réglages" - ) - })?; - trouvee.adresse_principale().ok_or_else(|| { - format!("l'interface {nom} n'a pas d'adresse joignable par un autre appareil") - }) -} - -async fn fermer(ouvert: Actif) { - let Actif { - room, - media, - live, - portail, - serveur, - inhibition, - surveillance, - .. - } = ouvert; - surveillance.abort(); - arreter_serveur(serveur).await; - drop(room); - if let Some(session) = portail { - session.fermer().await; - } - if let Some(inhibition) = inhibition { - inhibition.relacher().await; - } - // L'arrêt de la capture joint son thread d'encodage: hors du runtime. - let _ = tokio::task::spawn_blocking(move || drop((media, live))).await; -} - -async fn arreter_serveur(serveur: Serveur) { - let Serveur { mut tache, arret } = serveur; - let _ = arret.send(()); - match tokio::time::timeout(ARRET_SERVEUR, &mut tache).await { - Ok(Ok(Err(erreur))) => tracing::warn!(%erreur, "serveur arrêté sur une erreur"), - Ok(_) => {} - Err(_) => { - tracing::warn!("serveur trop lent à s'arrêter: interrompu"); - tache.abort(); - } - } -} - -/// Suit un partage: arrivées et départs, fin de capture, réseau. -async fn surveiller(faible: Weak, mut changements: watch::Receiver) { - let mut intervalle = tokio::time::interval(SURVEILLANCE); - let mut adresse_par_defaut = rs_rtc::local_candidate_address(); - // L'horloge monotone s'arrête pendant la veille, pas l'horloge murale: un - // grand écart entre deux tours dit que la machine a dormi, même sans - // logind. - let mut dernier_tour = SystemTime::now(); - loop { - tokio::select! { - resultat = changements.changed() => { - if resultat.is_err() { - return; - } - } - _ = intervalle.tick() => {} - } - let Some(interne) = faible.upgrade() else { - return; - }; - let hote = Hote(interne); - let ecart = SystemTime::now() - .duration_since(dernier_tour) - .unwrap_or_default(); - dernier_tour = SystemTime::now(); - if ecart > SURVEILLANCE * 10 { - tracing::info!( - evenement = "reveil_detecte", - secondes = ecart.as_secs(), - "la machine a dormi" - ); - hote.noter_veille(); - } - hote.rafraichir(); - - let (fin, interface, ecoute) = { - let vue = verrou(&hote.0.vue); - let Some(vue) = vue.as_ref() else { - return; - }; - ( - vue.live.as_ref().and_then(|l| l.ended()), - vue.interface.clone(), - vue.ecoute, - ) - }; - - if let Some(cause) = fin { - if hote.veille_recente() { - // Le compositeur a pu fermer le flux pendant la veille: on - // rouvre la même source, dans la même room. Les spectateurs - // reprennent seuls (ADR 0007). - match hote.relancer_capture().await { - Ok(()) => continue, - Err(erreur) => { - tokio::spawn(async move { - hote.arreter_avec(Some(Arret { - raison: format!( - "capture impossible à relancer après la veille: {erreur}" - ), - par_le_bureau: false, - })) - .await; - }); - return; - } - } - } - // L'arrêt annule cette tâche: il part dans la sienne. - tokio::spawn(async move { - hote.arreter_avec(Some(Arret { - raison: format!("capture terminée: {cause}"), - par_le_bureau: true, - })) - .await; - }); - return; - } - - match interface { - Some(nom) => match rs_platform::reseau::interface(&nom) { - Some(trouvee) if trouvee.active => { - hote.modifier_base(|b| { - b.avertissements.retain(|a| !a.starts_with("L'interface")) - }); - if let Some(nouvelle) = trouvee.adresse_principale() - && nouvelle != ecoute.ip() - { - let hote = hote.clone(); - tokio::spawn(async move { hote.readresser(nouvelle).await }); - } - } - _ => hote.avertir(format!( - "L'interface {nom} est déconnectée: les spectateurs ne peuvent plus \ - joindre l'hôte." - )), - }, - None => { - let actuelle = rs_rtc::local_candidate_address(); - if actuelle != adresse_par_defaut { - tracing::warn!( - evenement = "adresse_changee", - avant = ?adresse_par_defaut, - apres = ?actuelle, - "adresse du réseau changée" - ); - if let (Some(_), Some(apres)) = (adresse_par_defaut, actuelle) { - hote.avertir(format!( - "Adresse du réseau changée ({apres}): faire scanner le nouveau QR code." - )); - } - adresse_par_defaut = actuelle; - } - } - } - } -} - -/// La veille selon logind (#42). Elle ne fait que dater l'événement: c'est la -/// surveillance du partage qui décide de relancer une capture morte autour. -async fn surveiller_veille(faible: Weak) { - let mut reprise = match rs_platform::surveiller_reprise().await { - Ok(reprise) => reprise, - Err(erreur) => { - tracing::warn!(%erreur, "réveil non surveillé: pas de logind"); - return; - } - }; - while reprise.suivante().await.is_some() { - // Endormissement comme réveil: la capture peut mourir des deux côtés. - let Some(interne) = faible.upgrade() else { - return; - }; - let hote = Hote(interne); - hote.noter_veille(); - if let Some(actif) = hote.0.actif.lock().await.as_ref() { - // Les spectateurs reviennent par une session neuve: une image clé - // évite qu'ils attendent la suivante. - Commutable(actif.media.clone()).request_keyframe(); - } - } -} - -/// La durée de validité d'un accès, `None` pour sans limite. -fn validite(minutes: u32) -> Option { - (minutes > 0).then(|| Duration::from_secs(u64::from(minutes) * 60)) -} - -fn maintenant_ms() -> u64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .map_or(0, |d| d.as_millis() as u64) -} - -fn verrou(mutex: &Mutex) -> std::sync::MutexGuard<'_, T> { - mutex.lock().unwrap_or_else(|e| e.into_inner()) -} diff --git a/crates/rs-session/src/lib.rs b/crates/rs-session/src/lib.rs index dca9fe8..d111e79 100644 --- a/crates/rs-session/src/lib.rs +++ b/crates/rs-session/src/lib.rs @@ -1,29 +1,29 @@ -//! L'orchestrateur de l'hôte: un partage, sa capture, son serveur, ses -//! spectateurs et ses réglages. +//! The host orchestrator: a share, its capture, its server, its viewers and +//! its settings. //! -//! - [`hote`]: démarrer, arrêter, déconnecter un spectateur, régler, et suivre -//! l'état complet par un seul canal. -//! - [`etat`]: ce que l'interface affiche, exporté en TypeScript. -//! - [`sources`]: ce qu'on peut partager sur cette machine, avec vignettes. -//! - [`capture`]: ouvrir une capture et son encodeur. -//! - [`media`]: une source remplaçable sans couper les spectateurs. -//! - [`diagnostics`]: ce que l'hôte sait de lui-même, pour l'archive. +//! - [`host`]: start, stop, disconnect a viewer, change settings, and follow +//! the full state through a single channel. +//! - [`state`]: what the interface displays, exported to TypeScript. +//! - [`sources`]: what can be shared on this machine, with thumbnails. +//! - [`capture`]: open a capture and its encoder. +//! - [`media`]: a replaceable source that does not cut viewers off. +//! - [`diagnostics`]: what the host knows about itself, for the archive. //! -//! La ligne de commande (`rustscreen`) et la coque desktop s'en servent de la -//! même façon: aucun des deux ne connaît la capture ni le serveur. +//! The command line (`rustscreen`) and the desktop shell use it the same way: +//! neither knows about the capture or the server. pub mod capture; pub mod diagnostics; -pub mod etat; -pub mod hote; +pub mod host; pub mod media; pub mod sources; +pub mod state; -pub use etat::{ - Application, Arret, Etat, InterfaceProposee, Libelle, NoteSource, Partage, Phase, - SourceChoisie, SourceProposee, -}; -pub use hote::{Config, Hote, Surcharges}; -/// Le codec d'un lancement (`Surcharges::codec`), pour que la coque n'ait pas à -/// dépendre de `rs-codec`. +pub use host::{Config, Host, Overrides}; +/// The codec of a launch (`Overrides::codec`), so the shell does not have to +/// depend on `rs-codec`. pub use rs_codec::VideoCodec; +pub use state::{ + Capabilities, HostState, InterfaceOption, Label, Phase, SettingsOutcome, Share, SharedSource, + SourceChoice, SourceNote, SourceOption, Stop, ViewerDevice, +}; diff --git a/crates/rs-session/src/media.rs b/crates/rs-session/src/media.rs index 448748f..d18a6d6 100644 --- a/crates/rs-session/src/media.rs +++ b/crates/rs-session/src/media.rs @@ -1,110 +1,109 @@ -//! Une source média dont on peut remplacer la capture sans couper personne. +//! A media source whose capture can be replaced without cutting anyone off. //! -//! Le serveur reçoit une source à son démarrage et la garde. Pour relancer la -//! capture après une veille (#42), sans changer de room ni de jeton, il faut -//! donc une source qui délègue à une capture remplaçable: c'est celle-ci. -//! Chaque spectateur voit le changement à sa frame suivante: il se réabonne à -//! la nouvelle capture, et une image clé est demandée pour que son décodeur -//! reparte sans attendre. +//! The server receives a source when it starts and keeps it. To restart the +//! capture after sleep (#42) without changing room or token, we therefore need +//! a source that delegates to a replaceable capture: this is it. Each viewer +//! sees the change at its next frame: it subscribes again to the new capture, +//! and a keyframe is requested so its decoder restarts without waiting. use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, RwLock}; use rs_codec::{FrameSource, SharedMedia, VideoCodec}; -pub struct MediaCommutable { - courante: RwLock>, +pub struct SwitchableMedia { + current: RwLock>, generation: AtomicU64, } -impl MediaCommutable { - pub fn new(initiale: Arc) -> Arc { +impl SwitchableMedia { + pub fn new(initial: Arc) -> Arc { Arc::new(Self { - courante: RwLock::new(initiale), + current: RwLock::new(initial), generation: AtomicU64::new(0), }) } - /// Remplace la capture. L'ancienne est rendue: c'est à l'appelant de la - /// laisser tomber hors du runtime (son arrêt joint un thread). - pub fn remplacer(&self, nouvelle: Arc) -> Arc { - let ancienne = { - let mut courante = self.courante.write().unwrap_or_else(|e| e.into_inner()); - std::mem::replace(&mut *courante, nouvelle) + /// Replaces the capture. The old one is returned: the caller must drop it + /// outside the runtime (stopping it joins a thread). + pub fn replace(&self, new: Arc) -> Arc { + let old = { + let mut current = self.current.write().unwrap_or_else(|e| e.into_inner()); + std::mem::replace(&mut *current, new) }; self.generation.fetch_add(1, Ordering::Release); - self.courante().request_keyframe(); - ancienne + self.current().request_keyframe(); + old } - fn courante(&self) -> Arc { - self.courante + fn current(&self) -> Arc { + self.current .read() .unwrap_or_else(|e| e.into_inner()) .clone() } } -/// `subscribe` est appelé par le serveur sur un `Arc`: la vue -/// a besoin d'un `Arc` vers son parent, d'où ce petit enrobage. -pub struct Commutable(pub Arc); +/// `subscribe` is called by the server on an `Arc`: the view +/// needs an `Arc` to its parent, hence this small wrapper. +pub struct Switchable(pub Arc); -impl SharedMedia for Commutable { +impl SharedMedia for Switchable { fn subscribe(&self) -> Box { let generation = self.0.generation.load(Ordering::Acquire); - Box::new(VueCommutable { + Box::new(SwitchableView { parent: self.0.clone(), generation, - interne: self.0.courante().subscribe(), - servies: 0, + inner: self.0.current().subscribe(), + served: 0, }) } fn fps(&self) -> u8 { - self.0.courante().fps() + self.0.current().fps() } fn dimensions(&self) -> (u32, u32) { - self.0.courante().dimensions() + self.0.current().dimensions() } fn codec(&self) -> VideoCodec { - self.0.courante().codec() + self.0.current().codec() } fn request_keyframe(&self) { - self.0.courante().request_keyframe(); + self.0.current().request_keyframe(); } } -struct VueCommutable { - parent: Arc, +struct SwitchableView { + parent: Arc, generation: u64, - interne: Box, - servies: u64, + inner: Box, + served: u64, } -impl FrameSource for VueCommutable { +impl FrameSource for SwitchableView { fn fps(&self) -> u8 { - self.interne.fps() + self.inner.fps() } fn dimensions(&self) -> (u32, u32) { - self.interne.dimensions() + self.inner.dimensions() } fn next_frame(&mut self) -> Arc<[u8]> { let generation = self.parent.generation.load(Ordering::Acquire); if generation != self.generation { - self.interne = self.parent.courante().subscribe(); + self.inner = self.parent.current().subscribe(); self.generation = generation; } - self.servies += 1; - self.interne.next_frame() + self.served += 1; + self.inner.next_frame() } fn served(&self) -> u64 { - self.servies + self.served } } @@ -113,23 +112,23 @@ mod tests { use super::*; use rs_codec::SharedPlayback; - fn rejeu(octet: u8) -> Arc { - let image: Arc<[u8]> = Arc::from(&[octet; 4][..]); - Arc::new(SharedPlayback::new(Arc::new(vec![image]), 30, 64, 64)) + fn playback(byte: u8) -> Arc { + let frame: Arc<[u8]> = Arc::from(&[byte; 4][..]); + Arc::new(SharedPlayback::new(Arc::new(vec![frame]), 30, 64, 64)) } #[test] fn a_subscriber_follows_a_replaced_capture() { - let media = MediaCommutable::new(rejeu(1)); - let partage = Commutable(media.clone()); - let mut vue = partage.subscribe(); - assert_eq!(vue.next_frame()[0], 1); - let _ancienne = media.remplacer(rejeu(2)); + let media = SwitchableMedia::new(playback(1)); + let shared = Switchable(media.clone()); + let mut view = shared.subscribe(); + assert_eq!(view.next_frame()[0], 1); + let _old = media.replace(playback(2)); assert_eq!( - vue.next_frame()[0], + view.next_frame()[0], 2, - "la vue doit suivre la nouvelle capture" + "the view must follow the new capture" ); - assert_eq!(vue.served(), 2); + assert_eq!(view.served(), 2); } } diff --git a/crates/rs-session/src/sources.rs b/crates/rs-session/src/sources.rs index 7daf84b..e45ca79 100644 --- a/crates/rs-session/src/sources.rs +++ b/crates/rs-session/src/sources.rs @@ -1,127 +1,127 @@ -//! Les sources que l'interface propose, avec leur vignette quand c'est possible. +//! The sources the interface offers, with their thumbnail when possible. //! -//! La liste dit ce que la plateforme sait faire, sans promettre plus (risque 2 -//! d'`ARCHITECTURE.md`): sous Wayland, on ne peut ni lister les écrans ni en -//! prendre une vignette avant l'accord de l'utilisateur. On propose donc « un -//! écran », et c'est le sélecteur du bureau qui dit lequel. Sous X11, chaque -//! moniteur et chaque fenêtre est listé, vignette comprise (#16). +//! The list says what the platform can do, without promising more (risk 2 in +//! `ARCHITECTURE.md`): under Wayland, screens can neither be listed nor +//! thumbnailed before the user agrees. So we offer "a screen", and the desktop +//! picker says which one. Under X11, every monitor and every window is listed, +//! thumbnail included (#16). use base64::Engine as _; use rs_capture::CapturedFrame; use rs_platform::{Environment, PortalInfo, SessionType}; use rs_proto::SourceKind; -use crate::capture::TAILLE_VIRTUELLE; -use crate::etat::{Libelle, NoteSource, SourceChoisie, SourceProposee}; +use crate::capture::DEFAULT_VIRTUAL_SIZE; +use crate::state::{Label, SourceChoice, SourceNote, SourceOption}; -/// Largeur maximale d'une vignette: assez pour reconnaître un écran, assez -/// petit pour que vingt fenêtres passent sans peser. -const VIGNETTE_LARGEUR: u32 = 320; -const VIGNETTE_HAUTEUR: u32 = 180; +/// Maximum width of a thumbnail: enough to recognize a screen, small enough +/// for twenty windows to go through without weighing much. +const THUMBNAIL_WIDTH: u32 = 320; +const THUMBNAIL_HEIGHT: u32 = 180; -/// Les sources de cette machine. Bloquant (X11): à appeler hors du runtime. -pub fn proposer(environnement: &Environment, portail: Option<&PortalInfo>) -> Vec { +/// The sources of this machine. Blocking (X11): call it outside the runtime. +pub fn list(environment: &Environment, portal: Option<&PortalInfo>) -> Vec { let mut sources = Vec::new(); - match environnement.session { + match environment.session { SessionType::Wayland => { let pipewire = cfg!(feature = "pipewire"); - let manque = (!pipewire).then_some(NoteSource::SansPipewire); - if portail.is_some() { - sources.push(SourceProposee { - choix: SourceChoisie::Portail { - virtuel: false, - fenetre: false, - taille: None, + let missing = (!pipewire).then_some(SourceNote::NoPipewire); + if portal.is_some() { + sources.push(SourceOption { + choice: SourceChoice::Portal { + virtual_display: false, + window: false, + size: None, }, - genre: SourceKind::Screen, - nom: "Un écran".into(), - libelle: Libelle::Ecran, - largeur: 0, - hauteur: 0, - vignette: None, - note: manque.or(Some(NoteSource::PortailEcran)), - disponible: pipewire, + kind: SourceKind::Screen, + name: "A screen".into(), + label: Label::Screen, + width: 0, + height: 0, + thumbnail: None, + note: missing.or(Some(SourceNote::PortalScreen)), + available: pipewire, }); - // Une fenêtre: seulement si le portail le permet, et on le dit - // avant le démarrage plutôt que de rendre un écran entier (#17). - let fenetre = portail.is_some_and(PortalInfo::supporte_fenetre); - sources.push(SourceProposee { - choix: SourceChoisie::Portail { - virtuel: false, - fenetre: true, - taille: None, + // A window: only if the portal allows it, and we say so before + // starting rather than handing over an entire screen (#17). + let window = portal.is_some_and(PortalInfo::supports_window); + sources.push(SourceOption { + choice: SourceChoice::Portal { + virtual_display: false, + window: true, + size: None, }, - genre: SourceKind::Window, - nom: "Une fenêtre".into(), - libelle: Libelle::Fenetre, - largeur: 0, - hauteur: 0, - vignette: None, - note: Some(match (manque, fenetre) { - (Some(manque), _) => manque, - (None, true) => NoteSource::PortailFenetre, - (None, false) => NoteSource::PortailSansFenetre, + kind: SourceKind::Window, + name: "A window".into(), + label: Label::Window, + width: 0, + height: 0, + thumbnail: None, + note: Some(match (missing, window) { + (Some(missing), _) => missing, + (None, true) => SourceNote::PortalWindow, + (None, false) => SourceNote::PortalNoWindow, }), - disponible: pipewire && fenetre, + available: pipewire && window, }); } - if portail.is_some_and(PortalInfo::supporte_ecran_virtuel) { - let (largeur, hauteur) = TAILLE_VIRTUELLE; - sources.push(SourceProposee { - choix: SourceChoisie::Portail { - virtuel: true, - fenetre: false, - taille: Some(TAILLE_VIRTUELLE), + if portal.is_some_and(PortalInfo::supports_virtual_display) { + let (width, height) = DEFAULT_VIRTUAL_SIZE; + sources.push(SourceOption { + choice: SourceChoice::Portal { + virtual_display: true, + window: false, + size: Some(DEFAULT_VIRTUAL_SIZE), }, - genre: SourceKind::Screen, - nom: "Un second écran (virtuel)".into(), - libelle: Libelle::EcranVirtuel, - largeur, - hauteur, - vignette: None, - note: manque.or(Some(NoteSource::EcranVirtuel)), - disponible: pipewire, + kind: SourceKind::Screen, + name: "A second screen (virtual)".into(), + label: Label::VirtualScreen, + width, + height, + thumbnail: None, + note: missing.or(Some(SourceNote::VirtualScreen)), + available: pipewire, }); } } SessionType::X11 => sources.extend(x11()), SessionType::Headless => {} } - let (largeur, hauteur) = (1280, 720); - sources.push(SourceProposee { - choix: SourceChoisie::Synthetique { largeur, hauteur }, - genre: SourceKind::Screen, - nom: "Mire de test".into(), - libelle: Libelle::Mire, - largeur, - hauteur, - vignette: rs_capture::SyntheticCapturer::new(largeur, hauteur, 1) - .premiere_image() + let (width, height) = (1280, 720); + sources.push(SourceOption { + choice: SourceChoice::Synthetic { width, height }, + kind: SourceKind::Screen, + name: "Test pattern".into(), + label: Label::TestPattern, + width, + height, + thumbnail: rs_capture::SyntheticCapturer::new(width, height, 1) + .first_frame() .ok() - .and_then(|image| vignette(&image)), - note: Some(NoteSource::Mire), - disponible: true, + .and_then(|frame| thumbnail(&frame)), + note: Some(SourceNote::TestPattern), + available: true, }); sources } #[cfg(target_os = "linux")] -fn x11() -> Vec { +fn x11() -> Vec { use rs_capture::ScreenCapturer; - // Cadence élevée: chaque vignette attend une image, autant que ce soit vite. - let Ok(mut capture) = rs_capture::x11::X11Capturer::connecter(None, 240) else { + // High frame rate: each thumbnail waits for a frame, better make it quick. + let Ok(mut capture) = rs_capture::x11::X11Capturer::connect(None, 240) else { return Vec::new(); }; let Ok(sources) = capture.sources() else { return Vec::new(); }; - let principal = capture.moniteur_principal(); - let plusieurs = sources.iter().any(|s| s.id.0.starts_with("x11:moniteur:")); + let primary = capture.primary_monitor(); + let several = sources.iter().any(|s| s.id.0.starts_with("x11:moniteur:")); sources .into_iter() .map(|source| { - let image = source + let frame = source .available .then(|| { capture @@ -130,80 +130,80 @@ fn x11() -> Vec { .ok() }) .flatten(); - let libelle = match source.id.0.strip_prefix("x11:moniteur:") { - Some(sortie) => Libelle::Moniteur { - sortie: sortie.to_string(), - principal: principal.as_deref() == Some(sortie), + let label = match source.id.0.strip_prefix("x11:moniteur:") { + Some(output) => Label::Monitor { + output: output.to_string(), + primary: primary.as_deref() == Some(output), }, - None if source.kind == SourceKind::Window => Libelle::Titre { - texte: source.name.clone(), + None if source.kind == SourceKind::Window => Label::Title { + text: source.name.clone(), }, - None if plusieurs => Libelle::TousLesEcrans, - None => Libelle::EcranEntier, + None if several => Label::AllScreens, + None => Label::EntireScreen, }; - SourceProposee { - choix: SourceChoisie::X11 { + SourceOption { + choice: SourceChoice::X11 { id: source.id.0.clone(), }, - genre: source.kind, - nom: source.name, - libelle, - largeur: source.width, - hauteur: source.height, - vignette: image.as_ref().and_then(vignette), - note: (!source.available).then_some(NoteSource::Reduite), - disponible: source.available, + kind: source.kind, + name: source.name, + label, + width: source.width, + height: source.height, + thumbnail: frame.as_ref().and_then(thumbnail), + note: (!source.available).then_some(SourceNote::Minimized), + available: source.available, } }) .collect() } #[cfg(not(target_os = "linux"))] -fn x11() -> Vec { +fn x11() -> Vec { Vec::new() } -/// Réduit une image en vignette PNG, en `data:` URL. Réduction par moyenne -/// de blocs: un plus-proche-voisin rend le texte illisible et scintillant. -pub fn vignette(image: &CapturedFrame) -> Option { - let (w, h) = (image.width, image.height); - if w == 0 || h == 0 || image.bgra.len() < (w * h * 4) as usize { +/// Scales a frame down to a PNG thumbnail, as a `data:` URL. Box averaging: +/// nearest neighbour makes text unreadable and flickering. +pub fn thumbnail(frame: &CapturedFrame) -> Option { + let (w, h) = (frame.width, frame.height); + if w == 0 || h == 0 || frame.bgra.len() < (w * h * 4) as usize { return None; } - let echelle = (w as f32 / VIGNETTE_LARGEUR as f32) - .max(h as f32 / VIGNETTE_HAUTEUR as f32) + let scale = (w as f32 / THUMBNAIL_WIDTH as f32) + .max(h as f32 / THUMBNAIL_HEIGHT as f32) .max(1.0); - let vw = ((w as f32 / echelle) as u32).max(1); - let vh = ((h as f32 / echelle) as u32).max(1); - let mut rgb = Vec::with_capacity((vw * vh * 3) as usize); - for vy in 0..vh { - let y0 = vy * h / vh; - let y1 = ((vy + 1) * h / vh).max(y0 + 1); - for vx in 0..vw { - let x0 = vx * w / vw; - let x1 = ((vx + 1) * w / vw).max(x0 + 1); - let mut somme = [0u32; 3]; + let tw = ((w as f32 / scale) as u32).max(1); + let th = ((h as f32 / scale) as u32).max(1); + let mut rgb = Vec::with_capacity((tw * th * 3) as usize); + for ty in 0..th { + let y0 = ty * h / th; + let y1 = ((ty + 1) * h / th).max(y0 + 1); + for tx in 0..tw { + let x0 = tx * w / tw; + let x1 = ((tx + 1) * w / tw).max(x0 + 1); + let mut sum = [0u32; 3]; let mut n = 0u32; for y in y0..y1 { - let ligne = (y * w) as usize * 4; + let row = (y * w) as usize * 4; for x in x0..x1 { - let px = ligne + x as usize * 4; - somme[0] += u32::from(image.bgra[px + 2]); - somme[1] += u32::from(image.bgra[px + 1]); - somme[2] += u32::from(image.bgra[px]); + let px = row + x as usize * 4; + sum[0] += u32::from(frame.bgra[px + 2]); + sum[1] += u32::from(frame.bgra[px + 1]); + sum[2] += u32::from(frame.bgra[px]); n += 1; } } - rgb.extend(somme.map(|c| (c / n) as u8)); + rgb.extend(sum.map(|c| (c / n) as u8)); } } let mut png = Vec::new(); { - let mut encodeur = png::Encoder::new(&mut png, vw, vh); - encodeur.set_color(png::ColorType::Rgb); - encodeur.set_depth(png::BitDepth::Eight); - let mut ecrivain = encodeur.write_header().ok()?; - ecrivain.write_image_data(&rgb).ok()?; + let mut encoder = png::Encoder::new(&mut png, tw, th); + encoder.set_color(png::ColorType::Rgb); + encoder.set_depth(png::BitDepth::Eight); + let mut writer = encoder.write_header().ok()?; + writer.write_image_data(&rgb).ok()?; } Some(format!( "data:image/png;base64,{}", @@ -217,28 +217,25 @@ mod tests { #[test] fn a_thumbnail_keeps_the_aspect_ratio_and_is_a_png() { - let image = rs_capture::SyntheticCapturer::new(1920, 1080, 1) - .premiere_image() + let frame = rs_capture::SyntheticCapturer::new(1920, 1080, 1) + .first_frame() .unwrap(); - let url = vignette(&image).unwrap(); + let url = thumbnail(&frame).unwrap(); let png = base64::engine::general_purpose::STANDARD .decode(url.strip_prefix("data:image/png;base64,").unwrap()) .unwrap(); - let decodeur = png::Decoder::new(std::io::Cursor::new(png)); - let lecteur = decodeur.read_info().unwrap(); - let info = lecteur.info(); + let decoder = png::Decoder::new(std::io::Cursor::new(png)); + let reader = decoder.read_info().unwrap(); + let info = reader.info(); assert_eq!((info.width, info.height), (320, 180)); } #[test] fn a_headless_machine_still_offers_the_test_pattern() { - let environnement = Environment::from_vars(|_| None); - let sources = proposer(&environnement, None); + let environment = Environment::from_vars(|_| None); + let sources = list(&environment, None); assert_eq!(sources.len(), 1); - assert!(matches!( - sources[0].choix, - SourceChoisie::Synthetique { .. } - )); - assert!(sources[0].vignette.is_some()); + assert!(matches!(sources[0].choice, SourceChoice::Synthetic { .. })); + assert!(sources[0].thumbnail.is_some()); } } diff --git a/crates/rs-session/src/state.rs b/crates/rs-session/src/state.rs new file mode 100644 index 0000000..aa5bd97 --- /dev/null +++ b/crates/rs-session/src/state.rs @@ -0,0 +1,265 @@ +//! What the host interface displays, as a single object. +//! +//! The interface infers nothing: it receives the full [`HostState`] on every +//! change and displays it. That is what keeps the #15 criterion, "no button +//! that lies": a button has no state of its own, it reads this one. +//! +//! The types are exported to TypeScript (`apps/desktop/src/bindings`), never +//! rewritten by hand (AGENTS.md). + +use rs_proto::SourceKind; +use serde::{Deserialize, Serialize}; +use ts_rs::TS; + +/// Where the share stands. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)] +#[serde(rename_all = "snake_case")] +#[ts(export, export_to = "../../../desktop/src/bindings/")] +pub enum Phase { + Stopped, + /// Capture being opened: the desktop may ask for permission. + Starting, + Live, +} + +/// What the user chooses to share. The interface sends back the `choice` of a +/// [`SourceOption`] as is. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] +#[serde(tag = "type", rename_all = "snake_case")] +#[ts(export, export_to = "../../../desktop/src/bindings/")] +pub enum SourceChoice { + /// A generated test pattern, without a screen: to try things out. + Synthetic { width: u32, height: u32 }, + /// An X11 screen, monitor or window, by identifier. + X11 { id: String }, + /// The desktop portal (Wayland). The desktop shows its own picker: it is + /// the one that says which screen, or which window. + Portal { + virtual_display: bool, + /// A window rather than a screen (#17), if the portal allows it. + #[serde(default)] + window: bool, + /// Size of a virtual screen. Ignored for an existing screen. + size: Option<(u32, u32)>, + }, + /// A replayed VP8 file, for measurements (command line only). + Playback { path: String }, +} + +/// 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. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] +#[serde(tag = "type", rename_all = "snake_case")] +#[ts(export, export_to = "../../../desktop/src/bindings/")] +pub enum Label { + /// A window title, as the application gives it. + Title { + text: String, + }, + /// A monitor, named by its output (`HDMI-1`). + Monitor { + output: String, + primary: bool, + }, + Screen, + Window, + VirtualScreen, + TestPattern, + RecordedPattern, + AllScreens, + EntireScreen, + ChosenScreen, + ChosenWindow, +} + +/// What to know about a source before choosing it, translated by the +/// interface. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)] +#[serde(rename_all = "snake_case")] +#[ts(export, export_to = "../../../desktop/src/bindings/")] +pub enum SourceNote { + /// The desktop will ask which one, and the choice is remembered. + PortalScreen, + /// The desktop shows its windows; covered or minimized, what happens. + PortalWindow, + /// This desktop's portal cannot share a window (#17). + PortalNoWindow, + VirtualScreen, + TestPattern, + /// Binary built without PipeWire: nothing under Wayland. + NoPipewire, + /// Minimized window: restore it first. + Minimized, +} + +impl SourceNote { + /// The text for the command line, which only speaks English. + /// The interface translates the code instead (`locales/*.json`, + /// `desktop.notes`). + pub fn describe(self) -> &'static str { + match self { + Self::PortalScreen => { + "the desktop asks which one to share; the choice is remembered for next time" + } + Self::PortalWindow => "the desktop shows the list of windows", + Self::PortalNoWindow => { + "this desktop can only share an entire screen (portal without window capture)" + } + Self::VirtualScreen => "a screen created for the occasion", + Self::TestPattern => "a generated image, without a screen", + Self::NoPipewire => "binary built without PipeWire: Wayland capture unavailable", + Self::Minimized => "minimized: restore it to share it", + } + } +} + +/// A source offered in the list. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] +#[ts(export, export_to = "../../../desktop/src/bindings/")] +pub struct SourceOption { + pub choice: SourceChoice, + pub 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). + pub name: String, + /// The name to display, which the interface translates. + pub label: Label, + pub width: u32, + pub height: u32, + /// 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. + pub thumbnail: Option, + /// What to know before choosing ("the desktop will ask which one"). + pub note: Option, + /// 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). + pub available: bool, +} + +/// The source being shared. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] +#[ts(export, export_to = "../../../desktop/src/bindings/")] +pub struct SharedSource { + pub kind: SourceKind, + pub name: String, + pub label: Label, + /// `portal`, `x11`, `synthetic` or `ivf`. + pub backend: String, + /// Current encoded size: it follows a resolution change. + pub width: u32, + pub height: u32, +} + +/// A connected viewer. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] +#[ts(export, export_to = "../../../desktop/src/bindings/")] +pub struct ViewerDevice { + /// Number to send back to disconnect it. + #[ts(type = "number")] + pub connection: u64, + pub name: String, + pub platform: Option, + pub address: String, + /// Arrival, in Unix milliseconds. + #[ts(type = "number")] + pub since_ms: u64, +} + +/// A share in progress. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] +#[ts(export, export_to = "../../../desktop/src/bindings/")] +pub struct Share { + pub source: SharedSource, + pub room: String, + /// The URL to hand out, token included, on the LAN address. + pub url: String, + /// The QR code of `url`, as SVG. + pub qr_svg: String, + /// Short code to type without a camera, lowercase: the interface groups it. + pub code: String, + /// Expiry of the token and the code, in Unix milliseconds. `None`: no + /// limit. + #[ts(type = "number | null")] + pub expires_ms: Option, + /// The expiry has passed: no new device gets in until the host draws a + /// new code. + pub access_expired: bool, + /// SHA-256 fingerprint of the certificate, over HTTPS only. + pub fingerprint: Option, + /// Actual listen address and port (`0.0.0.0:8099`, `192.168.1.20:9000`). + pub listen: String, + /// Chosen interface, `None` if the host listens everywhere. + pub interface: Option, + pub devices: Vec, + pub limit: u8, + #[ts(type = "number")] + pub started_ms: u64, +} + +/// Why the last share stopped, when it was not the user. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] +#[ts(export, export_to = "../../../desktop/src/bindings/")] +pub struct Stop { + pub reason: String, + /// Stopped from the desktop ("stop sharing" button, screen unplugged): + /// the command line then exits with code 3. + pub by_desktop: bool, +} + +/// The whole state of the host. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] +#[ts(export, export_to = "../../../desktop/src/bindings/")] +pub struct HostState { + pub phase: Phase, + pub share: Option, + /// Failure of the last start, to display as is. + pub error: Option, + pub stop: Option, + /// What still works but deserves to be known (interface down, address + /// changed). + pub warnings: Vec, + /// Sleep inhibition mechanisms held (`login1`, `screensaver`): empty + /// outside a share, or if none could be taken. + pub sleep_inhibited: Vec, + /// Settings changed during the share, applied to the next one. + pub pending_settings: Vec, + /// The settings file was unusable at startup: what was done about it. + pub settings_recovered: Option, + /// Capabilities of this machine, to offer only what works. + pub capabilities: Capabilities, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] +#[ts(export, export_to = "../../../desktop/src/bindings/")] +pub struct Capabilities { + /// `wayland`, `x11` or `none`. + pub session: String, + pub desktop: String, + pub portal: bool, + pub virtual_display: bool, + /// The binary can consume a PipeWire stream (`pipewire` feature). + pub pipewire: bool, + /// Autostart can be set from this application. + pub autostart: bool, +} + +/// What a settings change produces. +#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize, TS)] +#[ts(export, export_to = "../../../desktop/src/bindings/")] +pub struct SettingsOutcome { + /// Fields applied right away. + pub immediate: Vec, + /// Fields waiting for the next share, with the reason. + pub next_share: Vec, +} + +/// A network interface offered in the settings. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] +#[ts(export, export_to = "../../../desktop/src/bindings/")] +pub struct InterfaceOption { + pub name: String, + pub addresses: Vec, + pub active: bool, +} diff --git a/crates/rs-session/tests/aucune_connexion_sortante.rs b/crates/rs-session/tests/aucune_connexion_sortante.rs deleted file mode 100644 index f266968..0000000 --- a/crates/rs-session/tests/aucune_connexion_sortante.rs +++ /dev/null @@ -1,177 +0,0 @@ -//! Le démarrage n'ouvre aucune connexion hors de la machine. -//! -//! Aucune télémétrie, aucun appel sortant (ARCHITECTURE.md, ADR 0008). Ce test -//! rejoue ce que fait le binaire au démarrage (journal sur disque, serveur, -//! adresse LAN, archive de diagnostics) et relit pendant ce temps la table des -//! sockets dans `/proc/self/net`: une socket **de ce processus** connectée à -//! une adresse qui n'est pas locale est un échec. La table couvre tout l'espace -//! de noms réseau (le navigateur de la machine y figure aussi): on ne garde que -//! les inodes que ce processus détient, lus dans `/proc/self/fd`. -//! -//! Fichier de test à part: chaque fichier de `tests/` est un processus, donc -//! `/proc/self` ne voit pas les sockets d'autres tests lancés en parallèle. -//! -//! `local_candidate_address` « connecte » une socket UDP à 192.0.2.1 pour lire -//! la route par défaut: un `connect` UDP n'émet aucun paquet, et l'adresse est -//! réservée à la documentation (RFC 5737). Elle est donc tolérée, et elle seule. - -#![cfg(target_os = "linux")] - -use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; -use std::time::{Duration, Instant}; - -use rs_session::{Config, Hote, SourceChoisie, Surcharges}; - -/// Adresse distante d'une ligne de `/proc/self/net/{tcp,udp}[6]`. -fn distante(ligne: &str, v6: bool) -> Option { - let champ = ligne.split_whitespace().nth(2)?; - let (ip, port) = champ.split_once(':')?; - let port = u16::from_str_radix(port, 16).ok()?; - let ip = if v6 { - // Quatre mots de 32 bits, chacun en ordre d'hôte (petit-boutiste). - let mut octets = [0u8; 16]; - for i in 0..4 { - let mot = u32::from_str_radix(ip.get(i * 8..i * 8 + 8)?, 16).ok()?; - octets[i * 4..i * 4 + 4].copy_from_slice(&mot.to_le_bytes()); - } - IpAddr::V6(Ipv6Addr::from(octets)) - } else { - IpAddr::V4(Ipv4Addr::from( - u32::from_str_radix(ip, 16).ok()?.to_le_bytes(), - )) - }; - Some(SocketAddr::new(ip, port)) -} - -fn locale(adresse: &SocketAddr) -> bool { - let ip = match adresse.ip() { - IpAddr::V6(v6) => v6.to_ipv4_mapped().map_or(IpAddr::V6(v6), IpAddr::V4), - v4 => v4, - }; - ip.is_unspecified() || ip.is_loopback() || ip == IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1)) -} - -/// Inodes des sockets ouvertes par ce processus (`socket:[12345]`). -fn nos_sockets() -> std::collections::HashSet { - std::fs::read_dir("/proc/self/fd") - .into_iter() - .flatten() - .filter_map(Result::ok) - .filter_map(|e| std::fs::read_link(e.path()).ok()) - .filter_map(|cible| { - cible - .to_str()? - .strip_prefix("socket:[")? - .strip_suffix(']') - .map(str::to_string) - }) - .collect() -} - -/// Les sockets du processus connectées à une adresse non locale. -fn sortantes() -> Vec { - let nos = nos_sockets(); - let mut trouvees = Vec::new(); - for (fichier, v6) in [ - ("tcp", false), - ("udp", false), - ("tcp6", true), - ("udp6", true), - ] { - let Ok(table) = std::fs::read_to_string(format!("/proc/self/net/{fichier}")) else { - continue; - }; - for ligne in table.lines().skip(1) { - // Dixième colonne: l'inode de la socket. - let inode = ligne.split_whitespace().nth(9).unwrap_or_default(); - if !nos.contains(inode) { - continue; - } - if let Some(adresse) = distante(ligne, v6) - && !locale(&adresse) - { - trouvees.push(format!("{fichier} vers {adresse}")); - } - } - } - trouvees -} - -#[test] -fn proc_lines_are_parsed() { - // 127.0.0.1:8099 et [::1]:443, tels que les écrit le noyau. - let v4 = "0: 0100007F:1FA3 0100007F:1F93 01 00000000:00000000"; - assert_eq!(distante(v4, false), Some("127.0.0.1:8083".parse().unwrap())); - let v6 = "0: 00000000000000000000000001000000:1FA3 00000000000000000000000001000000:01BB 01"; - assert_eq!(distante(v6, true), Some("[::1]:443".parse().unwrap())); - assert!(locale(&"0.0.0.0:0".parse().unwrap())); - assert!(!locale(&"93.184.216.34:443".parse().unwrap())); -} - -#[tokio::test(flavor = "multi_thread")] -async fn startup_opens_no_outbound_connection() { - // Témoin d'abord: le détecteur doit voir une connexion de ce processus, - // sinon un filtre trop strict rendrait ce test toujours vert. Un `connect` - // UDP n'émet aucun paquet, mais la table l'affiche comme connecté. - // Sans route vers l'extérieur (bac à sable Nix), même ce `connect` échoue: - // le témoin est alors sans objet, et aucune connexion sortante n'est de - // toute façon possible. - let temoin = std::net::UdpSocket::bind("0.0.0.0:0").unwrap(); - if temoin.connect("198.51.100.7:9").is_ok() { - let vues = sortantes(); - assert!( - vues.iter().any(|v| v.contains("198.51.100.7:9")), - "socket témoin non détectée: {vues:?}" - ); - } else { - eprintln!("pas de route vers l'extérieur: témoin sauté"); - } - drop(temoin); - - let dossier = std::env::temp_dir().join(format!("rs-sortant-{}", std::process::id())); - let journal = rs_diag::initialiser(Some(&dossier.join("logs")), "info"); - - let hote = Hote::nouveau(Config { - version: "test".into(), - viewer_dir: None, - tls: false, - magasin: Some(rs_store::Magasin::new(dossier.join("reglages.json"))), - surcharges: Surcharges { - port: Some(0), - limite: None, - codec: None, - }, - journaux: journal.dossier.clone(), - demarrage_auto: None, - }) - .await; - hote.demarrer(SourceChoisie::Synthetique { - largeur: 64, - hauteur: 64, - }) - .await - .expect("partage d'une mire"); - - // Ce que l'hôte fait aussi à la demande de l'utilisateur. - let _ = hote.sources().await; - let _ = hote.interfaces(); - hote.diagnostics().expect("archive de diagnostics"); - - // On relit la table pendant que le serveur démarre, pas seulement après: - // une connexion brève passerait entre deux lectures tardives. - let fin = Instant::now() + Duration::from_millis(500); - let mut vues = Vec::new(); - while Instant::now() < fin { - vues.extend(sortantes()); - tokio::time::sleep(Duration::from_millis(5)).await; - } - hote.arreter().await; - let _ = std::fs::remove_dir_all(&dossier); - - vues.sort(); - vues.dedup(); - assert!( - vues.is_empty(), - "connexions sortantes au démarrage: {vues:?}" - ); -} diff --git a/crates/rs-session/tests/host.rs b/crates/rs-session/tests/host.rs new file mode 100644 index 0000000..d0488cb --- /dev/null +++ b/crates/rs-session/tests/host.rs @@ -0,0 +1,280 @@ +//! The host end to end: a real server, a viewer over WebSocket. +//! +//! What the interface displays must follow what really happens (#15, "no +//! button that lies"): a viewer that arrives shows up, a viewer disconnected +//! by the host leaves and does not come back with the same token, a busy port +//! is reported with a free port to suggest (#27). + +use std::time::Duration; + +use futures_util::{SinkExt, StreamExt}; +use rs_proto::{ClientMessage, DeviceId, DeviceInfo, PROTOCOL_VERSION, RoomId, SessionToken}; +use rs_session::{Config, Host, Overrides, Phase, SourceChoice}; +use tokio_tungstenite::tungstenite::Message; + +struct TempDir(std::path::PathBuf); + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +async fn host(name: &str, port: u16) -> (Host, TempDir) { + let dir = std::env::temp_dir().join(format!("rs-host-{name}-{}", std::process::id())); + let host = Host::new(Config { + version: "test".into(), + viewer_dir: None, + tls: false, + store: Some(rs_store::Store::new(dir.join("settings.json"))), + overrides: Overrides { + port: Some(port), + limit: None, + codec: None, + }, + log_dir: None, + autostart: None, + }) + .await; + (host, TempDir(dir)) +} + +fn test_pattern() -> SourceChoice { + SourceChoice::Synthetic { + width: 64, + height: 64, + } +} + +type Ws = + tokio_tungstenite::WebSocketStream>; + +/// Introduces itself as a viewer and returns the first message received. +async fn viewer(port: u16, room: &str, token: &str, id: &str) -> (Ws, serde_json::Value) { + let (mut ws, _) = tokio_tungstenite::connect_async(format!("ws://127.0.0.1:{port}/ws")) + .await + .expect("WebSocket"); + let hello = ClientMessage::Hello { + version: PROTOCOL_VERSION, + room: RoomId::parse(room).unwrap(), + token: SessionToken::new(token), + device: DeviceInfo { + id: DeviceId(id.into()), + name: format!("device {id}"), + user_agent: None, + platform: Some("test".into()), + }, + }; + ws.send(Message::text(serde_json::to_string(&hello).unwrap())) + .await + .unwrap(); + let first = next(&mut ws).await; + (ws, first) +} + +async fn next(ws: &mut Ws) -> serde_json::Value { + loop { + let message = tokio::time::timeout(Duration::from_secs(5), ws.next()) + .await + .expect("message expected") + .expect("stream open") + .expect("valid message"); + if let Message::Text(text) = message { + return serde_json::from_str(&text).unwrap(); + } + } +} + +/// Without a route to a network (Nix sandbox), no ICE candidate can be +/// advertised: the host then rightly refuses the media session. Tests that +/// need an admitted viewer have nothing to check. +fn no_network() -> bool { + let missing = rs_rtc::local_candidate_address().is_none(); + if missing { + eprintln!("no network route: viewer impossible, test skipped"); + } + missing +} + +fn identifiers(url: &str) -> (u16, String, String) { + // http://ip:port/r/?t=&v=1 + let (start, rest) = url.split_once("/r/").unwrap(); + let port = start.rsplit(':').next().unwrap().parse().unwrap(); + let (room, query) = rest.split_once("?t=").unwrap(); + let token = query.split('&').next().unwrap(); + (port, room.to_string(), token.to_string()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_viewer_appears_then_is_kicked_and_cannot_come_back() { + if no_network() { + return; + } + let (host, _dir) = host("kick", 0).await; + let mut states = host.subscribe(); + host.start(test_pattern()).await.expect("share"); + let share = host.state().share.expect("share described"); + assert!(share.qr_svg.starts_with(" (u16, serde_json::Value) { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let mut stream = tokio::net::TcpStream::connect(("127.0.0.1", port)) + .await + .unwrap(); + let request = format!( + "POST {path} HTTP/1.1\r\nHost: test\r\nContent-Type: application/json\r\n\ + Content-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + stream.write_all(request.as_bytes()).await.unwrap(); + let mut response = String::new(); + stream.read_to_string(&mut response).await.unwrap(); + let status = response[9..12].parse().unwrap(); + let json = response + .split_once("\r\n\r\n") + .map(|(_, body)| serde_json::from_str(body).unwrap_or_default()) + .unwrap_or_default(); + (status, json) +} + +#[tokio::test(flavor = "multi_thread")] +async fn the_short_code_opens_the_session_and_a_new_code_retires_the_old_one() { + let (host, _dir) = host("code", 0).await; + host.start(test_pattern()).await.unwrap(); + let share = host.state().share.unwrap(); + let (port, room, token) = identifiers(&share.url); + assert!(share.url.contains("&v=1"), "versioned link: {}", share.url); + assert_eq!(share.code.len(), 6); + assert!(share.expires_ms.is_some(), "60 minutes by default"); + assert!(!share.access_expired); + + // The code typed in uppercase with a space yields the room and the token. + let typed = format!( + "{} {}", + share.code[..3].to_uppercase(), + share.code[3..].to_uppercase() + ); + let (status, response) = post(port, "/api/code", &format!(r#"{{"code":"{typed}"}}"#)).await; + assert_eq!(status, 200, "{response}"); + assert_eq!(response["status"], "accepted"); + assert_eq!(response["room"], room); + assert_eq!(response["token"], token); + + let (status, response) = post(port, "/api/code", r#"{"code":"zzzzzz"}"#).await; + assert_eq!((status, &response["status"]), (404, &"unknown".into())); + + // New code: the old code and the old token say "expired", not "invalid", + // to a device that never got in. + assert!(host.regenerate_access()); + let fresh = host.state().share.unwrap(); + assert_ne!(fresh.code, share.code); + assert_ne!(fresh.url, share.url); + let (status, response) = post( + port, + "/api/code", + &format!(r#"{{"code":"{}"}}"#, share.code), + ) + .await; + assert_eq!((status, &response["status"]), (410, &"expired".into())); + let (_ws, refused) = viewer(port, &room, &token, "newcomer").await; + assert_eq!(refused["code"], "token_expired", "{refused}"); + + host.stop().await; +} diff --git a/crates/rs-session/tests/hote.rs b/crates/rs-session/tests/hote.rs deleted file mode 100644 index d26cee9..0000000 --- a/crates/rs-session/tests/hote.rs +++ /dev/null @@ -1,293 +0,0 @@ -//! L'hôte de bout en bout: un vrai serveur, un spectateur en WebSocket. -//! -//! Ce que l'interface affiche doit suivre ce qui se passe vraiment (#15, « pas -//! de bouton qui ment »): un spectateur qui arrive apparaît, un spectateur -//! déconnecté par l'hôte part et ne revient pas avec le même jeton, un port -//! pris se dit avec un port libre à proposer (#27). - -use std::time::Duration; - -use futures_util::{SinkExt, StreamExt}; -use rs_proto::{ClientMessage, DeviceId, DeviceInfo, PROTOCOL_VERSION, RoomId, SessionToken}; -use rs_session::{Config, Hote, Phase, SourceChoisie, Surcharges}; -use tokio_tungstenite::tungstenite::Message; - -struct Dossier(std::path::PathBuf); - -impl Drop for Dossier { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.0); - } -} - -async fn hote(nom: &str, port: u16) -> (Hote, Dossier) { - let dossier = std::env::temp_dir().join(format!("rs-hote-{nom}-{}", std::process::id())); - let hote = Hote::nouveau(Config { - version: "test".into(), - viewer_dir: None, - tls: false, - magasin: Some(rs_store::Magasin::new(dossier.join("reglages.json"))), - surcharges: Surcharges { - port: Some(port), - limite: None, - codec: None, - }, - journaux: None, - demarrage_auto: None, - }) - .await; - (hote, Dossier(dossier)) -} - -fn mire() -> SourceChoisie { - SourceChoisie::Synthetique { - largeur: 64, - hauteur: 64, - } -} - -/// Se présente comme un viewer et rend le premier message reçu. -async fn spectateur( - port: u16, - room: &str, - token: &str, - id: &str, -) -> ( - tokio_tungstenite::WebSocketStream>, - serde_json::Value, -) { - let (mut ws, _) = tokio_tungstenite::connect_async(format!("ws://127.0.0.1:{port}/ws")) - .await - .expect("WebSocket"); - let hello = ClientMessage::Hello { - version: PROTOCOL_VERSION, - room: RoomId::parse(room).unwrap(), - token: SessionToken::new(token), - device: DeviceInfo { - id: DeviceId(id.into()), - name: format!("appareil {id}"), - user_agent: None, - platform: Some("test".into()), - }, - }; - ws.send(Message::text(serde_json::to_string(&hello).unwrap())) - .await - .unwrap(); - let premier = suivant(&mut ws).await; - (ws, premier) -} - -async fn suivant( - ws: &mut tokio_tungstenite::WebSocketStream< - tokio_tungstenite::MaybeTlsStream, - >, -) -> serde_json::Value { - loop { - let message = tokio::time::timeout(Duration::from_secs(5), ws.next()) - .await - .expect("message attendu") - .expect("flux ouvert") - .expect("message valide"); - if let Message::Text(texte) = message { - return serde_json::from_str(&texte).unwrap(); - } - } -} - -/// Sans route vers un réseau (bac à sable Nix), aucun candidat ICE n'est -/// annonçable: l'hôte refuse alors la session média, à raison. Les tests qui -/// ont besoin d'un spectateur admis n'ont rien à vérifier. -fn sans_reseau() -> bool { - let absent = rs_rtc::local_candidate_address().is_none(); - if absent { - eprintln!("pas de route réseau: spectateur impossible, test sauté"); - } - absent -} - -fn identifiants(url: &str) -> (u16, String, String) { - // http://ip:port/r/?t=&v=1 - let (debut, suite) = url.split_once("/r/").unwrap(); - let port = debut.rsplit(':').next().unwrap().parse().unwrap(); - let (room, requete) = suite.split_once("?t=").unwrap(); - let token = requete.split('&').next().unwrap(); - (port, room.to_string(), token.to_string()) -} - -#[tokio::test(flavor = "multi_thread")] -async fn a_viewer_appears_then_is_kicked_and_cannot_come_back() { - if sans_reseau() { - return; - } - let (hote, _dossier) = hote("expulsion", 0).await; - let mut etats = hote.abonner(); - hote.demarrer(mire()).await.expect("partage"); - let partage = hote.etat().partage.expect("partage décrit"); - assert!(partage.qr_svg.starts_with(" (u16, serde_json::Value) { - use tokio::io::{AsyncReadExt, AsyncWriteExt}; - let mut flux = tokio::net::TcpStream::connect(("127.0.0.1", port)) - .await - .unwrap(); - let requete = format!( - "POST {chemin} HTTP/1.1\r\nHost: test\r\nContent-Type: application/json\r\n\ - Content-Length: {}\r\nConnection: close\r\n\r\n{corps}", - corps.len() - ); - flux.write_all(requete.as_bytes()).await.unwrap(); - let mut reponse = String::new(); - flux.read_to_string(&mut reponse).await.unwrap(); - let statut = reponse[9..12].parse().unwrap(); - let json = reponse - .split_once("\r\n\r\n") - .map(|(_, corps)| serde_json::from_str(corps).unwrap_or_default()) - .unwrap_or_default(); - (statut, json) -} - -#[tokio::test(flavor = "multi_thread")] -async fn the_short_code_opens_the_session_and_a_new_code_retires_the_old_one() { - let (hote, _dossier) = hote("code", 0).await; - hote.demarrer(mire()).await.unwrap(); - let partage = hote.etat().partage.unwrap(); - let (port, room, token) = identifiants(&partage.url); - assert!( - partage.url.contains("&v=1"), - "lien versionné: {}", - partage.url - ); - assert_eq!(partage.code.len(), 6); - assert!(partage.expire_ms.is_some(), "60 minutes par défaut"); - assert!(!partage.acces_expire); - - // Le code tapé en majuscules avec un espace rend la room et le jeton. - let saisie = format!( - "{} {}", - partage.code[..3].to_uppercase(), - partage.code[3..].to_uppercase() - ); - let (statut, reponse) = poster(port, "/api/code", &format!(r#"{{"code":"{saisie}"}}"#)).await; - assert_eq!(statut, 200, "{reponse}"); - assert_eq!(reponse["status"], "accepted"); - assert_eq!(reponse["room"], room); - assert_eq!(reponse["token"], token); - - let (statut, reponse) = poster(port, "/api/code", r#"{"code":"zzzzzz"}"#).await; - assert_eq!((statut, &reponse["status"]), (404, &"unknown".into())); - - // Nouveau code: l'ancien code et l'ancien jeton disent « expiré », pas - // « invalide », à un appareil qui n'est jamais entré. - assert!(hote.regenerer_acces()); - let neuf = hote.etat().partage.unwrap(); - assert_ne!(neuf.code, partage.code); - assert_ne!(neuf.url, partage.url); - let (statut, reponse) = poster( - port, - "/api/code", - &format!(r#"{{"code":"{}"}}"#, partage.code), - ) - .await; - assert_eq!((statut, &reponse["status"]), (410, &"expired".into())); - let (_ws, refus) = spectateur(port, &room, &token, "nouveau").await; - assert_eq!(refus["code"], "token_expired", "{refus}"); - - hote.arreter().await; -} diff --git a/crates/rs-session/tests/no_outbound_connection.rs b/crates/rs-session/tests/no_outbound_connection.rs new file mode 100644 index 0000000..31cb35c --- /dev/null +++ b/crates/rs-session/tests/no_outbound_connection.rs @@ -0,0 +1,173 @@ +//! Startup opens no connection outside the machine. +//! +//! No telemetry, no outbound call (ARCHITECTURE.md, ADR 0008). This test +//! replays what the binary does at startup (log on disk, server, LAN address, +//! diagnostics archive) and meanwhile rereads the socket table in +//! `/proc/self/net`: a socket **of this process** connected to an address +//! that is not local is a failure. The table covers the whole network +//! namespace (the machine's browser shows up there too): we keep only the +//! inodes this process holds, read from `/proc/self/fd`. +//! +//! A separate test file: each file in `tests/` is a process, so `/proc/self` +//! does not see the sockets of other tests running in parallel. +//! +//! `local_candidate_address` "connects" a UDP socket to 192.0.2.1 to read the +//! default route: a UDP `connect` sends no packet, and the address is reserved +//! for documentation (RFC 5737). It is therefore tolerated, and it alone. + +#![cfg(target_os = "linux")] + +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; +use std::time::{Duration, Instant}; + +use rs_session::{Config, Host, Overrides, SourceChoice}; + +/// Remote address of a `/proc/self/net/{tcp,udp}[6]` line. +fn remote(line: &str, v6: bool) -> Option { + let field = line.split_whitespace().nth(2)?; + let (ip, port) = field.split_once(':')?; + let port = u16::from_str_radix(port, 16).ok()?; + let ip = if v6 { + // Four 32-bit words, each in host order (little-endian). + let mut bytes = [0u8; 16]; + for i in 0..4 { + let word = u32::from_str_radix(ip.get(i * 8..i * 8 + 8)?, 16).ok()?; + bytes[i * 4..i * 4 + 4].copy_from_slice(&word.to_le_bytes()); + } + IpAddr::V6(Ipv6Addr::from(bytes)) + } else { + IpAddr::V4(Ipv4Addr::from( + u32::from_str_radix(ip, 16).ok()?.to_le_bytes(), + )) + }; + Some(SocketAddr::new(ip, port)) +} + +fn is_local(address: &SocketAddr) -> bool { + let ip = match address.ip() { + IpAddr::V6(v6) => v6.to_ipv4_mapped().map_or(IpAddr::V6(v6), IpAddr::V4), + v4 => v4, + }; + ip.is_unspecified() || ip.is_loopback() || ip == IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1)) +} + +/// Inodes of the sockets opened by this process (`socket:[12345]`). +fn our_sockets() -> std::collections::HashSet { + std::fs::read_dir("/proc/self/fd") + .into_iter() + .flatten() + .filter_map(Result::ok) + .filter_map(|e| std::fs::read_link(e.path()).ok()) + .filter_map(|target| { + target + .to_str()? + .strip_prefix("socket:[")? + .strip_suffix(']') + .map(str::to_string) + }) + .collect() +} + +/// The process sockets connected to a non-local address. +fn outbound() -> Vec { + let ours = our_sockets(); + let mut found = Vec::new(); + for (file, v6) in [ + ("tcp", false), + ("udp", false), + ("tcp6", true), + ("udp6", true), + ] { + let Ok(table) = std::fs::read_to_string(format!("/proc/self/net/{file}")) else { + continue; + }; + for line in table.lines().skip(1) { + // Tenth column: the socket inode. + let inode = line.split_whitespace().nth(9).unwrap_or_default(); + if !ours.contains(inode) { + continue; + } + if let Some(address) = remote(line, v6) + && !is_local(&address) + { + found.push(format!("{file} to {address}")); + } + } + } + found +} + +#[test] +fn proc_lines_are_parsed() { + // 127.0.0.1:8099 and [::1]:443, as the kernel writes them. + let v4 = "0: 0100007F:1FA3 0100007F:1F93 01 00000000:00000000"; + assert_eq!(remote(v4, false), Some("127.0.0.1:8083".parse().unwrap())); + let v6 = "0: 00000000000000000000000001000000:1FA3 00000000000000000000000001000000:01BB 01"; + assert_eq!(remote(v6, true), Some("[::1]:443".parse().unwrap())); + assert!(is_local(&"0.0.0.0:0".parse().unwrap())); + assert!(!is_local(&"93.184.216.34:443".parse().unwrap())); +} + +#[tokio::test(flavor = "multi_thread")] +async fn startup_opens_no_outbound_connection() { + // Control first: the detector must see a connection of this process, + // otherwise a filter that is too strict would keep this test always green. + // A UDP `connect` sends no packet, but the table shows it as connected. + // Without a route outside (Nix sandbox), even this `connect` fails: the + // control is then moot, and no outbound connection is possible anyway. + let control = std::net::UdpSocket::bind("0.0.0.0:0").unwrap(); + if control.connect("198.51.100.7:9").is_ok() { + let seen = outbound(); + assert!( + seen.iter().any(|v| v.contains("198.51.100.7:9")), + "control socket not detected: {seen:?}" + ); + } else { + eprintln!("no route outside: control skipped"); + } + drop(control); + + let dir = std::env::temp_dir().join(format!("rs-outbound-{}", std::process::id())); + let log = rs_diag::init(Some(&dir.join("logs")), "info"); + + let host = Host::new(Config { + version: "test".into(), + viewer_dir: None, + tls: false, + store: Some(rs_store::Store::new(dir.join("settings.json"))), + overrides: Overrides { + port: Some(0), + limit: None, + codec: None, + }, + log_dir: log.dir.clone(), + autostart: None, + }) + .await; + host.start(SourceChoice::Synthetic { + width: 64, + height: 64, + }) + .await + .expect("sharing a test pattern"); + + // What the host also does at the user's request. + let _ = host.sources().await; + let _ = host.interfaces(); + host.diagnostics().expect("diagnostics archive"); + + // The table is reread while the server starts, not only afterwards: a + // brief connection would slip between two late reads. + let end = Instant::now() + Duration::from_millis(500); + let mut seen = Vec::new(); + while Instant::now() < end { + seen.extend(outbound()); + tokio::time::sleep(Duration::from_millis(5)).await; + } + host.stop().await; + let _ = std::fs::remove_dir_all(&dir); + + seen.sort(); + seen.dedup(); + assert!(seen.is_empty(), "outbound connections at startup: {seen:?}"); +} diff --git a/crates/rs-signaling/Cargo.toml b/crates/rs-signaling/Cargo.toml index c11175c..2835422 100644 --- a/crates/rs-signaling/Cargo.toml +++ b/crates/rs-signaling/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rs-signaling" -description = "Serveur local axum: fichiers statiques, signalement, TLS auto-signé." +description = "Local axum server: static files, signaling, self-signed TLS." version.workspace = true edition.workspace = true rust-version.workspace = true diff --git a/crates/rs-signaling/assets/demo.html b/crates/rs-signaling/assets/demo.html index a01d555..254f1dc 100644 --- a/crates/rs-signaling/assets/demo.html +++ b/crates/rs-signaling/assets/demo.html @@ -1,5 +1,5 @@ - + @@ -20,11 +20,11 @@
rustscreen - - en attente + + waiting
-
aucune statistique
+
no statistics
diff --git a/crates/rs-signaling/assets/host.html b/crates/rs-signaling/assets/host.html index edfe6b3..501c7ed 100644 --- a/crates/rs-signaling/assets/host.html +++ b/crates/rs-signaling/assets/host.html @@ -1,19 +1,19 @@ - + - rustscreen: session en cours + rustscreen: session in progress