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

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

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

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

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

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

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

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

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

Closes #80

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

Refs #78

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 17:28:09 +01:00
Guillaume AssierandClaude Opus 5.5 fa9d75fe87 chore: 0.4.0, utilisable au quotidien
Release / Paquets et release (push) Failing after 6s
Version 0.4.0 dans le workspace, le viewer, la coque desktop et le paquet
Nix (dont le hash npm, qui suit la version du package-lock). Notes de
version dans docs/releases/v0.4.0.md, avec ce qui est vérifié et ce qui
ne l'est pas encore (basculement réseau, capot, trois écrans physiques).
Backlog: jalon 0.4.0 fermé.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 17:27:40 +01:00
renovate-bot 9099f22a63 fix(deps): update rust crate base64 to 0.23.0
renovate/artifacts Artifact file update failure
CI / Formatage, tests et builds (pull_request) Successful in 4m53s
2026-10-26 16:17:20 +00:00
renovate-bot 1ca03fe077 chore(deps): update rust crate tokio-tungstenite to 0.30.0
renovate/artifacts Artifact file update failure
CI / Formatage, tests et builds (pull_request) Successful in 3m2s
2026-10-26 15:18:15 +00:00
renovate-bot 90ac8a82da chore(deps): update pnpm to v12.15.0
renovate/artifacts Artifact file update failure
CI / Formatage, tests et builds (pull_request) Successful in 3m2s
2026-10-26 15:17:36 +00:00
Guillaume AssierandClaude Opus 5.5 99b8554eca feat: utilisable au quotidien, coque desktop et hôte robuste
CI / Formatage, tests et builds (push) Successful in 4m18s
L'hôte tient désormais dans rs-session::Hote: démarrer, arrêter,
déconnecter un spectateur, régler, et publier l'état complet à chaque
changement. Le binaire rustscreen passe dans rs-session et ne fait plus
que le piloter, comme la nouvelle coque Tauri (apps/desktop, pnpm).

- coque desktop: choix de la source avec vignettes, QR et lien, liste
  des spectateurs avec déconnexion et bannissement (#15)
- chaque moniteur RandR est proposé, l'encodeur suit un changement de
  résolution sans couper le partage, un écran débranché arrête le
  partage en disant pourquoi (#16)
- réglages persistants dans rs-store, écriture atomique, fichier
  corrompu mis de côté champ par champ (#23)
- port réglable, un port pris est signalé avec un port libre avant la
  demande de partage (#27)
- choix de l'interface réseau, serveur relancé quand son adresse
  change (#33)
- le viewer reprend seul au retour du réseau ou de la page, sans boucle
  infinie, et garde la qualité choisie (#39)
- inhibition de la veille et de l'écran pendant un partage (#41)
- capture relancée dans la même room après une veille (#42)

Corrige aussi un bug de la 0.3: le viewer appelait crypto.randomUUID,
absent d'une page servie en HTTP sur le LAN, si bien qu'aucun autre
appareil que l'hôte ne pouvait se connecter. L'identifiant d'appareil
est maintenant stable et sert à la déconnexion par l'hôte.

Closes #15, #16, #23, #27, #33, #39, #41, #42

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 15:32:03 +01:00
Guillaume Assier 5c39683453 Merge remote-tracking branch 'origin/main'
CI / Formatage, tests et builds (push) Successful in 5m34s
Release / Paquets et release (push) Failing after 6s
# Conflicts:
#	docs/backlog.md
2026-10-26 10:52:52 +01:00
Guillaume AssierandClaude Opus 5.5 cb3b44792b chore: 0.3.0, voir l'écran
Release / Paquets et release (push) Canceled after 0s
Version 0.3.0 dans le workspace, le viewer et le paquet Nix (dont le hash npm,
qui suit la version du package-lock). Notes de version dans
docs/releases/v0.3.0.md, avec ce qui est vérifié et ce qui ne l'est pas
encore (KDE, capture d'un écran existant sous GNOME). Backlog: jalon 0.3.0
fermé.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 10:51:28 +01:00
Guillaume AssierandClaude Opus 5.5 5bebd4c84e fix(nix): construire le flake pour de bon, avec la capture Wayland
Le flake n'avait jamais été construit. Sa première construction a demandé
cinq corrections:

- motifs de fonction sans `...` (appelés avec `system` en plus);
- chaîne crane réduite à rustc, sans cargo;
- shebangs de libvpx en /usr/bin/env, absent du bac à sable: les en-têtes
  rtcd sortaient vides;
- configure de libvpx qui ne retenait pas nasm (`--as=nasm`);
- pages HTML embarquées retirées par le filtre de sources.

Le paquet active la feature `pipewire` (bindgenHook, pipewire), le hash npm du
viewer est renseigné, et le verrou du flake est versionné. `nix build` produit
un binaire qui capture sous Wayland, tests passés dans le bac à sable;
`nix develop` compile le workspace avec PipeWire.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 10:44:04 +01:00
Guillaume AssierandClaude Opus 5.5 1f82d29f3b feat(capture): capturer un vrai écran sous Linux, et créer un second écran
Le produit voit enfin quelque chose de réel.

Wayland: le portail négocie la capture, rs-capture::pipewire consomme le flux
dans un thread dédié (feature `pipewire`, ADR 0009). Formats 8 bits seulement,
convertis en BGRA et testés avec une mire; mémoire partagée, sans DMA-BUF; la
dernière image est rendue à pas fixe, GNOME n'envoyant qu'au dommage.

Écran virtuel: `rustscreen --virtuel --size LxH` demande au portail le type de
source VIRTUAL. La décision se lit dans AvailableSourceTypes, pas dans le nom
du bureau: GNOME 46 l'annonce, contrairement à ce que disait la doc. Vérifié
sur GNOME 46: écran 1280x800 créé, images reçues par un navigateur, première
image en 145 ms.

X11: x11rb en pur Rust, MIT-SHM par memfd, écran entier ou fenêtre précise
via Composite (`--lister`, `--fenetre`). Vérifié contre Xephyr.

Le chemin se choisit selon la session et se force par RUSTSCREEN_CAPTURE ou
`--source`. La révocation (signal Closed du portail, ou flux PipeWire perdu)
arrête l'encodage au lieu de réessayer, est journalisée, et rustscreen sort en
code 3.

La négociation du portail avait trois défauts que seule une vraie session a
révélés: corps D-Bus emballé dans une variante (InvalidArgs), méthodes
appelées sur l'objet session, et descripteur attendu dans la réponse de Start
alors qu'il vient d'OpenPipeWireRemote. Jetons de requête désormais uniques.

Diagnostics branchés: événements nommés (session_ouverte,
candidat_ice_retenu, premiere_image, changement_qualite, deconnexion avec sa
cause, capture_revoquee), `--diagnostics`, bouton du tableau de bord sur
/api/diagnostics réservé au loopback, et un test qui vérifie qu'aucune
connexion sortante n'est ouverte au démarrage.

La release exige désormais libpipewire-0.3-dev et libclang-dev sur le runner:
une AppImage sans PipeWire ne capturerait rien sous Wayland. La CI exerce la
feature quand la bibliothèque est présente.

Closes #6
Closes #10
Closes #60

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 10:43:57 +01:00
Guillaume AssierandClaude Opus 5.5 3c8d518f5a feat(diag): journal structuré local et archive de diagnostics
Nouveau crate rs-diag, sans télémétrie ni appel réseau (ADR 0008):

- tracing vers la console au format lisible, et vers des fichiers JSON (un
  événement par ligne) en rotation quotidienne, sept fichiers gardés, dans
  ~/.local/state/rustscreen/logs (RUSTSCREEN_LOG_DIR pour en changer);
- une archive zip fermée: manifest.json (version, système, réseau sans
  adresse MAC, sections fournies par l'appelant) et les journaux les plus
  récents sous un plafond de 5 Mo;
- l'expurgation des adresses MAC et des jetons de session (t=...) avant
  écriture, testée sur des cas qui ressemblent à une MAC sans en être une
  (IPv6, heures).

Le branchement dans le binaire et le serveur vient avec la capture.

Refs #6

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 10:43:43 +01:00
Guillaume AssierandClaude Opus 5.5 65da0c9e6d docs(adr): valider les ADR et trancher les décisions restantes
Relecture des cinq ADR structurantes, chacune datée et dotée d'une condition
de réouverture. Les écarts avec le code sont corrigés: la 0005 décrivait du TLS
par défaut alors que la décision #65 a fait du HTTP en clair sur le LAN le mode
par défaut, l'empreinte n'a jamais été dans le QR, et le périmètre de la 0003
est désormais Linux pour la 1.0.

Les trois décisions ouvertes ont leur ADR:

- 0006: signalement en JSON sur WebSocket, types générés depuis rs-proto;
- 0007: reprise par renégociation complète, pas de reprise ICE;
- 0008: diagnostics en archive zip expurgée, produite à la demande.

La 0009 consigne la capture Linux (PipeWire derrière une feature, X11 en
repli) et l'écran virtuel par le portail. ARCHITECTURE.md lie toutes les ADR.

Closes #2

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 10:43:30 +01:00
Guillaume Assier fdcc3f31a9 docs: capture Windows en p3, cohérente avec son jalon
CI / Formatage, tests et builds (push) Successful in 1m33s
#8 portait `priority/p0` dans le jalon « 1.x Après 1.0 » : la carte se
retrouvait en tête d'un tableau dont tout le propos est d'être après la 1.0,
et le ROADMAP dit l'inverse depuis le début (Windows est la deuxième cible,
parquée en 1.x parce que son coût administratif n'a de sens qu'une fois le
produit debout sur Linux). L'étiquette était la seule à contredire le jalon.

Passe en p3, et ouvre la file des « plus tard » : c'est le chantier qui élargit
la plateforme, avant l'audio, le contrôle à distance et les extras.
2026-10-26 09:01:04 +00:00
Guillaume Assier 4f26e06c44 docs: un tableau de projet par jalon, ordre de lecture explicite
CI / Formatage, tests et builds (push) Successful in 1m43s
Le tableau unique « Roadmap 1.0 » entassait les cinquante issues ouvertes dans
une seule colonne « À faire », dans un ordre qui ne voulait rien dire, et les
jalons étaient invisibles. On ne pouvait donc pas répondre à « qu'est-ce que je
fais maintenant » autrement qu'en ouvrant chaque ticket.

- Projets du dépôt : un tableau par jalon, titré du nom du jalon, créés dans
  l'ordre des releases pour que les onglets se lisent dans cet ordre.
- Colonnes : `En cours`, puis `P0 bloquant`, `P1 haute`, `P2 normale`,
  `P3 basse`. L'ordre des cartes dans une colonne est l'ordre de travail.
- Trois issues ouvertes n'avaient pas de priorité et se retrouvaient sans
  colonne possible : #67 en p2, #69 en p1, #70 en p1, avec leur nature.
- ROADMAP.md décrit ce mode de lecture au lieu du projet disparu, et
  backlog.md est régénéré depuis le tracker en ordre de release.
2026-10-26 08:35:15 +00:00
renovate-bot 374e4e9143 chore(deps): update actions/checkout action to v7
CI / Formatage, tests et builds (pull_request) Successful in 2m58s
2026-10-25 18:17:30 +00:00
heap 871c2fbb1b Merge pull request 'chore: Configure Renovate' (#68) from renovate/configure into main
CI / Formatage, tests et builds (push) Successful in 3m19s
Reviewed-on: #68
2026-10-25 17:31:17 +00:00
heap 235e9174d8 Merge branch 'main' into renovate/configure
CI / Formatage, tests et builds (pull_request) Successful in 4m24s
2026-10-25 17:31:13 +00:00
Guillaume Assier c5de06628f feat(platform): négocier une capture avec le portail, jusqu'au descripteur
CI / Formatage, tests et builds (push) Successful in 2m58s
Première brique du cas d'usage: demander un écran au portail Wayland et obtenir
le flux, sans tirer libpipewire.

La séquence est complète: `CreateSession`, `SelectSources` (moniteurs, sélection
unique, curseur inclus, mode persistant), puis `Start`, dont la réponse porte le
descripteur PipeWire. L'abonnement au signal `Response` précède chaque appel: le
signal peut partir avant qu'on ne s'abonne, et une réponse perdue se traduirait
par un blocage de deux minutes.

Trois détails qui coûtent cher quand on les ignore:

- le chemin de l'objet request se dérive du nom unique sur le bus (`:1.42`
  devient `1_42`) et du jeton, qui est validé avant l'appel: un caractère
  interdit doit être refusé ici, pas par un « invalid object path » du bus;
- le descripteur arrive comme valeur possédée de type `h`. On en duplique une
  copie (`dup`) puis on transfère sa propriété, parce que l'original appartient
  à la réponse D-Bus et sera fermé avec elle. Sans la duplication, le premier
  nettoyage fermerait le flux sous nos pieds;
- `Start` prend trois arguments (session, fenêtre parente, options), les deux
  autres un seul. Un corps générique construit à la va-vite passait la
  compilation et échouait à l'exécution.

`--test-portail` exerce la négociation seule: session, sélecteur, flux, et
referme. Sur une machine sans portail, il rend une erreur lisible et sort en 1,
sans bloquer. C'est le critère de sortie de l'issue #10 pour cette étape.

La consommation des images (négociation de format, buffers) demandera
`libpipewire`, qui n'est pas installée ici: elle vient après, et se vérifiera sur
une machine avec un bureau.
2026-10-25 17:18:51 +00:00
Guillaume Assier be1b368620 docs: feuille de route vers la 1.0 et jalons de release
CI / Formatage, tests et builds (push) Successful in 13m31s
Sept releases planifiées de 0.3.0 à 1.0.0, avec un critère de sortie par version
plutôt qu'un compteur d'issues fermées.

Le chemin critique est explicite: la capture Wayland (#10) et la sortie virtuelle
(#60) conditionnent tout le reste, et la validation sur une machine réelle est le
vrai goulot.

Ce qui ne conditionne pas le cas d'usage est parqué dans un jalon 1.x: audio,
contrôle, transfert de fichiers, branding, Windows. Une 1.0 qui attend toutes
les fonctions n'arrive jamais.

Les anciens jalons thématiques M0 à M5 et Extensions sont supprimés: garder deux
systèmes de jalons en parallèle garantit que personne ne saura lequel fait foi.
2026-10-25 15:27:27 +00:00
Guillaume Assier bec86b78b0 feat(platform): sonder le portail d'enregistrement d'écran
Sous Wayland, aucune application ne lit l'écran directement: elle demande au
portail, qui affiche un sélecteur et rend un flux PipeWire. Sans portail, il n'y
a pas de capture, et il vaut mieux l'apprendre au démarrage que devant un écran
noir.

Le module interroge org.freedesktop.portal.ScreenCast et lit sa version, sans
déclencher de demande de consentement: lire une version ne demande aucune
autorisation. La version 4 est le seuil pour demander une sortie virtuelle.

Périmètre acté au passage: Wayland est la cible, X11 devient un bonus assumé
(evdi, droits root, module noyau) qui ne bloque aucune livraison. macOS sort du
périmètre, Windows viendra après la 1.0.

Sur cette machine, sans portail, le chemin d'erreur est exercé et le test dit
explicitement qu'il accepte les deux issues: il vérifie le comportement, pas
l'environnement.
2026-10-25 15:27:27 +00:00
renovate-bot ab6fab46b0 Add renovate.json
CI / Formatage, tests et builds (pull_request) Successful in 6m2s
2026-10-25 15:18:34 +00:00
Guillaume Assier 7e066c3b9e feat(platform): dire au démarrage quel écran virtuel est possible
CI / Formatage, tests et builds (push) Successful in 3m25s
Le cas d'usage principal est d'étendre le bureau sur une tablette. Sous Linux,
cela dépend entièrement du compositeur: KDE Wayland sait créer une sortie
virtuelle sans droits particuliers, wlroots aussi, GNOME Wayland non, X11 passe
par evdi et un module noyau.

Le module `display` de rs-platform lit XDG_SESSION_TYPE, XDG_CURRENT_DESKTOP et
les sockets présents, en déduit le type de session, le bureau et le backend
d'écran virtuel utilisable. La détection est injectable, donc testable sans
session graphique: neuf tests couvrent KDE (dont plasmawayland), sway sans nom de
bureau, GNOME assumé non supporté, X11, l'inférence par socket quand
XDG_SESSION_TYPE manque, et l'absence d'environnement.

Le binaire l'annonce au démarrage, avec un conseil lisible. Sur une machine sans
serveur graphique, il dit simplement qu'il n'y a rien à capturer.

Ce n'est pas la fonctionnalité, c'est le diagnostic qui la précède: la capture
réelle (issue #10) et la création de la sortie (#60) restent à écrire.
2026-10-25 15:06:23 +00:00
Guillaume Assier 6d3d15d65c docs: faisabilité de l'écran virtuel, condition du vrai second écran
CI / Formatage, tests et builds (push) Successful in 1m13s
Le cas d'usage principal est d'étendre le bureau sur une tablette, pas de
dupliquer l'écran existant. La différence n'est pas cosmétique: sans moniteur
branché, la sortie d'affichage disparaît, et il n'y a plus rien à capturer.

Trois voies documentées: krfb-virtualmonitor et wlroots headless sous Linux,
IddCx sous Windows (signature de pilote obligatoire, coût récurrent), et
CGVirtualDisplay sous macOS (API privée, risque de rupture).

Conséquence: #60 passe devant les codecs. Tant qu'il n'existe pas, le produit
est un miroir.
2026-10-25 14:46:25 +00:00
Guillaume Assier 6655d99f3d feat(codec): VP9 dans l'encodeur, pas encore dans le produit
CI / Formatage, tests et builds (push) Successful in 1m24s
L'encodeur sait produire du VP9 et le transport sait l'annoncer. Mesuré sur le
papier, VP9 coûte 1,42x le temps de calcul de VP8 pour 35 % de bande passante en
moins: c'est un gain, et le code est prêt.

Il n'est pas exposé, parce que deux mesures en conditions réelles disent non.

1. libvpx garde 25 images en file pour VP9 (`g_lag_in_frames`), que `vpx-encode`
   ne permet pas de régler. Le premier paquet sort à la frame 24: environ 800 ms
   de latence à 30 i/s, rédhibitoire pour du partage d'écran.
2. Le flux n'est pas décodé côté navigateur. Cinq spectateurs en 640x360: trois
   passent « en direct » avec un débit annoncé, aucune image n'arrive
   (`videoWidth` à 0). Type de charge utile et mode de packetisation VP9 restent
   à instruire.

Ce qui est en place et testé: `VideoCodec` (Vp8/Vp9), `EncodeConfig::codec`,
`VpxEncoder` qui encode réellement en VP9, `SharedMedia::codec()` propagé jusqu'à
`Session::new`, qui n'annonce en SDP que le codec réellement encodé.

Ce dernier point n'est pas cosmétique: proposer VP9 en envoyant du VP8 donne un
écran noir côté spectateur, sans erreur nulle part. Avant, la session prenait le
premier type de charge utile disponible, ce qui marchait par chance de l'ordre
d'annonce.

`request_keyframe` est maintenant réellement implémenté (réouverture de
l'encodeur, faute d'accès au drapeau `VPX_EFLAG_FORCE_KF`): un spectateur qui
rejoint n'attend plus la prochaine image clé périodique.

L'issue #67 porte le plan: encodeur sur `vpx-sys` pour maîtriser lag et images
clés, choix explicite du type de charge utile, vérification du décodage dans
Chromium. Un mode qui ajoute 800 ms et affiche du noir n'est pas une
fonctionnalité.
2026-10-25 14:45:09 +00:00
Guillaume Assier f7da2d44ae bench(codec): mesurer VP9 et AV1 avant de les adopter
CI / Formatage, tests et builds (push) Successful in 1m20s
Banc d'essai qui encode une image de type bureau avec chaque codec disponible
et rend la cadence et la bande passante obtenues.

Résultat, 720p, 1 vCPU: VP9 coûte 1,42x le temps de calcul de VP8 et rend 35 %
de bande passante en moins, avec encore 43 i/s de marge pour une cible de 30.
AV1 logiciel: libaom tombe à 7 i/s, SVT-AV1 tient le temps réel au preset le
plus rapide mais sans contrôle de débit fin.

La feature vp9 de vpx-encode est activée: libvpx compilé ici contient déjà
l'encodeur VP9, il n'y a rien à reconstruire.
2026-10-25 14:34:34 +00:00
Guillaume Assier 8a40837106 docs: backlog à jour (plusieurs spectateurs livrés)
CI / Formatage, tests et builds (push) Successful in 1m19s
2026-10-25 12:48:02 +00:00
Guillaume Assier b7df0e9f22 chore: 0.2.0, plusieurs spectateurs sur une source partagée
CI / Formatage, tests et builds (push) Successful in 1m22s
Release / Paquets et release (push) Successful in 59s
2026-10-25 12:47:43 +00:00
Guillaume Assier f35dc413e9 feat(codec): une capture et un encodeur pour tous les spectateurs
CI / Formatage, tests et builds (push) Successful in 2m23s
Chaque spectateur créait sa propre source média, donc sa propre capture et son
propre encodeur VP8. Trois spectateurs en 720p se disputaient un cœur: mesuré à
16,3 et 15,9 i/s, avec la troisième connexion qui échouait et une charge système
de 2,5 pour un seul cœur.

`rs-codec::SharedMedia` remplace la fabrique par spectateur: la capture et
l'encodeur vivent dans un thread unique, et `subscribe()` rend une `SourceView`
par session, avec son propre curseur sur la dernière image publiée. Les frames
encodées sont partagées en `Arc`, donc le coût par spectateur se réduit au
fan-out RTP.

Un spectateur qui rejoint demande une image clé au prochain encodage: sans elle,
son décodeur attendrait la suivante, parfois plusieurs secondes. La demande
passe par un drapeau atomique que le thread d'encodage consomme.

Le rejeu IVF passe par le même trait (`SharedPlayback`), avec les frames en
mémoire et un curseur par abonné.

Mesures, 1 vCPU, 720p:

- 3 spectateurs: 29,8 / 27,1 / 29,7 i/s, tous en direct (avant: 16,3 / 15,9 /
  échec)
- 5 spectateurs en 640x360: 30,0 i/s chacun, tous en direct
- 5 spectateurs en 720p: le serveur les admet tous, mais le navigateur ne peut
  pas décoder cinq flux 720p pendant que la machine encode. Ce n'est pas une
  limite du partage, c'est la capacité d'un cœur, et docs/perf.md le dit.

Tests ajoutés: deux abonnés reçoivent des frames sans doubler le nombre
d'encodages, un abonné qui part est désenregistré, un rejeu partagé donne un
curseur indépendant à chacun.
2026-10-25 12:45:52 +00:00
202 changed files with 28486 additions and 1841 deletions

No files matched your search

+77 -50
View File
@@ -1,20 +1,19 @@
# Chaîne d'intégration continue de rustscreen.
# rustscreen continuous integration.
#
# Elle tourne sur Gitea, sur le runner `rustscreen-ci`, qui est un hôte et non un
# conteneur : la machine n'a pas de démon Docker, mais elle a cargo, node et
# nasm. Ce runner est enregistré pour ce dépôt : celui d'Exoledge ne voit que les
# jobs de l'organisation Exoledge, et rustscreen vit sous `heap`. Le label est explicite pour qu'un changement d'environnement se voie
# dans le diff plutôt qu'en pleine exécution.
# It runs on Gitea, on the `rustscreen-ci` runner, which is a host and not a
# container: the machine has no Docker daemon, but it has cargo, node and nasm.
# This runner is registered for this repository: Exoledge's only sees jobs from
# the Exoledge organization, and rustscreen lives under `heap`. The label is
# explicit so that an environment change shows up in the diff rather than in
# the middle of a run.
#
# Deux précautions qui coûtent cher quand on les oublie :
# Two precautions that cost a lot when forgotten:
#
# - libvpx n'est pas fourni par le système. `env-libvpx-sys` exige un préfixe
# explicite, donc la chaîne construit libvpx une fois dans le cache et le
# réutilise. Sans ce cache, chaque exécution repaierait dix minutes de
# compilation C.
# - les caches sont rangés par dépôt. Le runner est partagé avec d'autres
# projets : un `CARGO_TARGET_DIR` commun ferait se marcher dessus des
# compilations qui n'ont rien à voir.
# - libvpx is not provided by the system. `env-libvpx-sys` requires an explicit
# prefix, so the pipeline builds libvpx once into the cache and reuses it.
# Without that cache, every run would pay ten minutes of C compilation again.
# - caches are kept per repository. The runner is shared with other projects:
# a common `CARGO_TARGET_DIR` would make unrelated builds trample each other.
name: CI
@@ -27,17 +26,17 @@ permissions:
contents: read
jobs:
integrer:
name: Formatage, tests et builds
integrate:
name: Formatting, tests and builds
runs-on: rustscreen-ci
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: Outils et caches
- name: Tools and caches
run: |
set -euo pipefail
# Les caches vivent hors du dépôt, et le répertoire est propre à ce
# projet: la machine de la chaîne est partagée avec d'autres.
# Caches live outside the repository, in a directory specific to this
# project: the CI machine is shared with others.
cache="${RUSTSCREEN_CACHE_DIR:-$HOME/.cache/rustscreen-ci}"
mkdir -p "$cache"
{
@@ -45,9 +44,9 @@ jobs:
echo "VPX_PREFIX=$cache/libvpx"
echo "npm_config_cache=$cache/npm"
} >> "$GITHUB_ENV"
# nasm, file et desktop-file-validate peuvent être installés par
# l'administrateur du runner dans ~/.local/bin, hors du PATH de la
# session. Absents, la chaîne se replie sur ce que le système fournit.
# nasm, file and desktop-file-validate may be installed by the runner's
# administrator in ~/.local/bin, outside the session PATH. When they
# are missing there, the pipeline falls back on what the system provides.
if [ -d "$HOME/.local/bin" ]; then
echo "PATH=$HOME/.local/bin:$PATH" >> "$GITHUB_ENV"
fi
@@ -60,15 +59,15 @@ jobs:
cargo fmt --version
node --version
npm --version
nasm -v || echo "nasm absent: libvpx sera construit sans assembleur, encodage plus lent"
nasm -v || echo "nasm missing: libvpx will be built without an assembler, slower encoding"
- name: Bibliothèque libvpx
- name: libvpx library
run: |
set -euo pipefail
# La version est figée par le script : au-delà de 1.13, les bindings
# pré-générés de `env-libvpx-sys` ne suffisent plus.
# The version is pinned by the script: beyond 1.13, the pre-generated
# bindings of `env-libvpx-sys` are no longer enough.
if [ -f "$VPX_PREFIX/lib/libvpx.a" ]; then
echo "libvpx déjà construite dans $VPX_PREFIX"
echo "libvpx already built in $VPX_PREFIX"
else
./scripts/build-libvpx.sh "$VPX_PREFIX"
fi
@@ -78,59 +77,87 @@ jobs:
echo "VPX_VERSION=1.13.0"
} >> "$GITHUB_ENV"
- name: Dépendances du viewer
- name: Viewer dependencies
run: |
set -euo pipefail
cd apps/viewer
# `npm ci` plutôt que `npm install` : le fichier de verrouillage est la
# référence, la chaîne ne négocie aucune version.
# `npm ci` rather than `npm install`: the lock file is the reference,
# the pipeline negotiates no version.
npm ci --no-audit --no-fund
- name: Lint et types du viewer
- name: Viewer lint and types
run: |
set -euo pipefail
cd apps/viewer
npm run lint
npx tsc --noEmit
- name: Tests du viewer
- name: Viewer tests
run: |
set -euo pipefail
cd apps/viewer
npm test
- name: Bundle du viewer
- name: Viewer bundle
run: |
set -euo pipefail
cd apps/viewer
npm run build
- name: Formatage
- name: Formatting
run: cargo fmt --all --check
- name: Clippy
run: cargo clippy --workspace --all-targets -- -D warnings
- name: Tests
run: cargo test --workspace -- --skip export_bindings
# The `export_bindings` tests write the TypeScript types: they run
# here, with the rest, and the "up to date" step only compares. A
# second cargo invocation, with different features, rebuilt half of
# the workspace (34 s, #78).
run: cargo test --workspace
- name: Binaire de publication
- name: Wayland capture (PipeWire)
run: |
set -euo pipefail
# La chaîne ne se contente pas de tester : elle vérifie que le binaire
# se construit et démarre, parce qu'un produit qui ne démarre pas passe
# tous les tests unitaires.
cargo build --release -p rs-signaling --bin rustscreen
"$CARGO_TARGET_DIR/release/rustscreen" --version
# The feature requires libpipewire-0.3 and libclang (bindgen). The
# runner does not always have them: without them, the step says so and
# passes, and the release is the one that fails (see release.yml).
if pkg-config --exists libpipewire-0.3; then
cargo clippy -p rs-capture -p rs-session --features rs-session/pipewire --all-targets -- -D warnings
cargo test -p rs-capture --features pipewire
else
echo "libpipewire-0.3 missing on the runner: Wayland capture not checked"
fi
- name: Le protocole TypeScript est à jour
- name: The binary starts
run: |
set -euo pipefail
# Les types du protocole sont générés depuis Rust. Un écart entre le
# dépôt et la génération veut dire que le viewer compile contre une
# version périmée du protocole, ce qui ne se voit qu'en production.
cargo test -p rs-proto export_bindings >/dev/null
git diff --exit-code -- apps/viewer/src/proto || {
echo "apps/viewer/src/proto n'est pas à jour : lancer make proto et commiter" >&2
# The pipeline does not stop at tests: it checks that the binary
# starts, because a product that does not start passes every unit
# test. The integration tests have already built it.
"$CARGO_TARGET_DIR/debug/rustscreen-cli" --version
- name: Release binary
# On main only: the whole stack in release costs more than a minute,
# and the release workflow rebuilds it anyway (#78).
if: github.event_name == 'push'
run: |
set -euo pipefail
cargo build --release -p rs-session --bin rustscreen-cli
"$CARGO_TARGET_DIR/release/rustscreen-cli" --version
- name: The TypeScript protocol is up to date
run: |
set -euo pipefail
# The protocol types are generated from Rust. A gap between the
# repository and the generated output means the viewer compiles
# against a stale protocol, which only shows in production.
# Written by the "Tests" step: all that is left is to compare.
# `status` rather than `diff`: a new type, never committed, counts too.
drift=$(git status --porcelain -- apps/viewer/src/proto apps/desktop/src/bindings)
if [ -n "$drift" ]; then
echo "$drift" >&2
echo "generated TypeScript types are out of date: run make proto and commit" >&2
exit 1
}
fi
+45 -38
View File
@@ -1,14 +1,14 @@
# Publication : une étiquette `vX.Y.Z` produit une release avec ses artefacts.
# Release: a `vX.Y.Z` tag produces a release with its artifacts.
#
# Rien d'autre ne déclenche cette chaîne: pas de bouton, pas de commande tapée
# sur un portable, et pas de numéro de version écrit à la main dans un fichier.
# L'étiquette git est la seule source de la version; le binaire et l'AppImage en
# découlent, et la release dit ce qu'elle contient.
# Nothing else triggers this pipeline: no button, no command typed on a laptop,
# and no version number written by hand in a file. The git tag is the single
# source of the version; the binary and the AppImage follow from it, and the
# release states what it contains.
#
# Elle vérifie d'abord que l'étiquette correspond à la version déclarée dans le
# `Cargo.toml`: une release `v0.2.0` construite sur un `Cargo.toml` en `0.1.0`
# mentirait sur son contenu, et c'est le genre d'erreur qu'on ne voit qu'après
# avoir distribué le paquet.
# It first checks that the tag matches the version declared in `Cargo.toml`: a
# `v0.2.0` release built from a `Cargo.toml` at `0.1.0` would lie about its
# contents, and that is the kind of mistake only noticed after the package has
# been distributed.
name: Release
@@ -21,20 +21,20 @@ permissions:
jobs:
release:
name: Paquets et release
name: Packages and release
runs-on: rustscreen-ci
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
with:
# `git describe` et l'historique depuis l'étiquette précédente ont
# besoin des étiquettes, que le clone superficiel ne prend pas.
# `git describe` and the history since the previous tag need the
# tags, which a shallow clone does not fetch.
fetch-depth: 0
- name: Outils et caches
- name: Tools and caches
run: |
set -euo pipefail
# Les caches vivent hors du dépôt, et le répertoire est propre à ce
# projet: la machine de la chaîne est partagée avec d'autres.
# Caches live outside the repository, in a directory specific to this
# project: the CI machine is shared with others.
cache="${RUSTSCREEN_CACHE_DIR:-$HOME/.cache/rustscreen-ci}"
mkdir -p "$cache"
{
@@ -42,26 +42,26 @@ jobs:
echo "VPX_PREFIX=$cache/libvpx"
echo "npm_config_cache=$cache/npm"
} >> "$GITHUB_ENV"
# nasm, file et desktop-file-validate peuvent être installés par
# l'administrateur du runner dans ~/.local/bin, hors du PATH de la
# session. Absents, la chaîne se replie sur ce que le système fournit.
# nasm, file and desktop-file-validate may be installed by the runner's
# administrator in ~/.local/bin, outside the session PATH. When they
# are missing there, the pipeline falls back on what the system provides.
if [ -d "$HOME/.local/bin" ]; then
echo "PATH=$HOME/.local/bin:$PATH" >> "$GITHUB_ENV"
fi
- name: Version et étiquette
- name: Version and tag
run: |
set -euo pipefail
etiquette="${GITHUB_REF_NAME#v}"
declaree=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)
if [ "$etiquette" != "$declaree" ]; then
echo "étiquette v$etiquette mais Cargo.toml déclare $declaree" >&2
tag="${GITHUB_REF_NAME#v}"
declared=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)
if [ "$tag" != "$declared" ]; then
echo "tag v$tag but Cargo.toml declares $declared" >&2
exit 1
fi
echo "VERSION=$etiquette" >> "$GITHUB_ENV"
echo "version $etiquette confirmée"
echo "VERSION=$tag" >> "$GITHUB_ENV"
echo "version $tag confirmed"
- name: Bibliothèque libvpx
- name: libvpx library
run: |
set -euo pipefail
if [ ! -f "$VPX_PREFIX/lib/libvpx.a" ]; then
@@ -80,14 +80,21 @@ jobs:
npm ci --no-audit --no-fund
npm run build
- name: Binaire
- name: Binary
run: |
set -euo pipefail
cargo build --release -p rs-signaling --bin rustscreen
# Le binaire est distribué: ses symboles ne servent qu'aux diagnostics
# de développement et pèsent la moitié du fichier.
strip "$CARGO_TARGET_DIR/release/rustscreen"
"$CARGO_TARGET_DIR/release/rustscreen" --version
# A binary released without PipeWire captures nothing under Wayland,
# the product's target (ADR 0009): the release fails rather than ship
# it. The runner needs libpipewire-0.3-dev and libclang-dev.
if ! pkg-config --exists libpipewire-0.3; then
echo "libpipewire-0.3 not found: install libpipewire-0.3-dev and libclang-dev on the runner" >&2
exit 1
fi
cargo build --release -p rs-session --features pipewire --bin rustscreen-cli
# The binary is distributed: its symbols only help development
# diagnostics and weigh half of the file.
strip "$CARGO_TARGET_DIR/release/rustscreen-cli"
"$CARGO_TARGET_DIR/release/rustscreen-cli" --version
- name: AppImage
run: |
@@ -96,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"
+122 -9
View File
@@ -11,12 +11,35 @@ TypeScript. Le spectateur n'installe rien : il ouvre une URL, éventuellement sc
code. La cible fonctionnelle est le plan **Pro** de Deskreen, plus les fonctions Teams qui ne
dépendent pas d'un service en ligne.
Ce qui tourne: capture synthétique, conversion BGRA vers I420, encodage VP8, session str0m par
spectateur, serveur local avec jeton, viewer React. Ce qui manque: la capture réelle par OS, la
coque desktop Tauri, et l'encodeur matériel.
Ce qui tourne: capture Linux réelle (portail et PipeWire sous Wayland, X11 en repli, chaque
moniteur RandR, une fenêtre seule), écran virtuel par le portail (GNOME 46, KDE), conversion BGRA
vers I420, encodage VP8 ou VP9 temps réel qui suit les changements de résolution, session str0m par
spectateur, serveur local avec jeton qui expire et code court, viewer React qui reprend seul après
une coupure ou une veille, tourne l'image et suit le thème, coque desktop Tauri avec icône de
barre système, réglages persistants, interface en français et en anglais, inhibition de veille,
journal JSON local et archive de diagnostics.
Ce qui manque: la capture Windows et macOS, l'encodeur matériel, et la traduction des messages
produits par l'hôte (erreurs, avertissements), aujourd'hui en anglais seulement (#75).
L'hôte tient dans `rs-session::Host`: démarrer, arrêter, déconnecter un spectateur, régler, et
publier l'état complet à chaque changement. Lancer `rustscreen` ouvre l'application de bureau
(`apps/desktop/src-tauri`); la ligne de commande est `rustscreen-cli`
(`rs-session/src/bin/rustscreen-cli.rs`). Les deux ne font que piloter l'hôte: aucune ne connaît
la capture ni le serveur.
## Conventions
### Langue
- **Le code est en anglais**: identifiants, noms de fichiers et de modules, commentaires, messages
et noms d'événements du journal, messages d'erreur, sorties de `rustscreen-cli`, scripts (#83).
- **Les textes affichés à l'utilisateur** passent par `locales/` (français et anglais), jamais en dur.
- **La documentation** (`docs/`, ce fichier, `README.md`) **et les messages de commit** restent en
français.
- Un format déjà écrit chez l'utilisateur garde ses anciens noms en lecture: alias `serde` des
réglages, `reglages.json` relu à défaut de `settings.json`, anciennes clés `localStorage`,
anciennes options de la ligne de commande, ancien fichier de restauration du portail.
### Rust
- Édition 2024, un crate par domaine sous `crates/`, préfixe `rs-`. Le spike jetable est sous
@@ -33,7 +56,17 @@ coque desktop Tauri, et l'encodeur matériel.
### TypeScript
- `apps/viewer` et `apps/desktop` : Vite, React 19, TypeScript strict, biome pour lint et format
(tabs, guillemets simples, pas d'ESLint, pas de Prettier).
(tabs, guillemets simples, pas d'ESLint, pas de Prettier). Le viewer s'installe avec npm, la
coque avec **pnpm** (`pnpm-lock.yaml`).
- Les types de la coque (`apps/desktop/src/bindings`) sont générés depuis `rs-store` et
`rs-session`, comme ceux du viewer depuis `rs-proto`: `make proto`.
- **Aucun texte en dur dans un composant.** Les textes vivent dans `locales/<langue>.json`, une
section par application, et passent par `t('clé')`. L'anglais est la langue de repli et doit
être complet, le français aussi. `npm run lint` (viewer) et `pnpm lint` (coque) lancent
`scripts/check-i18n.mjs`, qui refuse une clé absente de l'anglais et un texte en dur. Ajouter
une langue, c'est ajouter un fichier: l'hôte l'embarque (`rs-signaling/build.rs`) et la sert au
viewer, la coque l'embarque à la compilation. Le viewer et la coque partagent le cœur
(`apps/viewer/src/lib/i18n.ts`), sans React.
- Aucune dépendance à un service externe : pas d'analytics, pas de CDN, pas de police distante.
Le client doit fonctionner sur un LAN sans Internet.
- Le protocole vient de `rs-proto`. Un type de message en double (un côté Rust, un côté TS, écrit
@@ -45,6 +78,10 @@ coque desktop Tauri, et l'encodeur matériel.
pas de tiret cadratin.
- Une issue par sujet dans le tracker Gitea, avec son jalon. Une demande nouvelle ouvre une issue
avant la première ligne de code.
- Le suivi d'avancement est un **tableau Projets par jalon**, colonnes `En cours`, `P0`, `P1`, `P2`,
`P3` de gauche à droite. Une carte passe dans `En cours` quand elle est attaquée, l'ordre des
cartes dans une colonne est l'ordre de travail, et une issue livrée se ferme (elle quitte le
tableau). Ne pas recréer de colonnes de statut : le statut, c'est l'état ouvert/fermé.
## Pièges connus de ce domaine
@@ -80,20 +117,68 @@ cargo test -p rs-proto export_bindings # régénère apps/viewer/src/proto
Une fonctionnalité de capture ou d'encodage se prouve avec une mire de test et des mesures de
latence, pas avec une capture d'écran de l'UI.
Le banc d'essai actuel est la démo de `rs-signaling`: elle assemble la vraie pile (protocole,
session, serveur) et rejoue une mire IVF.
Le banc d'essai actuel est le binaire `rustscreen-cli` de `rs-session`: il assemble la vraie pile
(capture, encodage, protocole, session, serveur) et sait aussi rejouer une mire IVF.
```bash
# mire synthétique: capture, conversion BGRA vers I420, encodage VP8, en direct
cargo run -p rs-signaling --bin rustscreen -- --synthetic --port 8099
cargo run -p rs-session --bin rustscreen-cli -- --synthetic --port 8099
# ou rejeu d'un fichier encodé, sans encodeur
cargo run -p rs-signaling --bin rustscreen -- spikes/str0m-mire/mire.ivf --port 8099
cargo run -p rs-session --bin rustscreen-cli -- spikes/str0m-mire/mire.ivf --port 8099
```
Elle accepte `--limit N`, `--tls` et `--viewer DIR`. Sans TLS, le serveur est en HTTP simple:
Il accepte `--limit N`, `--tls` et `--viewer DIR`; le port, l'interface et la limite viennent
sinon des réglages (`~/.config/rustscreen/settings.json`, partagés avec l'application de bureau). Sans TLS, le serveur est en HTTP simple:
pratique pour un navigateur local, insuffisant pour un vrai appareil (voir ADR 0005).
La capture réelle sous Wayland demande la feature `pipewire` (libpipewire-0.3 et libclang au
build, fournies par `nix develop`; ADR 0009). Sans elle, le binaire refuse le chemin portail avec
un message clair.
```bash
# écran réel, par le portail (sous X11: XShm, sans feature)
cargo run --release -p rs-session --features pipewire --bin rustscreen-cli
# second écran créé par le portail, à la taille de la tablette
cargo run --release -p rs-session --features pipewire --bin rustscreen-cli -- --virtual --size 1280x800
# archive de diagnostics, sans rien démarrer
cargo run -p rs-session --bin rustscreen-cli -- --diagnostics
# VP9 au lieu de VP8 (même qualité pour moins de débit, 1,6x le calcul), une fenêtre par le portail
cargo run --release -p rs-session --features pipewire --bin rustscreen-cli -- --codec vp9 --pick-window
```
La coque desktop demande WebKitGTK au build: elle a son propre workspace Cargo et son shell Nix.
```bash
nix develop .#desktop
make desktop # pnpm install, interface, puis binaire (target/release/rustscreen)
nix build .#rustscreen # le paquet: application de bureau, rustscreen-cli et viewer
make desktop-lint # biome, vitest, rustfmt et clippy de la coque
```
En debug, le binaire embarque `apps/desktop/dist` (feature `custom-protocol` par défaut);
`--no-default-features` charge le serveur Vite (`pnpm --dir apps/desktop dev`) à la place.
Le chemin se force avec `RUSTSCREEN_CAPTURE=portal|x11|synthetic`. Le test X11 réel se lance
contre un serveur jetable: `Xephyr :5 & DISPLAY=:5 xeyes &` puis
`RUSTSCREEN_X11_TEST=:5 cargo test -p rs-capture x11 -- --ignored`. Pour plusieurs moniteurs,
lancer Xephyr avec `+extension RANDR` et en déclarer avec `xrandr --setmonitor` (voir le test).
Avec openbox sur ce serveur, le même test réduit puis restaure une fenêtre partagée (#17).
Pour essayer la coque ou un navigateur sans rien ouvrir sur le bureau, préférer `Xvfb` à
`Xephyr`, qui affiche une fenêtre. L'icône de barre système, elle, passe par le bus de session: elle
apparaît dans la vraie barre. Elle se vérifie par D-Bus (`org.kde.StatusNotifierWatcher`, menu
`com.canonical.dbusmenu`), et son menu se pilote par `Event`.
Le journal JSON (`~/.local/state/rustscreen/logs`) nomme les étapes d'une session par le champ
`event`: `portal_granted`, `capture_format`, `first_buffer`, `first_frame_encoded`,
`session_opened`, `ice_candidate_selected`, `first_frame_sent`, `quality_change`, `disconnected`
(avec `cause`), `capture_revoked`, `capture_failed`, `encode_failed`, et côté hôte `share_started`,
`share_ended`, `share_interrupted`, `viewer_disconnected`, `resolution_changed`, `sleep_inhibited`,
`sleep_released`, `wake_detected`, `capture_restarted`, `address_changed`, `settings_changed`,
`access_regenerated`, `code_accepted`, `code_rejected`. Avant la 0.6, ces noms étaient en français
(champ `evenement`). Ne jamais y écrire un titre de fenêtre ni une image (ADR 0008).
Le spike historique `spikes/str0m-mire` reste pour comparer les mesures:
```bash
@@ -116,3 +201,31 @@ vérifier qu'une régression ne casse pas le transport.
reçu. C'est un argument pour ICE-lite côté hôte.
- **Le candidat annoncé doit être l'adresse LAN**, jamais `127.0.0.1`: Chrome ignore les candidats
loopback et la connexion reste en `Checking`.
- **Le viewer servi en HTTP sur le LAN n'est pas un contexte sécurisé.** `crypto.randomUUID()`,
`navigator.clipboard` et d'autres API y manquent. Un `randomUUID` dans le `hello` a empêché toute
connexion depuis un autre appareil que l'hôte, alors que tous les essais sur `127.0.0.1`
passaient. Tester le viewer par l'adresse du LAN, jamais seulement par le loopback.
- **Le type de charge utile suit le codec encodé**, jamais le premier venu: `payload_params().next()`
prenait VP8 pendant qu'on envoyait du VP9, et le navigateur affichait un écran noir sans erreur.
- **libvpx 1.13 plante en VP9 à la vitesse 6**, et avec le réglage « contenu écran » à toute vitesse
(SIGSEGV dans `vpx_variance8x8_sse2`, reproduit en C pur; corrigé en 1.14). L'encodeur est figé
à la vitesse 7 et le test `vp9_survives_moving_content` tombe si quelqu'un remet 6.
## Pièges du portail, appris à la dure
La négociation du portail a « compilé et passé les tests » avec trois bugs que seule une vraie
session a révélés. Le détail est dans `docs/capture-wayland.md`; l'essentiel:
- **Le corps d'un appel D-Bus est un tuple d'arguments, pas une `Variant`**: sinon la signature
part en `(v)` et le portail répond `InvalidArgs`.
- **`SelectSources`, `Start`, `OpenPipeWireRemote` s'appellent sur `/org/freedesktop/portal/desktop`**,
la session en premier argument.
- **Le descripteur PipeWire vient de `OpenPipeWireRemote`**, jamais de la réponse de `Start`.
- **GNOME livre des tampons MemFd que PipeWire ne mappe pas**, malgré `MAP_BUFFERS`: `data()` est
vide. Ils se lisent par `pread` sur le descripteur (`read_memfd`). Les ignorer donnait un écran
noir sans aucune erreur. Une mire GStreamer (`examples/pipewire_local.rs`) livre des tampons
mappés: elle ne remplace pas un essai par le vrai portail. Le journal dit comment arrive le
premier tampon (`premier_tampon`), puis la première panne de capture ou d'encodage.
- **`/proc/self/net/*` liste tout l'espace de noms réseau**, pas le processus: filtrer par les
inodes de `/proc/self/fd` (voir le test `no_outbound_connection`).
Generated
+827 -57
View File
File diff suppressed because it is too large. Load diff
+10 -1
View File
@@ -9,11 +9,14 @@ members = [
"crates/rs-session",
"crates/rs-platform",
"crates/rs-store",
"crates/rs-diag",
"spikes/str0m-mire",
]
# La coque Tauri a son propre workspace: WebKitGTK au build (voir son Cargo.toml).
exclude = ["apps/desktop/src-tauri"]
[workspace.package]
version = "0.1.1"
version = "0.5.0"
edition = "2024"
rust-version = "1.90"
license = "Apache-2.0"
@@ -24,3 +27,9 @@ serde = { version = "1", features = ["derive"] }
serde_json = "1"
thiserror = "2"
tracing = "0.1"
# Les dépendances sans informations de débogage complètes: des binaires de test
# trois fois plus légers et une édition de liens plus courte (#78). Les numéros
# de ligne restent, une trace de pile se lit toujours; nos crates gardent tout.
[profile.dev.package."*"]
debug = "line-tables-only"
+25 -12
View File
@@ -1,6 +1,6 @@
# Portes du projet. `make` seul lance tout ce qui doit être vert avant un commit.
# Project gates. Plain `make` runs everything that must pass before a commit.
.PHONY: all fmt lint test build proto bench clean
.PHONY: all fmt lint test build proto bench clean desktop desktop-lint
all: fmt lint test build
@@ -13,26 +13,39 @@ lint:
cargo clippy --workspace --all-targets -- -D warnings
npm --prefix apps/viewer run lint
# `--skip export_bindings` : les tests de génération de ts-rs écriraient dans
# apps/viewer/src/proto à chaque exécution. La cible `proto` s'en charge, avec
# le formatage qui va avec.
# `--skip export_bindings`: the ts-rs generation tests would write into
# apps/viewer/src/proto on every run. The `proto` target handles that, along
# with the matching formatting.
test:
cargo test --workspace -- --skip export_bindings
# Les types TypeScript du protocole sont générés, jamais écrits à la main.
# Ils sont exclus du formateur et du linter (voir biome.json): leur format
# appartient à ts-rs, sinon chaque `make` laisse un diff dans le dépôt.
# The protocol's TypeScript types are generated, never written by hand.
# They are excluded from the formatter and the linter (see biome.json): their
# format belongs to ts-rs, otherwise every `make` leaves a diff in the repository.
proto:
cargo test -p rs-proto export_bindings
cargo test -p rs-proto -p rs-store -p rs-session export_bindings
build:
cargo build --workspace
npm --prefix apps/viewer run build
# Banc d'essai: toujours en release, un binaire debug fausse les mesures.
# Test bench: always in release, a debug binary skews the measurements.
bench:
cargo run --release -p rs-signaling --bin rustscreen -- --synthetic
cargo run --release -p rs-session --bin rustscreen-cli -- --synthetic
# The Tauri shell: WebKitGTK at build time, so inside `nix develop .#desktop`.
# Its crate has its own workspace; it shares the target directory to avoid
# rebuilding everything. pnpm for the shell's interface, npm for the viewer.
desktop:
pnpm --dir apps/desktop install --frozen-lockfile
pnpm --dir apps/desktop build
cd apps/desktop/src-tauri && CARGO_TARGET_DIR=../../../target cargo build --release --features pipewire
desktop-lint:
pnpm --dir apps/desktop lint
pnpm --dir apps/desktop test
cd apps/desktop/src-tauri && cargo fmt --check && CARGO_TARGET_DIR=../../../target cargo clippy --features pipewire -- -D warnings
clean:
cargo clean
rm -rf apps/viewer/dist
rm -rf apps/viewer/dist apps/desktop/dist
+31 -13
View File
@@ -8,20 +8,28 @@
côté spectateur. Réimplémentation de [Deskreen](https://deskreen.com) (Electron + WebRTC) avec un
hôte en Rust, un client web en TypeScript et une interface desktop Tauri.
État : **M0 terminé, M1 en cours**. Ce qui tourne aujourd'hui, vérifié le 24 octobre 2026:
État : **jalon 0.3 « Voir l'écran »**. Ce qui tourne aujourd'hui, vérifié le 26 octobre 2026:
- workspace Rust de huit crates, protocole partagé avec types TypeScript générés
- `rs-capture`: interface de capture, avec une mire synthétique qui alimente tout le pipeline
- 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 (`--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
- `rs-rtc`: session str0m par spectateur, avec sa boucle testée
- `rs-signaling`: serveur local, jeton de room, WebSocket de signalement, TLS auto-signé
- `apps/viewer`: viewer React avec machine à états, reconnexion bornée, statistiques
- `rs-session`: l'hôte (partage, spectateurs, réglages, veille, réseau) et le binaire `rustscreen`
- `rs-store`: réglages persistants, écriture atomique, fichier corrompu mis de côté
- `apps/desktop`: coque Tauri, choix de la source avec vignettes, QR, spectateurs, réglages
- `apps/viewer`: viewer React avec machine à états, reprise après coupure ou veille, statistiques
- une session complète de bout en bout: capture synthétique, encodage en direct, VP8 dans le
navigateur, couleurs vérifiées à l'écran (voir `docs/perf.md` pour les mesures)
Restent à écrire: la capture réelle par OS (#8, #9, #10), la coque desktop Tauri (#15), et
l'encodeur matériel (#53). Le prerequis de build hors Rust est libvpx: voir
`scripts/build-libvpx.sh` et AGENTS.md.
Restent à écrire: la capture Windows (#8, après la 1.0), l'icône de barre système (#22), et
l'encodeur matériel (#57). Les prérequis de build hors Rust sont libvpx (`scripts/build-libvpx.sh`)
et, pour la capture Wayland, libpipewire-0.3 et libclang (`nix develop` fournit tout): voir
AGENTS.md.
## Pourquoi
@@ -43,7 +51,8 @@ offre SaaS multi-tenant. Ils sont cadrés dans le backlog comme extensions, pas
## Stack
- **Hôte** : Rust, `axum` (HTTP/WSS), `str0m` (WebRTC sans I/O), `scap` (capture), `libvpx` puis
- **Hôte** : Rust, `axum` (HTTP/WSS), `str0m` (WebRTC sans I/O), portail `zbus` + `pipewire` et
`x11rb` (capture), `libvpx` puis
encodeurs matériels (`rs-codec`), `rustls` + `rcgen` (TLS local), `mdns-sd` (nom local)
- **UI desktop** : Tauri v2, front TypeScript + React 19 + Vite
- **Client spectateur** : TypeScript + Vite, `RTCPeerConnection` natif du navigateur, servi par
@@ -56,21 +65,23 @@ offre SaaS multi-tenant. Ils sont cadrés dans le backlog comme extensions, pas
```
apps/desktop UI Tauri (front TS) + src-tauri (commandes, cycle de vie)
apps/viewer client navigateur (TS, Vite)
locales textes de l'interface, un fichier JSON par langue
crates/rs-proto types partagés, versions, modèle de session
crates/rs-capture abstraction de capture + implémentations par OS
crates/rs-codec conversion de pixels et encodeurs vidéo
crates/rs-rtc session str0m, ICE, DTLS, RTP, statistiques
crates/rs-signaling serveur axum, WebSocket de signalement, QR code, TLS optionnel, viewer statique
crates/rs-session orchestration des sessions, appareils, alias, confiance
crates/rs-session l'hôte: partage, spectateurs, réglages, veille; binaire `rustscreen`
crates/rs-platform autostart, inhibition de veille, interfaces réseau, MAC, tray
crates/rs-store persistance locale (JSON)
crates/rs-diag journal structuré local, archive de diagnostics
docs architecture, ADR, matrice de fonctionnalités, backlog
```
## Prérequis (une fois le code là)
- Rust stable (édition 2024), `cargo`
- Node 22+ et npm 12 pour `apps/desktop` et `apps/viewer`
- Node 22+, npm pour `apps/viewer`, pnpm pour `apps/desktop` (`nix develop .#desktop`)
- Linux : PipeWire et `xdg-desktop-portal` (Wayland), X11 accepté en repli
- macOS : 12.3+ pour ScreenCaptureKit
- Windows : 10 1809+ pour la duplications de bureau DXGI
@@ -78,18 +89,25 @@ 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
démarrent aujourd'hui avec `--synthetic` : la capture d'un vrai écran reste à brancher (#8, #9, #10).
capturent l'écran sous Wayland (portail) et X11; `--synthetic` reste là pour essayer sans écran.
## Licence
Apache-2.0, voir [LICENSE](LICENSE). Licence permissive avec clause de brevets explicite: elle
laisse réutiliser le code, y compris dans un produit commercial, sans imposer de partager le reste.
## Feuille de route
[docs/ROADMAP.md](docs/ROADMAP.md) dit ce qui doit exister pour une 1.0 honnête, dans quel ordre, et
comment on décide qu'une release est prête. Le suivi vivant est dans les jalons Gitea et le projet
« Roadmap 1.0 ».
## Suivre le travail
Le découpage complet est dans [docs/backlog.md](docs/backlog.md), une issue par sujet, avec les
+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>rustscreen</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+29
View File
@@ -0,0 +1,29 @@
{
"name": "@rustscreen/desktop",
"private": true,
"version": "0.5.0",
"type": "module",
"packageManager": "pnpm@12.15.0",
"description": "rustscreen desktop shell: pick the source, see the viewers, stop.",
"scripts": {
"dev": "vite",
"build": "tsc --noEmit && vite build",
"lint": "biome lint src && node ../../scripts/check-i18n.mjs apps/desktop/src desktop",
"format": "biome format --write src",
"test": "vitest run"
},
"dependencies": {
"@tauri-apps/api": "^2.12.3",
"react": "^19.2.0",
"react-dom": "^19.2.0"
},
"devDependencies": {
"@biomejs/biome": "^2.6.0",
"@types/react": "^19.2.0",
"@types/react-dom": "^19.2.0",
"@vitejs/plugin-react": "^6.1.0",
"typescript": "~7.0.0",
"vite": "^8.3.0",
"vitest": "^5.0.5"
}
}
+1203
View File
File diff suppressed because it is too large. Load diff
+6168
View File
File diff suppressed because it is too large. Load diff
+44
View File
@@ -0,0 +1,44 @@
[package]
name = "rustscreen-desktop"
description = "rustscreen desktop shell: choose what to share, see who is watching, stop."
version = "0.5.0"
edition = "2024"
rust-version = "1.90"
license = "Apache-2.0"
repository = "https://gitea-nubo.hopledge.com/heap/rustscreen"
# Outside the main workspace: WebKitGTK and GTK are needed at build time, and
# the host CI does not have them. `nix develop .#desktop` provides them.
# Launching rustscreen opens this desktop application (#84); the command line
# is `rustscreen-cli` (crates/rs-session).
[[bin]]
name = "rustscreen"
path = "src/main.rs"
[workspace]
[features]
# The built interface (`dist`) is embedded in the binary. Without this
# feature, Tauri loads `devUrl` (the Vite server, `pnpm dev`): that is the
# development mode, `--no-default-features`. The Tauri CLI makes this choice on
# its own; we do without it, hence the explicit choice.
default = ["custom-protocol"]
custom-protocol = ["tauri/custom-protocol"]
# Real Wayland capture (ADR 0009), like the command-line binary.
pipewire = ["rs-session/pipewire"]
[dependencies]
rs-diag = { path = "../../../crates/rs-diag" }
rs-session = { path = "../../../crates/rs-session" }
rs-store = { path = "../../../crates/rs-store" }
# `tray-icon`: system tray icon (#22); `image-png`: its icons.
tauri = { version = "2.12.5", features = ["tray-icon", "image-png"] }
tracing = "0.1"
serde = { version = "1.0.229", features = ["derive"] }
[target.'cfg(target_os = "linux")'.dependencies]
# Trial load of libayatana-appindicator before creating the icon (#22).
libloading = "0.8.9"
[build-dependencies]
tauri-build = { version = "2.7.4", features = [] }
+3
View File
@@ -0,0 +1,3 @@
fn main() {
tauri_build::build();
}
@@ -0,0 +1,7 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "The main window: listen to the host state. The application commands are allowed by default.",
"windows": ["main"],
"permissions": ["core:default"]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

+325
View File
@@ -0,0 +1,325 @@
//! rustscreen desktop shell (#15): the screen the host sees.
//!
//! It does nothing but relay: each command calls [`rs_session::Host`], and
//! each state change goes to the interface through the `state` event, the
//! complete state every time. The interface therefore keeps no share state of
//! its own, and cannot show a button that lies.
mod tray;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use rs_session::{
Config, Host, HostState, InterfaceOption, Overrides, Phase, SettingsOutcome, SourceChoice,
SourceOption,
};
use rs_store::{CloseAction, Rejection, Settings};
use tauri::{Emitter, Manager, RunEvent, State, WindowEvent};
/// The last started source, so that the system tray menu can restart a share
/// without opening the window.
#[derive(Default)]
struct LastSource(Mutex<Option<SourceChoice>>);
/// The system tray icon, if this desktop has one: without it, hiding the
/// window would make the application impossible to find.
struct MaybeTray(Option<Arc<tray::Tray<tauri::Wry>>>);
impl MaybeTray {
fn present(&self) -> bool {
self.0.is_some()
}
}
fn last_source_known(app: &tauri::AppHandle) -> bool {
app.state::<LastSource>()
.0
.lock()
.unwrap_or_else(|e| e.into_inner())
.is_some()
}
// The binary is `rustscreen` (#84): its log target follows.
const FILTER: &str = "rustscreen=info,rs_session=info,rs_signaling=info,rs_rtc=info,\
rs_capture=info,rs_codec=info,rs_platform=info,rs_diag=info,\
rs_store=info,str0m=warn";
#[tauri::command]
fn state(host: State<'_, Host>) -> HostState {
host.state()
}
#[tauri::command]
async fn sources(host: State<'_, Host>) -> Result<Vec<SourceOption>, ()> {
Ok(host.sources().await)
}
#[tauri::command]
async fn start(
host: State<'_, Host>,
last: State<'_, LastSource>,
choice: SourceChoice,
) -> Result<(), String> {
*last.0.lock().unwrap_or_else(|e| e.into_inner()) = Some(choice.clone());
host.start(choice).await
}
#[tauri::command]
async fn stop(host: State<'_, Host>) -> Result<(), ()> {
host.stop().await;
Ok(())
}
#[tauri::command]
fn disconnect(host: State<'_, Host>, connection: u64) -> bool {
host.disconnect(connection)
}
#[tauri::command]
fn regenerate_access(host: State<'_, Host>) -> bool {
host.regenerate_access()
}
/// The texts of the system tray menu, in the language of the interface.
#[tauri::command]
fn translate_tray(
app: tauri::AppHandle,
host: State<'_, Host>,
tray: State<'_, MaybeTray>,
texts: tray::TrayTexts,
) {
if let Some(tray) = &tray.0 {
tray.translate(texts);
tray.follow(&host.state(), last_source_known(&app));
}
}
#[tauri::command]
fn settings(host: State<'_, Host>) -> Settings {
host.settings()
}
#[tauri::command]
async fn update_settings(
host: State<'_, Host>,
settings: Settings,
) -> Result<SettingsOutcome, Vec<Rejection>> {
host.update_settings(settings).await
}
#[tauri::command]
fn interfaces(host: State<'_, Host>) -> Vec<InterfaceOption> {
host.interfaces()
}
/// Writes the diagnostics archive to the download folder and returns its
/// path: the user sends it themselves (ADR 0008).
#[tauri::command]
async fn export_diagnostics(host: State<'_, Host>) -> Result<String, String> {
let host = host.inner().clone();
tauri::async_runtime::spawn_blocking(move || {
let (name, bytes) = host.diagnostics()?;
let dir = download_dir();
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
let path = dir.join(name);
std::fs::write(&path, bytes).map_err(|e| e.to_string())?;
tracing::info!(event = "diagnostics_exported", "archive written");
Ok(path.display().to_string())
})
.await
.map_err(|e| e.to_string())?
}
/// `XDG_DOWNLOAD_DIR` from `user-dirs.dirs` when it exists, otherwise the home
/// folder.
fn download_dir() -> PathBuf {
let home = std::env::var_os("HOME")
.map(PathBuf::from)
.unwrap_or_default();
let config = std::env::var_os("XDG_CONFIG_HOME")
.map(PathBuf::from)
.unwrap_or_else(|| home.join(".config"));
std::fs::read_to_string(config.join("user-dirs.dirs"))
.ok()
.and_then(|text| {
text.lines().find_map(|line| {
let value = line.strip_prefix("XDG_DOWNLOAD_DIR=")?.trim_matches('"');
Some(PathBuf::from(
value.replace("$HOME", &home.display().to_string()),
))
})
})
.unwrap_or(home)
}
/// A click in the system tray menu.
fn on_tray_click(app: &tauri::AppHandle, id: &str) {
let host = app.state::<Host>().inner().clone();
match id {
tray::OPEN => tray::show(app),
tray::START => {
let last = app
.state::<LastSource>()
.0
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone();
match last {
Some(choice) => {
tauri::async_runtime::spawn(async move {
// The failure shows in the window, through the state.
let _ = host.start(choice).await;
});
}
None => tray::show(app),
}
}
tray::STOP => {
tauri::async_runtime::spawn(async move { host.stop().await });
}
tray::QUIT => request_quit(app),
_ => {}
}
}
/// Autostart argument: the application starts hidden in the system tray
/// (#32).
const AUTOSTARTED: &str = "--autostarted";
/// The former spelling, still written in the `.desktop` files of existing
/// installations: it keeps being accepted.
const AUTOSTARTED_LEGACY: &str = "--au-demarrage";
/// Quit, or ask first if a share is running (#43): a reflex gesture must not
/// cut a presentation short. The window comes back and asks the question; the
/// `quit` command concludes.
fn request_quit(app: &tauri::AppHandle) {
let host = app.state::<Host>();
if host.state().phase == Phase::Stopped || !host.settings().confirm_quit {
app.exit(0);
return;
}
tray::show(app);
if let Err(error) = app.emit("confirm-quit", ()) {
tracing::warn!(%error, "quit confirmation not requested: quitting");
app.exit(0);
}
}
/// Answer to the confirmation: quit, and stop asking if so wished.
#[tauri::command]
async fn quit(
app: tauri::AppHandle,
host: State<'_, Host>,
dont_ask_again: bool,
) -> Result<(), Vec<Rejection>> {
if dont_ask_again {
let mut settings = host.settings();
settings.confirm_quit = false;
host.update_settings(settings).await?;
}
app.exit(0);
Ok(())
}
fn main() {
let log = rs_diag::init(rs_diag::log_dir().as_deref(), FILTER);
// Autostart relaunches this binary. An AppImage runs from a temporary
// mount: its file is what must be relaunched.
let executable = std::env::var_os("APPIMAGE")
.map(PathBuf::from)
.or_else(|| std::env::current_exe().ok());
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,
store: rs_store::Store::user_default(),
overrides: Overrides::default(),
log_dir: log.dir.clone(),
autostart: executable.map(|exe| (exe, AUTOSTARTED.to_string())),
}));
let application = tauri::Builder::default()
.manage(host.clone())
.manage(LastSource::default())
.invoke_handler(tauri::generate_handler![
state,
sources,
start,
stop,
disconnect,
regenerate_access,
translate_tray,
quit,
settings,
update_settings,
interfaces,
export_diagnostics,
])
.setup(move |app| {
let tray = tray::Tray::create(app.handle(), on_tray_click).map(Arc::new);
app.manage(MaybeTray(tray.clone()));
// The window is created hidden: at session start, it stays so if
// the system tray exists to find it again; otherwise it is shown,
// an invisible application would be lost.
if !(autostarted && tray.is_some()) {
tray::show(app.handle());
}
// The state goes to the interface and to the icon on each change,
// complete: the icon follows the real state at the same moment as
// the window.
let handle = app.handle().clone();
let mut subscriber = host.subscribe();
if let Some(tray) = &tray {
tray.follow(&subscriber.borrow(), false);
}
tauri::async_runtime::spawn(async move {
while subscriber.changed().await.is_ok() {
let state = subscriber.borrow_and_update().clone();
if let Some(tray) = &tray {
tray.follow(&state, last_source_known(&handle));
}
if let Err(error) = handle.emit("state", state) {
tracing::warn!(%error, "state not sent to the interface");
}
}
});
Ok(())
})
.on_window_event(|window, event| {
if let WindowEvent::CloseRequested { api, .. } = event {
let app = window.app_handle();
let host = app.state::<Host>();
if host.settings().close_action == CloseAction::Quit {
// Closing means quitting: same confirmation as the menu.
api.prevent_close();
request_quit(app);
return;
}
// Closing does not cut a share (#22): the window hides in the
// system tray. Without a tray, it minimizes during a share,
// and closes the application otherwise.
if app.state::<MaybeTray>().present() {
api.prevent_close();
let _ = window.hide();
} else if host.state().phase != Phase::Stopped {
api.prevent_close();
let _ = window.minimize();
}
}
})
.build(tauri::generate_context!())
.expect("Tauri application");
application.run(move |app, event| {
// Quitting stops the share cleanly: portal session closed, sleep
// released, viewers told.
if let RunEvent::Exit = event {
let host = app.state::<Host>().inner().clone();
tauri::async_runtime::block_on(host.stop());
}
});
drop(log);
}
+302
View File
@@ -0,0 +1,302 @@
//! System tray icon and session menu (#22).
//!
//! The icon tells the real state: it follows the same `state` as the window,
//! at the same moment, so in well under a second. The menu can start (the last
//! chosen source), stop, open the window and quit, without the window being
//! open.
//!
//! On Linux, the icon goes through StatusNotifierItem (libayatana-appindicator,
//! loaded at run time). GNOME without the AppIndicator extension shows nothing:
//! [`available`] detects it, and closing the window then falls back to a plain
//! minimize, so as never to hide a share with no way to find it again.
//!
//! The texts come from the interface (`translate_tray`), in its language
//! (#21): translations live in `locales/`, not here. The English below (the fallback language) only
//! serves before the first update.
use std::sync::Mutex;
use rs_session::{HostState, Phase};
use serde::Deserialize;
use tauri::image::Image;
use tauri::menu::{Menu, MenuItem, PredefinedMenuItem};
use tauri::tray::{MouseButton, MouseButtonState, TrayIcon, TrayIconBuilder, TrayIconEvent};
use tauri::{AppHandle, Manager, Runtime};
const ICON: &[u8] = include_bytes!("../icons/icon.png");
/// What the menu offers; the identifier comes back in the click event.
pub const OPEN: &str = "open";
pub const START: &str = "start";
pub const STOP: &str = "stop";
pub const QUIT: &str = "quit";
/// The forms of the live status: Rust does not know the plural rules of each
/// language, the interface gives it those for 0, for 1 and for the rest.
#[derive(Debug, Clone, Deserialize)]
pub struct PluralForms {
pub zero: String,
pub one: String,
/// With `{count}` to replace.
pub other: String,
}
/// The menu texts, translated by the interface.
#[derive(Debug, Clone, Deserialize)]
pub struct TrayTexts {
pub none: String,
pub starting: String,
pub live: PluralForms,
pub open: String,
pub start: String,
pub resume: String,
pub stop: String,
pub quit: String,
}
impl Default for TrayTexts {
fn default() -> Self {
Self {
none: "Not sharing".into(),
starting: "Starting to share…".into(),
live: PluralForms {
zero: "Live, nobody is watching".into(),
one: "Live, 1 viewer".into(),
other: "Live, {count} viewers".into(),
},
open: "Open rustscreen".into(),
start: "Start sharing…".into(),
resume: "Resume the last share".into(),
stop: "Stop sharing".into(),
quit: "Quit".into(),
}
}
}
impl TrayTexts {
fn status(&self, state: &HostState) -> String {
match state.phase {
Phase::Stopped => self.none.clone(),
Phase::Starting => self.starting.clone(),
Phase::Live => match state.share.as_ref().map_or(0, |s| s.devices.len()) {
0 => self.live.zero.clone(),
1 => self.live.one.clone(),
n => self.live.other.replace("{count}", &n.to_string()),
},
}
}
}
pub struct Tray<R: Runtime> {
icon: TrayIcon<R>,
status: MenuItem<R>,
open: MenuItem<R>,
start: MenuItem<R>,
stop: MenuItem<R>,
quit: MenuItem<R>,
idle: Image<'static>,
live: Image<'static>,
texts: Mutex<TrayTexts>,
}
impl<R: Runtime> Tray<R> {
/// Creates the icon and its menu. `None` when this desktop has no system
/// tray: the application then lives in its window only.
pub fn create(
app: &AppHandle<R>,
on_click: impl Fn(&AppHandle<R>, &str) + Send + Sync + 'static,
) -> Option<Self> {
if !available() {
tracing::info!("no system tray on this desktop: window only");
return None;
}
let build = || -> tauri::Result<Self> {
let idle = Image::from_bytes(ICON)?.to_owned();
let live = with_dot(&idle);
let texts = TrayTexts::default();
let status = MenuItem::with_id(app, "status", &texts.none, false, None::<&str>)?;
let open = MenuItem::with_id(app, OPEN, &texts.open, true, None::<&str>)?;
let start = MenuItem::with_id(app, START, &texts.start, true, None::<&str>)?;
let stop = MenuItem::with_id(app, STOP, &texts.stop, false, None::<&str>)?;
let quit = MenuItem::with_id(app, QUIT, &texts.quit, true, None::<&str>)?;
let menu = Menu::with_items(
app,
&[
&status,
&PredefinedMenuItem::separator(app)?,
&open,
&start,
&stop,
&PredefinedMenuItem::separator(app)?,
&quit,
],
)?;
let icon = TrayIconBuilder::with_id("rustscreen")
.icon(idle.clone())
.tooltip(format!("rustscreen: {}", texts.none))
.menu(&menu)
.show_menu_on_left_click(false)
.on_menu_event(move |app, event| on_click(app, event.id().as_ref()))
.on_tray_icon_event(|icon, event| {
// Windows and macOS: a left click reopens the window. On
// Linux, StatusNotifierItem only sends the menu.
if let TrayIconEvent::Click {
button: MouseButton::Left,
button_state: MouseButtonState::Up,
..
} = event
{
show(icon.app_handle());
}
})
.build(app)?;
Ok(Self {
icon,
status,
open,
start,
stop,
quit,
idle,
live,
texts: Mutex::new(texts),
})
};
match build() {
Ok(tray) => Some(tray),
Err(error) => {
tracing::warn!(%error, "system tray icon impossible");
None
}
}
}
/// Changes the menu language; the caller redraws with [`Tray::follow`].
pub fn translate(&self, texts: TrayTexts) {
let result = (|| -> tauri::Result<()> {
self.open.set_text(&texts.open)?;
self.stop.set_text(&texts.stop)?;
self.quit.set_text(&texts.quit)?;
Ok(())
})();
if let Err(error) = result {
tracing::warn!(%error, "system tray menu not translated");
}
*self.texts.lock().unwrap_or_else(|e| e.into_inner()) = texts;
}
/// Makes the icon, the tooltip and the menu match the state.
pub fn follow(&self, state: &HostState, last_source: bool) {
let texts = self.texts.lock().unwrap_or_else(|e| e.into_inner()).clone();
let text = texts.status(state);
let icon = if state.phase == Phase::Live {
&self.live
} else {
&self.idle
};
let result = (|| -> tauri::Result<()> {
self.icon.set_icon(Some(icon.clone()))?;
self.icon.set_tooltip(Some(format!("rustscreen: {text}")))?;
self.status.set_text(&text)?;
// Starting from the menu restarts the last source; without one,
// the menu opens the window to pick one.
self.start.set_text(if last_source {
&texts.resume
} else {
&texts.start
})?;
self.start.set_enabled(state.phase == Phase::Stopped)?;
self.stop.set_enabled(state.phase != Phase::Stopped)?;
Ok(())
})();
if let Err(error) = result {
tracing::warn!(%error, "system tray not updated");
}
}
}
/// Reopens the main window, hidden or minimized.
pub fn show<R: Runtime>(app: &AppHandle<R>) {
if let Some(window) = app.get_webview_window("main") {
let _ = window.unminimize();
let _ = window.show();
let _ = window.set_focus();
}
}
/// Is there a system tray? On Linux, it takes a StatusNotifierItem host on the
/// session bus and the library that talks to it.
#[cfg(target_os = "linux")]
fn available() -> bool {
let library = ["libayatana-appindicator3.so.1", "libappindicator3.so.1"]
.iter()
.any(|name| library_loads(name));
library && status_notifier_host()
}
#[cfg(not(target_os = "linux"))]
fn available() -> bool {
true
}
/// Can the dynamic loader open this library? tray-icon panics otherwise,
/// instead of returning an error. Looking for the file is not enough: a binary
/// built by Nix does not read the system cache, the same loading as its own
/// must be tried.
#[cfg(target_os = "linux")]
fn library_loads(name: &str) -> bool {
// SAFETY: this is the library tray-icon will load anyway right after,
// through the same search path; its constructors (GObject type
// registration) are meant to run once loaded, and keeping it loaded avoids
// a second pass.
match unsafe { libloading::Library::new(name) } {
Ok(library) => {
std::mem::forget(library);
true
}
Err(_) => false,
}
}
/// Does `org.kde.StatusNotifierWatcher` have an owner on the session bus? It
/// is the one that shows the icons (KDE, Ubuntu, GNOME with the AppIndicator
/// extension).
#[cfg(target_os = "linux")]
fn status_notifier_host() -> bool {
std::process::Command::new("busctl")
.args([
"--user",
"call",
"org.freedesktop.DBus",
"/org/freedesktop/DBus",
"org.freedesktop.DBus",
"NameHasOwner",
"s",
"org.kde.StatusNotifierWatcher",
])
.output()
.is_ok_and(|output| String::from_utf8_lossy(&output.stdout).trim() == "b true")
}
/// The "live" icon: the same one, with a red dot at the bottom right, readable
/// even at 16 pixels.
fn with_dot(base: &Image<'_>) -> Image<'static> {
let (w, h) = (base.width(), base.height());
let mut rgba = base.rgba().to_vec();
let radius = w.min(h) as f32 * 0.22;
let (cx, cy) = (w as f32 - radius - 1.0, h as f32 - radius - 1.0);
for y in 0..h {
for x in 0..w {
let d = ((x as f32 + 0.5 - cx).powi(2) + (y as f32 + 0.5 - cy).powi(2)).sqrt();
let i = ((y * w + x) * 4) as usize;
if d <= radius {
rgba[i..i + 4].copy_from_slice(&[0xdc, 0x26, 0x26, 0xff]);
} else if d <= radius + w as f32 * 0.03 {
// White rim: the dot stands out on a dark bar as on a light
// one.
rgba[i..i + 4].copy_from_slice(&[0xff, 0xff, 0xff, 0xff]);
}
}
}
Image::new_owned(rgba, w, h)
}
+30
View File
@@ -0,0 +1,30 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "rustscreen",
"version": "0.5.0",
"identifier": "local.rustscreen.desktop",
"build": {
"frontendDist": "../dist",
"devUrl": "http://localhost:5175"
},
"app": {
"windows": [
{
"label": "main",
"title": "rustscreen",
"width": 1100,
"height": 760,
"minWidth": 800,
"minHeight": 560,
"visible": false
}
],
"security": {
"csp": "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; connect-src ipc: http://ipc.localhost"
}
},
"bundle": {
"active": false,
"icon": ["icons/icon.png"]
}
}
+244
View File
@@ -0,0 +1,244 @@
import { useCallback, useEffect, useState } from 'react';
import type { HostState } from './bindings/HostState';
import type { SourceChoice } from './bindings/SourceChoice';
import type { SourceOption } from './bindings/SourceOption';
import type { Theme } from './bindings/Theme';
import { ConfirmQuit } from './components/ConfirmQuit';
import { SettingsDialog } from './components/SettingsDialog';
import { SharePanel } from './components/SharePanel';
import { SourcePicker } from './components/SourcePicker';
import { effectiveLanguage, I18nProvider, useI18n } from './i18n';
import type { Host } from './lib/host';
import { actions, key, status, trayTexts } from './lib/view';
/**
* The language comes from the host settings, or from the desktop. Changing it
* retranslates the interface and the system tray menu at the next render
* (#21).
*/
export function App({ host }: { host: Host }) {
const [setting, setSetting] = useState<string | null>(null);
useEffect(() => {
host.settings().then((s) => setSetting(s.language));
}, [host]);
const language = effectiveLanguage(setting, navigator.languages ?? [navigator.language]);
return (
<I18nProvider language={language}>
<Shell host={host} onLanguage={setSetting} />
</I18nProvider>
);
}
function Shell({ host, onLanguage }: { host: Host; onLanguage: (code: string | null) => void }) {
const { t, language } = useI18n();
const [state, setState] = useState<HostState | null>(null);
const [sources, setSources] = useState<SourceOption[] | null>(null);
const [selection, setSelection] = useState<SourceChoice | null>(null);
const [sending, setSending] = useState(false);
const [settingsOpen, setSettingsOpen] = useState(false);
const [confirmQuit, setConfirmQuit] = useState(false);
const [theme, setTheme] = useState<Theme>('system');
// The state comes from the host, always complete: subscribe before reading,
// so as not to miss a change in between.
useEffect(() => {
let unlisten: (() => void) | undefined;
let done = false;
host.listen(setState).then((stop) => {
if (done) stop();
else unlisten = stop;
});
host.state().then(setState);
let unlistenQuit: (() => void) | undefined;
host
.listenQuit(() => setConfirmQuit(true))
.then((stop) => {
if (done) stop();
else unlistenQuit = stop;
});
host.settings().then((s) => setTheme(s.theme));
return () => {
done = true;
unlisten?.();
unlistenQuit?.();
};
}, [host]);
useEffect(() => {
document.documentElement.dataset.theme = theme;
}, [theme]);
// The system tray menu is drawn by Rust: it receives its texts in the
// language of the interface.
useEffect(() => {
document.documentElement.lang = language;
host.translateTray(trayTexts(t)).catch(() => undefined);
}, [host, t, language]);
const refresh = useCallback(() => {
setSources(null);
host.sources().then((list) => {
setSources(list);
// A selection that vanished (window closed) is not kept silently.
setSelection((choice) =>
choice && list.some((s) => key(s.choice) === key(choice))
? choice
: (list[0]?.choice ?? null),
);
});
}, [host]);
const phase = state?.phase;
useEffect(() => {
if (phase === 'stopped') {
refresh();
}
}, [phase, refresh]);
if (!state) {
return <div className='loading'>{t('title')}</div>;
}
const buttons = actions(state, selection, sending);
const badge = status(state, t);
const send = async (command: () => Promise<unknown>) => {
setSending(true);
try {
await command();
} catch {
// The error also arrives in the state (`error`), which shows it.
} finally {
setSending(false);
}
};
const portal = selection?.type === 'portal';
return (
<div className='app'>
<header className='header'>
<h1>{t('title')}</h1>
<span className={`badge ${badge.tone}`} role='status'>
{badge.text}
</span>
{state.phase === 'live' && (
<span className='sleep' title={state.sleep_inhibited.join(', ')}>
{state.sleep_inhibited.length > 0 ? t('sleepInhibited') : t('sleepNotInhibited')}
</span>
)}
<span className='spacer' />
<button type='button' className='button muted' onClick={() => setSettingsOpen(true)}>
{t('settings')}
</button>
</header>
<main className='content'>
<Banners state={state} />
{state.phase === 'live' && state.share ? (
<SharePanel
share={state.share}
onDisconnect={(connection) => send(() => host.disconnect(connection))}
onNewCode={() => send(() => host.regenerateAccess())}
/>
) : (
<SourcePicker
sources={sources}
selection={selection}
enabled={buttons.pick}
onPick={setSelection}
onRefresh={refresh}
/>
)}
</main>
<footer className='action-bar'>
{state.phase === 'starting' && (
<p className='waiting' role='status'>
{portal ? t('waitingDesktop') : t('waiting')}
</p>
)}
<span className='spacer' />
{buttons.start.visible && (
<button
type='button'
className='button primary'
disabled={!buttons.start.enabled}
onClick={() => selection && send(() => host.start(selection))}
>
{t('start')}
</button>
)}
{buttons.cancel.visible && (
<button
type='button'
className='button'
disabled={!buttons.cancel.enabled}
onClick={() => host.stop()}
>
{t('cancel')}
</button>
)}
{buttons.stop.visible && (
<button
type='button'
className='button danger'
disabled={!buttons.stop.enabled}
onClick={() => send(() => host.stop())}
>
{t('stop')}
</button>
)}
</footer>
{confirmQuit && (
<ConfirmQuit
viewers={state.share?.devices.length ?? 0}
onCancel={() => setConfirmQuit(false)}
onQuit={(dontAskAgain) => {
void host.quit(dontAskAgain);
}}
/>
)}
{settingsOpen && (
<SettingsDialog
host={host}
autostart={state.capabilities.autostart}
onClose={() => setSettingsOpen(false)}
onSaved={(s) => {
setTheme(s.theme);
onLanguage(s.language);
}}
/>
)}
</div>
);
}
function Banners({ state }: { state: HostState }) {
const { t } = useI18n();
return (
<>
{state.error && state.phase === 'stopped' && (
<div className='banner error' role='alert'>
<strong>{t('startFailed')}</strong> {state.error}
</div>
)}
{state.stop && state.phase === 'stopped' && (
<div className='banner error' role='alert'>
<strong>{t('stoppedByDesktop')}</strong> {state.stop.reason}
</div>
)}
{state.settings_recovered && <div className='banner warning'>{state.settings_recovered}</div>}
{state.warnings.map((w) => (
<div key={w} className='banner warning' role='alert'>
{w}
</div>
))}
{state.pending_settings.length > 0 && (
<div className='banner info'>
<strong>{t('pendingSettings')}</strong> {state.pending_settings.join('; ')}
</div>
)}
</>
);
}
+15
View File
@@ -0,0 +1,15 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type Capabilities = {
/**
* `wayland`, `x11` or `none`.
*/
session: string, desktop: string, portal: boolean, virtual_display: boolean,
/**
* The binary can consume a PipeWire stream (`pipewire` feature).
*/
pipewire: boolean,
/**
* Autostart can be set from this application.
*/
autostart: boolean, };
+6
View File
@@ -0,0 +1,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* What closing the desktop application window does (#22).
*/
export type CloseAction = "tray" | "quit";
+7
View File
@@ -0,0 +1,7 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* Video codec of the shares (#67). VP9 keeps the same quality at a lower
* bitrate, but costs 1.6x the CPU of VP8 (`docs/perf.md`).
*/
export type Codec = "vp8" | "vp9";
+36
View File
@@ -0,0 +1,36 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { Capabilities } from "./Capabilities";
import type { Phase } from "./Phase";
import type { Share } from "./Share";
import type { Stop } from "./Stop";
/**
* The whole state of the host.
*/
export type HostState = { phase: Phase, share: Share | null,
/**
* Failure of the last start, to display as is.
*/
error: string | null, stop: Stop | null,
/**
* What still works but deserves to be known (interface down, address
* changed).
*/
warnings: Array<string>,
/**
* Sleep inhibition mechanisms held (`login1`, `screensaver`): empty
* outside a share, or if none could be taken.
*/
sleep_inhibited: Array<string>,
/**
* Settings changed during the share, applied to the next one.
*/
pending_settings: Array<string>,
/**
* The settings file was unusable at startup: what was done about it.
*/
settings_recovered: string | null,
/**
* Capabilities of this machine, to offer only what works.
*/
capabilities: Capabilities, };
@@ -0,0 +1,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* A network interface offered in the settings.
*/
export type InterfaceOption = { name: string, addresses: Array<string>, active: boolean, };
+7
View File
@@ -0,0 +1,7 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* What the interface shows as the name of a source, in its language (#21).
* Only a window title or an output name comes from the system as is.
*/
export type Label = { "type": "title", text: string, } | { "type": "monitor", output: string, primary: boolean, } | { "type": "screen" } | { "type": "window" } | { "type": "virtual_screen" } | { "type": "test_pattern" } | { "type": "recorded_pattern" } | { "type": "all_screens" } | { "type": "entire_screen" } | { "type": "chosen_screen" } | { "type": "chosen_window" };
+6
View File
@@ -0,0 +1,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* Where the share stands.
*/
export type Phase = "stopped" | "starting" | "live";
+7
View File
@@ -0,0 +1,7 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* A rejected value, named by its field: the interface places it next to the
* faulty field, and the message reads as is.
*/
export type Rejection = { field: string, message: string, };
+53
View File
@@ -0,0 +1,53 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { QualityPreset } from "../../../viewer/src/proto/QualityPreset";
import type { CloseAction } from "./CloseAction";
import type { Codec } from "./Codec";
import type { Theme } from "./Theme";
import type { TrustedDevice } from "./TrustedDevice";
/**
* Everything that can be set, in a single place.
*
* `#[serde(default)]`: a file written by a version that did not know a field
* still reads, the field takes its default value. Every renamed field keeps
* its previous (French) name as an alias, so files from 0.5 and earlier read
* without loss.
*/
export type Settings = { version: number,
/**
* Listening port of the server (viewer and signaling).
*/
port: number,
/**
* Name of the network interface to listen on (`wlp2s0`, `enp3s0`).
* `None`: all interfaces.
*/
interface: string | null, theme: Theme,
/**
* Language code of the interface (`fr`, `en`, `pt-BR`), among the files
* of `locales/` (#21). `None`: the desktop's. A code, not a closed list:
* adding a language does not change this format.
*/
language: string | null,
/**
* Simultaneous viewers.
*/
limit: number,
/**
* Quality offered when a share starts.
*/
quality: QualityPreset, codec: Codec,
/**
* Minutes during which the QR code and the short code let a new device in
* (#19). `0`: no limit. Devices already admitted come back after the
* deadline.
*/
code_validity_min: number,
/**
* Start the host when the user session opens (#32).
*/
autostart: boolean, close_action: CloseAction,
/**
* Ask for confirmation before quitting during a share (#43).
*/
confirm_quit: boolean, trusted_devices: Array<TrustedDevice>, };
@@ -0,0 +1,14 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* What a settings change produces.
*/
export type SettingsOutcome = {
/**
* Fields applied right away.
*/
immediate: Array<string>,
/**
* Fields waiting for the next share, with the reason.
*/
next_share: Array<string>, };
+42
View File
@@ -0,0 +1,42 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { SharedSource } from "./SharedSource";
import type { ViewerDevice } from "./ViewerDevice";
/**
* A share in progress.
*/
export type Share = { source: SharedSource, room: string,
/**
* The URL to hand out, token included, on the LAN address.
*/
url: string,
/**
* The QR code of `url`, as SVG.
*/
qr_svg: string,
/**
* Short code to type without a camera, lowercase: the interface groups it.
*/
code: string,
/**
* Expiry of the token and the code, in Unix milliseconds. `None`: no
* limit.
*/
expires_ms: number | null,
/**
* The expiry has passed: no new device gets in until the host draws a
* new code.
*/
access_expired: boolean,
/**
* SHA-256 fingerprint of the certificate, over HTTPS only.
*/
fingerprint: string | null,
/**
* Actual listen address and port (`0.0.0.0:8099`, `192.168.1.20:9000`).
*/
listen: string,
/**
* Chosen interface, `None` if the host listens everywhere.
*/
interface: string | null, devices: Array<ViewerDevice>, limit: number, started_ms: number, };
+16
View File
@@ -0,0 +1,16 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { SourceKind } from "../../../viewer/src/proto/SourceKind";
import type { Label } from "./Label";
/**
* The source being shared.
*/
export type SharedSource = { kind: SourceKind, name: string, label: Label,
/**
* `portal`, `x11`, `synthetic` or `ivf`.
*/
backend: string,
/**
* Current encoded size: it follows a resolution change.
*/
width: number, height: number, };
+15
View File
@@ -0,0 +1,15 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* What the user chooses to share. The interface sends back the `choice` of a
* [`SourceOption`] as is.
*/
export type SourceChoice = { "type": "synthetic", width: number, height: number, } | { "type": "x11", id: string, } | { "type": "portal", virtual_display: boolean,
/**
* A window rather than a screen (#17), if the portal allows it.
*/
window: boolean,
/**
* Size of a virtual screen. Ignored for an existing screen.
*/
size: [number, number] | null, } | { "type": "playback", path: string, };
+7
View File
@@ -0,0 +1,7 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* What to know about a source before choosing it, translated by the
* interface.
*/
export type SourceNote = "portal_screen" | "portal_window" | "portal_no_window" | "virtual_screen" | "test_pattern" | "no_pipewire" | "minimized";
+35
View File
@@ -0,0 +1,35 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { SourceKind } from "../../../viewer/src/proto/SourceKind";
import type { Label } from "./Label";
import type { SourceChoice } from "./SourceChoice";
import type { SourceNote } from "./SourceNote";
/**
* A source offered in the list.
*/
export type SourceOption = { choice: SourceChoice, kind: SourceKind,
/**
* English name, for the command line. A window title may be in it: it
* stays in the local interface, never in the log (ADR 0008).
*/
name: string,
/**
* The name to display, which the interface translates.
*/
label: Label, width: number, height: number,
/**
* Thumbnail as a `data:image/png` URL, when the platform allows taking
* one without consent (X11). Never under Wayland: the portal shows
* nothing before the user agrees.
*/
thumbnail: string | null,
/**
* What to know before choosing ("the desktop will ask which one").
*/
note: SourceNote | null,
/**
* False for a source that is listed but not shareable right now
* (minimized window, desktop that cannot share a window): the note says
* why, before starting and not after (#17).
*/
available: boolean, };
+11
View File
@@ -0,0 +1,11 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* Why the last share stopped, when it was not the user.
*/
export type Stop = { reason: string,
/**
* Stopped from the desktop ("stop sharing" button, screen unplugged):
* the command line then exits with code 3.
*/
by_desktop: boolean, };
+6
View File
@@ -0,0 +1,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* Theme of the host interface.
*/
export type Theme = "system" | "light" | "dark";
@@ -0,0 +1,8 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { DeviceId } from "../../../viewer/src/proto/DeviceId";
/**
* A device allowed to come back without scanning again (#34). The storage
* exists already so that the format does not need a new version that day.
*/
export type TrustedDevice = { id: DeviceId, name: string, };
+14
View File
@@ -0,0 +1,14 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* A connected viewer.
*/
export type ViewerDevice = {
/**
* Number to send back to disconnect it.
*/
connection: number, name: string, platform: string | null, address: string,
/**
* Arrival, in Unix milliseconds.
*/
since_ms: number, };
@@ -0,0 +1,52 @@
import { useId, useState } from 'react';
import { useI18n } from '../i18n';
type Props = {
viewers: number;
onCancel: () => void;
onQuit: (dontAskAgain: boolean) => void;
};
/**
* Quitting during a share (#43): say so before cutting the viewers off.
* "Don't ask again" can be turned back on in the settings.
*/
export function ConfirmQuit({ viewers, onCancel, onQuit }: Props) {
const { t } = useI18n();
const [dontAskAgain, setDontAskAgain] = useState(false);
const id = useId();
return (
<div className='overlay'>
<div
className='dialog'
role='alertdialog'
aria-modal='true'
aria-labelledby={`${id}-title`}
aria-describedby={`${id}-text`}
onKeyDown={(e) => e.key === 'Escape' && onCancel()}
>
<h2 id={`${id}-title`}>{t('quitTitle')}</h2>
<p id={`${id}-text`}>{t('quitText', { count: viewers })}</p>
<label className='checkbox'>
<input
type='checkbox'
checked={dontAskAgain}
onChange={(e) => setDontAskAgain(e.target.checked)}
/>
{t('dontAskAgain')}
</label>
<div className='dialog-actions'>
<span className='spacer' />
{/* biome-ignore lint/a11y/noAutofocus: the safe choice gets the focus, Enter stops nothing */}
<button type='button' className='button' onClick={onCancel} autoFocus>
{t('cancel')}
</button>
<button type='button' className='button danger' onClick={() => onQuit(dontAskAgain)}>
{t('quitConfirm')}
</button>
</div>
</div>
</div>
);
}
@@ -0,0 +1,303 @@
import { useEffect, useId, useState } from 'react';
import type { QualityPreset } from '../../../viewer/src/proto/QualityPreset';
import type { CloseAction } from '../bindings/CloseAction';
import type { Codec } from '../bindings/Codec';
import type { InterfaceOption } from '../bindings/InterfaceOption';
import type { Rejection } from '../bindings/Rejection';
import type { Settings } from '../bindings/Settings';
import type { SettingsOutcome } from '../bindings/SettingsOutcome';
import type { Theme } from '../bindings/Theme';
import { LANGUAGES, useI18n } from '../i18n';
import { type Host, rejectionsOf } from '../lib/host';
import { outcomeSummary } from '../lib/view';
const QUALITIES: QualityPreset[] = ['saver', 'balanced', 'sharp'];
const CODECS: Codec[] = ['vp8', 'vp9'];
const THEMES: Theme[] = ['system', 'light', 'dark'];
const CLOSE_ACTIONS: CloseAction[] = ['tray', 'quit'];
type Props = {
host: Host;
autostart: boolean;
onClose: () => void;
onSaved: (settings: Settings) => void;
};
export function SettingsDialog({ host, autostart, onClose, onSaved }: Props) {
const { t } = useI18n();
const [settings, setSettings] = useState<Settings | null>(null);
const [interfaces, setInterfaces] = useState<InterfaceOption[]>([]);
const [rejections, setRejections] = useState<Rejection[]>([]);
// What is kept is the fact, not its sentence: changing the language while
// saving also retranslates the confirmation.
const [message, setMessage] = useState<
{ type: 'outcome'; outcome: SettingsOutcome } | { type: 'diagnostics'; path: string } | null
>(null);
const [sending, setSending] = useState(false);
const id = useId();
useEffect(() => {
host.settings().then(setSettings);
host.interfaces().then(setInterfaces);
}, [host]);
if (!settings) {
return null;
}
const change = <K extends keyof Settings>(field: K, value: Settings[K]) => {
setSettings({ ...settings, [field]: value });
setRejections((r) => r.filter((x) => x.field !== field));
setMessage(null);
};
const error = (field: string) => rejections.find((r) => r.field === field)?.message;
const save = async () => {
setSending(true);
try {
const outcome = await host.updateSettings(settings);
setRejections([]);
setMessage({ type: 'outcome', outcome });
onSaved(settings);
} catch (e) {
setRejections(rejectionsOf(e));
setMessage(null);
} finally {
setSending(false);
}
};
const exportDiagnostics = async () => {
try {
setMessage({ type: 'diagnostics', path: await host.exportDiagnostics() });
} catch (e) {
setRejections([{ field: 'diagnostics', message: String(e) }]);
}
};
// A chosen interface missing from the list (unplugged) stays displayed, so
// that the saved setting does not vanish silently.
const missing =
settings.interface !== null && !interfaces.some((i) => i.name === settings.interface);
return (
<div className='overlay'>
<div
className='dialog'
role='dialog'
aria-modal='true'
aria-labelledby={`${id}-title`}
onKeyDown={(e) => e.key === 'Escape' && onClose()}
>
<h2 id={`${id}-title`}>{t('settings')}</h2>
<form
className='form'
onSubmit={(e) => {
e.preventDefault();
save();
}}
>
<Field
id={`${id}-port`}
label={t('portField')}
help={t('portHelp')}
error={error('port')}
>
<input
id={`${id}-port`}
type='number'
min={1024}
max={65535}
value={settings.port}
onChange={(e) => change('port', Number(e.target.value))}
/>
</Field>
<Field
id={`${id}-interface`}
label={t('interface')}
help={t('interfaceHelp')}
error={error('interface')}
>
<select
id={`${id}-interface`}
value={settings.interface ?? ''}
onChange={(e) => change('interface', e.target.value === '' ? null : e.target.value)}
>
<option value=''>{t('allInterfaces')}</option>
{interfaces.map((i) => (
<option key={i.name} value={i.name}>
{i.name} ({i.addresses.join(', ')}){i.active ? '' : `, ${t('interfaceInactive')}`}
</option>
))}
{missing && settings.interface && (
<option value={settings.interface}>
{settings.interface}, {t('interfaceInactive')}
</option>
)}
</select>
</Field>
<Field id={`${id}-limit`} label={t('limit')} error={error('limit')}>
<input
id={`${id}-limit`}
type='number'
min={1}
max={20}
value={settings.limit}
onChange={(e) => change('limit', Number(e.target.value))}
/>
</Field>
<Field
id={`${id}-validity`}
label={t('codeValidity')}
help={t('codeValidityHelp')}
error={error('code_validity_min')}
>
<input
id={`${id}-validity`}
type='number'
min={0}
max={1440}
value={settings.code_validity_min}
onChange={(e) => change('code_validity_min', Number(e.target.value))}
/>
</Field>
<Field id={`${id}-quality`} label={t('quality')} error={error('quality')}>
<select
id={`${id}-quality`}
value={settings.quality}
onChange={(e) => change('quality', e.target.value as QualityPreset)}
>
{QUALITIES.map((q) => (
<option key={q} value={q}>
{t(`qualities.${q}`)}
</option>
))}
</select>
</Field>
<Field id={`${id}-codec`} label={t('codec')} help={t('codecHelp')} error={error('codec')}>
<select
id={`${id}-codec`}
value={settings.codec}
onChange={(e) => change('codec', e.target.value as Codec)}
>
{CODECS.map((c) => (
<option key={c} value={c}>
{t(`codecs.${c}`)}
</option>
))}
</select>
</Field>
<Field id={`${id}-theme`} label={t('theme')}>
<select
id={`${id}-theme`}
value={settings.theme}
onChange={(e) => change('theme', e.target.value as Theme)}
>
{THEMES.map((theme) => (
<option key={theme} value={theme}>
{t(`themes.${theme}`)}
</option>
))}
</select>
</Field>
<Field id={`${id}-language`} label={t('language')}>
<select
id={`${id}-language`}
value={settings.language ?? ''}
onChange={(e) => change('language', e.target.value === '' ? null : e.target.value)}
>
<option value=''>{t('languageSystem')}</option>
{LANGUAGES.map((l) => (
<option key={l.code} value={l.code} lang={l.code}>
{l.name}
</option>
))}
</select>
</Field>
<Field id={`${id}-close-action`} label={t('closeAction')} help={t('closeActionHelp')}>
<select
id={`${id}-close-action`}
value={settings.close_action}
onChange={(e) => change('close_action', e.target.value as CloseAction)}
>
{CLOSE_ACTIONS.map((a) => (
<option key={a} value={a}>
{t(`closeActions.${a}`)}
</option>
))}
</select>
</Field>
<label className='checkbox'>
<input
type='checkbox'
checked={settings.confirm_quit}
onChange={(e) => change('confirm_quit', e.target.checked)}
/>
{t('confirmQuit')}
</label>
{autostart && (
<label className='checkbox'>
<input
type='checkbox'
checked={settings.autostart}
onChange={(e) => change('autostart', e.target.checked)}
/>
{t('autostart')}
{error('autostart') && <span className='field-error'>{error('autostart')}</span>}
</label>
)}
{error('file') && <p className='field-error'>{error('file')}</p>}
{message && (
<p className='confirmation' role='status'>
{message.type === 'outcome'
? outcomeSummary(message.outcome, t)
: t('diagnosticsWritten', { path: message.path })}
</p>
)}
<div className='dialog-actions'>
<button type='button' className='button muted' onClick={exportDiagnostics}>
{t('diagnostics')}
</button>
<span className='spacer' />
<button type='button' className='button muted' onClick={onClose}>
{t('close')}
</button>
<button type='submit' className='button primary' disabled={sending}>
{t('save')}
</button>
</div>
<p className='help'>{t('diagnosticsHelp')}</p>
{error('diagnostics') && <p className='field-error'>{error('diagnostics')}</p>}
</form>
</div>
</div>
);
}
function Field({
id,
label,
help,
error,
children,
}: {
id: string;
label: string;
help?: string;
error?: string | undefined;
children: React.ReactNode;
}) {
return (
<div className={`field${error ? ' has-error' : ''}`}>
<label htmlFor={id}>{label}</label>
{children}
{error ? (
<span className='field-error' role='alert'>
{error}
</span>
) : (
help && <span className='help'>{help}</span>
)}
</div>
);
}
+142
View File
@@ -0,0 +1,142 @@
import { useEffect, useState } from 'react';
import type { Share } from '../bindings/Share';
import { useI18n } from '../i18n';
import { displayCode, displayName, duration, expiry } from '../lib/view';
type Props = {
share: Share;
onDisconnect: (connection: number) => void;
onNewCode: () => void;
};
export function SharePanel({ share, onDisconnect, onNewCode }: Props) {
const { t } = useI18n();
const now = useNow();
const [copied, setCopied] = useState(false);
const copy = async () => {
try {
await navigator.clipboard.writeText(share.url);
setCopied(true);
setTimeout(() => setCopied(false), 1500);
} catch {
setCopied(false);
}
};
const [address] = share.listen.split(':');
const home = share.url.split('/r/')[0] ?? share.url;
const remaining = expiry(share.expires_ms, now, t);
return (
<section className='share'>
<div className='card qr-card'>
<h2>{t('scan')}</h2>
{/* SVG produced by the host (rs-signaling::qr), never by an outside input. */}
<div
className='qr'
role='img'
aria-label={share.url}
// biome-ignore lint/security/noDangerouslySetInnerHtml: SVG generated by the local host
dangerouslySetInnerHTML={{ __html: share.qr_svg }}
/>
<label className='link'>
<span>{t('link')}</span>
<span className='link-row'>
<input readOnly value={share.url} onFocus={(e) => e.target.select()} />
<button type='button' className='button' onClick={copy}>
{copied ? t('copied') : t('copy')}
</button>
</span>
</label>
<div className={`short-code ${share.access_expired ? 'code-expired' : ''}`}>
<span className='muted'>
{t('code')} {t('codeHelp', { home })}
</span>
<strong className='code-value' aria-live='polite'>
{displayCode(share.code)}
</strong>
{remaining && (
<span className={share.access_expired ? 'warning-text' : 'muted'}>{remaining}</span>
)}
<button
type='button'
className='button muted code-new'
title={t('newCodeHelp')}
onClick={onNewCode}
>
{t('newCode')}
</button>
</div>
{share.fingerprint && (
<p className='fingerprint'>
{t('fingerprint')}: <code>{share.fingerprint}</code>
</p>
)}
</div>
<div className='card'>
<dl className='facts'>
<dt>{t('source')}</dt>
<dd>
{displayName(share.source.label, t)}
<span className='muted'>
{' '}
{share.source.width} × {share.source.height}
</span>
</dd>
<dt>{t('listen')}</dt>
<dd>
{share.interface ? `${share.interface} (${address})` : t('allInterfaces')}
<span className='muted'>
{' '}
{t('port', { port: share.listen.split(':').pop() ?? '' })}
</span>
</dd>
<dt>{t('since')}</dt>
<dd>{duration(share.started_ms, now)}</dd>
</dl>
<h2 className='viewers-title'>
{t('viewers')}
<span className='counter'>
{t('seats', { n: share.devices.length, limit: share.limit })}
</span>
</h2>
{share.devices.length === 0 ? (
<p className='help'>{t('nobody')}</p>
) : (
<ul className='devices'>
{share.devices.map((device) => (
<li key={device.connection}>
<span className='device-name'>{device.name}</span>
<span className='muted'>
{[device.platform, device.address].filter(Boolean).join(' · ')}
{' · '}
{duration(device.since_ms, now)}
</span>
<button
type='button'
className='button muted danger'
title={t('disconnectHelp')}
onClick={() => onDisconnect(device.connection)}
>
{t('disconnect')}
</button>
</li>
))}
</ul>
)}
</div>
</section>
);
}
/** The current time, refreshed every second for the displayed durations. */
function useNow(): number {
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
const timer = setInterval(() => setNow(Date.now()), 1000);
return () => clearInterval(timer);
}, []);
return now;
}
@@ -0,0 +1,83 @@
import { useMemo, useState } from 'react';
import type { SourceChoice } from '../bindings/SourceChoice';
import type { SourceOption } from '../bindings/SourceOption';
import { useI18n } from '../i18n';
import { displayName, filter, key } from '../lib/view';
type Props = {
sources: SourceOption[] | null;
selection: SourceChoice | null;
enabled: boolean;
onPick: (choice: SourceChoice) => void;
onRefresh: () => void;
};
/** Beyond this, the list gets long to scan: the search field appears. */
const SEARCH_THRESHOLD = 6;
export function SourcePicker({ sources, selection, enabled, onPick, onRefresh }: Props) {
const { t } = useI18n();
const [search, setSearch] = useState('');
const visible = useMemo(() => filter(sources ?? [], search, t), [sources, search, t]);
const picked = selection ? key(selection) : null;
return (
<section className='picker' aria-labelledby='picker-title'>
<div className='picker-header'>
<h2 id='picker-title'>{t('pickTitle')}</h2>
{sources && sources.length > SEARCH_THRESHOLD && (
<input
type='search'
className='search'
placeholder={t('search')}
aria-label={t('search')}
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
)}
<button type='button' className='button muted' onClick={onRefresh} disabled={!enabled}>
{t('refresh')}
</button>
</div>
{sources === null && <p className='help'>{t('loadingSources')}</p>}
{sources !== null && visible.length === 0 && <p className='help'>{t('noSource')}</p>}
<ul className='sources'>
{visible.map((source) => {
const id = key(source.choice);
const name = displayName(source.label, t);
const selected = id === picked;
return (
<li key={id}>
<button
type='button'
className={`source${selected ? ' selected' : ''}${source.available ? '' : ' unavailable'}`}
aria-pressed={selected}
disabled={!enabled || !source.available}
onClick={() => onPick(source.choice)}
>
<span className='thumbnail'>
{source.thumbnail ? (
<img src={source.thumbnail} alt='' />
) : (
<span className='thumbnail-empty' aria-hidden='true'>
{source.kind === 'window' ? '▭' : '▣'}
</span>
)}
</span>
<span className='source-name' title={name}>
{name}
</span>
{source.width > 0 && (
<span className='source-size'>
{source.width} × {source.height}
</span>
)}
{source.note && <span className='source-note'>{t(`notes.${source.note}`)}</span>}
</button>
</li>
);
})}
</ul>
</section>
);
}
+66
View File
@@ -0,0 +1,66 @@
import { createContext, type ReactNode, useContext, useMemo } from 'react';
import {
type AvailableLanguage,
type Catalog,
createTranslator,
FALLBACK_LANGUAGE,
pickLanguage,
type Translate,
} from '../../viewer/src/lib/i18n';
/**
* Texts of the shell (#21). The same files as the viewer (`locales/*.json`),
* embedded at build time: the shell has no server to ask when no share is
* running. A file added to the folder is one more language, with no code to
* change.
*/
type LocaleFile = Catalog & { _language: AvailableLanguage };
const FILES = Object.values(
import.meta.glob<LocaleFile>('../../../locales/*.json', { eager: true, import: 'default' }),
);
/** The embedded languages, by code. */
export const LANGUAGES: AvailableLanguage[] = FILES.map((f) => f._language).sort((a, b) =>
a.name.localeCompare(b.name),
);
function catalog(code: string): Catalog | undefined {
return FILES.find((f) => f._language.code === code);
}
/**
* The language to display: the setting if it names an embedded language,
* otherwise the desktop's (`navigator.languages` reflects the session locale).
*/
export function effectiveLanguage(setting: string | null, preferences: readonly string[]): string {
const codes = LANGUAGES.map((l) => l.code);
if (setting && codes.includes(setting)) return setting;
return pickLanguage(preferences, codes);
}
/** The shell translation in `code`, English as fallback. */
export function translatorFor(code: string): Translate {
const catalogs = [catalog(code), catalog(FALLBACK_LANGUAGE)].filter(
(c): c is Catalog => c !== undefined,
);
return createTranslator(code, 'desktop', catalogs);
}
type Context = { t: Translate; language: string };
const I18n = createContext<Context | null>(null);
export function useI18n(): Context {
const context = useContext(I18n);
if (!context) throw new Error('useI18n outside of I18nProvider');
return context;
}
/** Changing `language` retranslates everything at the next render, without a restart. */
export function I18nProvider({ language, children }: { language: string; children: ReactNode }) {
const value = useMemo(() => ({ t: translatorFor(language), language }), [language]);
return <I18n.Provider value={value}>{children}</I18n.Provider>;
}
+62
View File
@@ -0,0 +1,62 @@
import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
import type { HostState } from '../bindings/HostState';
import type { InterfaceOption } from '../bindings/InterfaceOption';
import type { Rejection } from '../bindings/Rejection';
import type { Settings } from '../bindings/Settings';
import type { SettingsOutcome } from '../bindings/SettingsOutcome';
import type { SourceChoice } from '../bindings/SourceChoice';
import type { SourceOption } from '../bindings/SourceOption';
import type { TrayTexts } from './view';
/**
* What the interface can ask of the host. A single real implementation,
* through the Tauri commands; the tests provide a fake one.
*/
export type Host = {
state(): Promise<HostState>;
/** Returns the function that stops listening. */
listen(callback: (state: HostState) => void): Promise<() => void>;
sources(): Promise<SourceOption[]>;
start(choice: SourceChoice): Promise<void>;
stop(): Promise<void>;
disconnect(connection: number): Promise<boolean>;
/** New QR code and new short code (#19). */
regenerateAccess(): Promise<boolean>;
settings(): Promise<Settings>;
/** Rejects with the list of refused values. */
updateSettings(settings: Settings): Promise<SettingsOutcome>;
interfaces(): Promise<InterfaceOption[]>;
/** Returns the path of the written archive. */
exportDiagnostics(): Promise<string>;
/** The texts of the system tray menu, in the language of the interface. */
translateTray(texts: TrayTexts): Promise<void>;
/** The host asks for confirmation before quitting (#43). */
listenQuit(callback: () => void): Promise<() => void>;
quit(dontAskAgain: boolean): Promise<void>;
};
export const tauriHost: Host = {
state: () => invoke<HostState>('state'),
listen: (callback) => listen<HostState>('state', (event) => callback(event.payload)),
sources: () => invoke<SourceOption[]>('sources'),
start: (choice) => invoke<void>('start', { choice }),
stop: () => invoke<void>('stop'),
disconnect: (connection) => invoke<boolean>('disconnect', { connection }),
regenerateAccess: () => invoke<boolean>('regenerate_access'),
settings: () => invoke<Settings>('settings'),
updateSettings: (settings) => invoke<SettingsOutcome>('update_settings', { settings }),
interfaces: () => invoke<InterfaceOption[]>('interfaces'),
exportDiagnostics: () => invoke<string>('export_diagnostics'),
translateTray: (texts) => invoke<void>('translate_tray', { texts }),
listenQuit: (callback) => listen('confirm-quit', () => callback()),
quit: (dontAskAgain) => invoke<void>('quit', { dontAskAgain }),
};
/** Rejections from Rust arrive as is; any other failure becomes a global rejection. */
export function rejectionsOf(error: unknown): Rejection[] {
if (Array.isArray(error)) {
return error as Rejection[];
}
return [{ field: 'file', message: String(error) }];
}
+196
View File
@@ -0,0 +1,196 @@
import { describe, expect, it } from 'vitest';
import type { HostState } from '../bindings/HostState';
import type { Share } from '../bindings/Share';
import type { SourceOption } from '../bindings/SourceOption';
import { effectiveLanguage, LANGUAGES, translatorFor } from '../i18n';
import {
actions,
displayCode,
displayName,
duration,
expiry,
filter,
key,
outcomeSummary,
status,
trayTexts,
} from './view';
const t = translatorFor('fr');
function state(phase: HostState['phase'], share: Share | null = null): HostState {
return {
phase,
share,
error: null,
stop: null,
warnings: [],
sleep_inhibited: [],
pending_settings: [],
settings_recovered: null,
capabilities: {
session: 'wayland',
desktop: 'Gnome',
portal: true,
virtual_display: true,
pipewire: true,
autostart: true,
},
};
}
const pattern = { type: 'synthetic', width: 1280, height: 720 } as const;
describe('the buttons follow the host state (#15, no button that lies)', () => {
it('stopped: start only with a chosen source', () => {
expect(actions(state('stopped'), null, false).start).toEqual({ visible: true, enabled: false });
expect(actions(state('stopped'), pattern, false).start).toEqual({
visible: true,
enabled: true,
});
expect(actions(state('stopped'), pattern, false).stop.visible).toBe(false);
});
it('a command in flight is not sent twice', () => {
const a = actions(state('stopped'), pattern, true);
expect(a.start.enabled).toBe(false);
expect(a.pick).toBe(false);
});
it('while starting: neither start nor change the source, cancel possible', () => {
const a = actions(state('starting'), pattern, true);
expect(a.start.visible).toBe(false);
expect(a.pick).toBe(false);
expect(a.cancel).toEqual({ visible: true, enabled: true });
});
it('live: stop only', () => {
const a = actions(state('live'), pattern, false);
expect(a.stop).toEqual({ visible: true, enabled: true });
expect(a.start.visible).toBe(false);
expect(a.cancel.visible).toBe(false);
});
});
describe('status', () => {
it('counts the viewers', () => {
const share = { devices: [{}, {}] } as unknown as Share;
expect(status(state('live', share), t).text).toBe('En direct, 2 spectateurs');
const nobody = status(state('live', { devices: [] } as unknown as Share), t);
expect(nobody).toEqual({ text: 'En direct, personne ne regarde', tone: 'live' });
expect(status(state('starting'), t).tone).toBe('waiting');
const en = translatorFor('en');
expect(status(state('live', share), en).text).toBe('Live, 2 viewers');
});
});
describe('sources', () => {
const source = (name: string, id: string): SourceOption => ({
choice: { type: 'x11', id },
kind: 'window',
name,
label: { type: 'title', text: name },
width: 800,
height: 600,
thumbnail: null,
note: null,
available: true,
});
it('the search ignores accents and case', () => {
const list = [source('Présentation.odp', 'a'), source('Terminal', 'b')];
expect(filter(list, 'presen', t).map((s) => s.name)).toEqual(['Présentation.odp']);
expect(filter(list, ' ', t)).toHaveLength(2);
});
it('the search looks at the displayed name, in the language of the interface (#21)', () => {
const pattern: SourceOption = {
...source('Mire de test', 'm'),
choice: { type: 'synthetic', width: 64, height: 64 },
label: { type: 'test_pattern' },
};
expect(filter([pattern], 'test pattern', translatorFor('en'))).toHaveLength(1);
expect(displayName({ type: 'monitor', output: 'HDMI-1', primary: true }, t)).toBe(
'HDMI-1 (principal)',
);
});
it('every label has a name in English and in French', () => {
const labels = [
'screen',
'window',
'virtual_screen',
'test_pattern',
'recorded_pattern',
'all_screens',
'entire_screen',
'chosen_screen',
'chosen_window',
] as const;
for (const type of labels) {
expect(displayName({ type }, t)).not.toBe('');
expect(displayName({ type }, translatorFor('en'))).not.toBe('');
}
});
it('the key tells an existing screen from a virtual one', () => {
expect(key({ type: 'portal', virtual_display: false, window: true, size: null })).not.toBe(
key({ type: 'portal', virtual_display: false, window: false, size: null }),
);
expect(key({ type: 'portal', virtual_display: true, window: false, size: null })).not.toBe(
key({ type: 'portal', virtual_display: false, window: false, size: null }),
);
});
});
describe('texts', () => {
it('durations stay short', () => {
expect(duration(0, 42_000)).toBe('42 s');
expect(duration(0, 5 * 60_000)).toBe('5 min');
expect(duration(0, 65 * 60_000)).toBe('1 h 05');
expect(duration(10_000, 0)).toBe('0 s');
});
it('a pending setting is said', () => {
expect(outcomeSummary({ immediate: ['limit'], next_share: [] }, t)).toContain('appliqués');
expect(outcomeSummary({ immediate: [], next_share: ['port: would cut'] }, t)).toContain(
'prochain partage',
);
});
});
describe('short code (#19)', () => {
it('shows in two groups of three', () => {
expect(displayCode('k7m4pq')).toBe('K7M 4PQ');
});
it('says what is left, in seconds during the last minute', () => {
expect(expiry(null, 0, t)).toBeNull();
expect(expiry(10 * 60_000, 0, t)).toContain('10 min');
expect(expiry(30_000, 0, t)).toContain('30 s');
expect(expiry(0, 1, t)).toBe(t('codeExpired'));
});
});
describe('language (#21)', () => {
it('French and English are embedded', () => {
const codes = LANGUAGES.map((l) => l.code);
expect(codes).toContain('fr');
expect(codes).toContain('en');
expect(LANGUAGES.find((l) => l.code === 'fr')?.name).toBe('Français');
});
it('the setting wins, then the desktop language, then English', () => {
expect(effectiveLanguage('fr', ['en-US'])).toBe('fr');
expect(effectiveLanguage(null, ['fr-FR'])).toBe('fr');
expect(effectiveLanguage(null, ['de-DE'])).toBe('en');
expect(effectiveLanguage('xx', ['fr-BE'])).toBe('fr');
});
it('the system tray gets the three forms, {count} to replace', () => {
const tray = trayTexts(t);
expect(tray.live.zero).toBe('En direct, personne ne regarde');
expect(tray.live.one).toBe('En direct, 1 spectateur');
expect(tray.live.other).toBe('En direct, {count} spectateurs');
});
});
+208
View File
@@ -0,0 +1,208 @@
import type { Translate } from '../../../viewer/src/lib/i18n';
import type { HostState } from '../bindings/HostState';
import type { Label } from '../bindings/Label';
import type { SettingsOutcome } from '../bindings/SettingsOutcome';
import type { SourceChoice } from '../bindings/SourceChoice';
import type { SourceOption } from '../bindings/SourceOption';
/**
* What the buttons show, derived from the host state and nothing else.
*
* This is the criterion of #15, "no button that lies": a button has no state
* of its own. `sending` only says that a command went out and that its answer
* has not come back, so as not to send it twice.
*/
export type Actions = {
/** The source list is clickable. */
pick: boolean;
start: { visible: boolean; enabled: boolean };
cancel: { visible: boolean; enabled: boolean };
stop: { visible: boolean; enabled: boolean };
};
export function actions(
state: HostState,
selection: SourceChoice | null,
sending: boolean,
): Actions {
switch (state.phase) {
case 'stopped':
return {
pick: !sending,
start: { visible: true, enabled: selection !== null && !sending },
cancel: { visible: false, enabled: false },
stop: { visible: false, enabled: false },
};
case 'starting':
return {
pick: false,
start: { visible: false, enabled: false },
cancel: { visible: true, enabled: true },
stop: { visible: false, enabled: false },
};
case 'live':
return {
pick: false,
start: { visible: false, enabled: false },
cancel: { visible: false, enabled: false },
stop: { visible: true, enabled: !sending },
};
}
}
export type Status = { text: string; tone: 'idle' | 'waiting' | 'live' };
export function status(state: HostState, t: Translate): Status {
switch (state.phase) {
case 'stopped':
return { text: t('statusStopped'), tone: 'idle' };
case 'starting':
return { text: t('statusStarting'), tone: 'waiting' };
case 'live': {
const n = state.share?.devices.length ?? 0;
return { text: t('statusLive', { count: n }), tone: 'live' };
}
}
}
/** Stable identity of a choice, for the selection and React keys. */
export function key(choice: SourceChoice): string {
switch (choice.type) {
case 'x11':
return `x11:${choice.id}`;
case 'portal':
if (choice.virtual_display) return 'portal:virtual';
return choice.window ? 'portal:window' : 'portal:screen';
case 'synthetic':
return 'synthetic';
case 'playback':
return `playback:${choice.path}`;
}
}
function normalize(text: string): string {
return text
.normalize('NFD')
.replace(/\p{Diacritic}/gu, '')
.toLowerCase();
}
/**
* Search by displayed name, ignoring accents and case: one searches for what
* one reads, in the language of the interface.
*/
export function filter(sources: SourceOption[], search: string, t: Translate): SourceOption[] {
const wanted = normalize(search.trim());
if (wanted === '') {
return sources;
}
return sources.filter((s) => normalize(displayName(s.label, t)).includes(wanted));
}
/** The name of a source in the language of the interface (#21). */
export function displayName(label: Label, t: Translate): string {
switch (label.type) {
case 'title':
return label.text;
case 'monitor':
return label.primary ? t('sources.primary', { output: label.output }) : label.output;
case 'screen':
return t('sources.screen');
case 'window':
return t('sources.window');
case 'virtual_screen':
return t('sources.virtual_screen');
case 'test_pattern':
return t('sources.test_pattern');
case 'recorded_pattern':
return t('sources.recorded_pattern');
case 'all_screens':
return t('sources.all_screens');
case 'entire_screen':
return t('sources.entire_screen');
case 'chosen_screen':
return t('sources.chosen_screen');
case 'chosen_window':
return t('sources.chosen_window');
}
}
/** Readable duration since a Unix date in milliseconds. */
export function duration(sinceMs: number, nowMs: number): string {
const seconds = Math.max(0, Math.floor((nowMs - sinceMs) / 1000));
if (seconds < 60) {
return `${seconds} s`;
}
const minutes = Math.floor(seconds / 60);
if (minutes < 60) {
return `${minutes} min`;
}
const hours = Math.floor(minutes / 60);
return `${hours} h ${String(minutes % 60).padStart(2, '0')}`;
}
/** What is said after saving settings. */
export function outcomeSummary(outcome: SettingsOutcome, t: Translate): string {
if (outcome.next_share.length > 0) {
return t('settingsPending', { fields: outcome.next_share.join('; ') });
}
if (outcome.immediate.length > 0) {
return t('settingsApplied');
}
return t('settingsUnchanged');
}
/** The short code as it is read and dictated: `K7M 4PQ`. */
export function displayCode(code: string): string {
const upper = code.toUpperCase();
return upper.length === 6 ? `${upper.slice(0, 3)} ${upper.slice(3)}` : upper;
}
/**
* What remains of the access code, in plain words, or `null` if it does not
* expire. Under a minute, it counts in seconds: that is when the host must
* know that a newcomer is about to be refused.
*/
export function expiry(expiresMs: number | null, now: number, t: Translate): string | null {
if (expiresMs === null) return null;
const remaining = expiresMs - now;
if (remaining <= 0) return t('codeExpired');
if (remaining < 60_000)
return t('codeExpiresIn', { duration: `${Math.ceil(remaining / 1000)} s` });
return t('codeExpiresIn', { duration: `${Math.ceil(remaining / 60_000)} min` });
}
/** What the system tray menu shows, translated (#21, #22). */
export type TrayTexts = {
none: string;
starting: string;
/** Forms of the live status, by exact number then category. */
live: { zero: string; one: string; other: string };
open: string;
start: string;
resume: string;
stop: string;
quit: string;
};
/**
* The texts of the system tray. Rust does not know the plural rules of each
* language: it gets the forms for 0, 1 and the rest, with `{count}` to
* replace.
*/
export function trayTexts(t: Translate): TrayTexts {
return {
none: t('tray.none'),
starting: t('tray.starting'),
live: {
zero: t('tray.live', { count: 0 }),
one: t('tray.live', { count: 1 }),
other: t('tray.live', { count: '{count}' }),
},
open: t('tray.open'),
start: t('tray.start'),
resume: t('tray.resume'),
stop: t('tray.stop'),
quit: t('tray.quit'),
};
}
+14
View File
@@ -0,0 +1,14 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { App } from './App';
import { tauriHost } from './lib/host';
import './styles.css';
const root = document.getElementById('root');
if (!root) throw new Error('root element missing');
createRoot(root).render(
<StrictMode>
<App host={tauriHost} />
</StrictMode>,
);
+559
View File
@@ -0,0 +1,559 @@
/* Desktop shell. System fonts, no remote resource. Sizes in rem: the
interface follows the desktop scale factor (HiDPI) without images to double. */
:root {
--bg: #f5f6f8;
--surface: #ffffff;
--border: #d9dee5;
--text: #18202a;
--muted: #5d6b7c;
--accent: #2563eb;
--accent-text: #ffffff;
/* Dark enough for text on a light background: AA contrast (4.5:1) checked
for each text and background pair (#28). */
--live: #15803d;
--waiting: #b45309;
--danger: #b91c1c;
--warning-bg: #fff7e6;
--error-bg: #fdecec;
--info-bg: #eaf1ff;
--radius: 10px;
color-scheme: light;
font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Cantarell", sans-serif;
font-size: 15px;
}
:root[data-theme="dark"] {
--bg: #0d1116;
--surface: #151b23;
--border: #2a3441;
--text: #e9eef5;
--muted: #97a5b6;
--accent: #4c9aff;
--accent-text: #0d1116;
--live: #3ddc84;
--waiting: #f5a524;
--danger: #ff6b6b;
--warning-bg: #2b2210;
--error-bg: #2e1517;
--info-bg: #13213a;
color-scheme: dark;
}
@media (prefers-color-scheme: dark) {
:root[data-theme="system"] {
--bg: #0d1116;
--surface: #151b23;
--border: #2a3441;
--text: #e9eef5;
--muted: #97a5b6;
--accent: #4c9aff;
--accent-text: #0d1116;
--live: #3ddc84;
--waiting: #f5a524;
--danger: #ff6b6b;
--warning-bg: #2b2210;
--error-bg: #2e1517;
--info-bg: #13213a;
color-scheme: dark;
}
}
* {
box-sizing: border-box;
}
html,
body,
#root {
height: 100%;
margin: 0;
}
body {
background: var(--bg);
color: var(--text);
-webkit-font-smoothing: antialiased;
}
h1,
h2 {
margin: 0;
font-weight: 600;
}
h1 {
font-size: 1.15rem;
}
h2 {
font-size: 1rem;
}
.loading {
display: grid;
height: 100%;
place-items: center;
color: var(--muted);
}
.app {
display: flex;
height: 100%;
flex-direction: column;
}
.header,
.action-bar {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.75rem 1.25rem;
background: var(--surface);
}
.header {
border-bottom: 1px solid var(--border);
}
.action-bar {
border-top: 1px solid var(--border);
min-height: 3.75rem;
}
.spacer {
flex: 1;
}
.content {
flex: 1;
overflow: auto;
padding: 1.25rem;
}
.badge {
display: inline-flex;
align-items: center;
gap: 0.4rem;
padding: 0.2rem 0.65rem;
border-radius: 999px;
border: 1px solid var(--border);
color: var(--muted);
font-size: 0.85rem;
}
.badge::before {
content: "";
width: 0.5rem;
height: 0.5rem;
border-radius: 50%;
background: currentColor;
}
.badge.live {
color: var(--live);
border-color: currentColor;
}
.badge.waiting {
color: var(--waiting);
border-color: currentColor;
}
.sleep {
color: var(--muted);
font-size: 0.85rem;
}
.button {
padding: 0.5rem 1rem;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--surface);
color: var(--text);
font: inherit;
cursor: pointer;
}
.button:hover:not(:disabled) {
border-color: var(--accent);
}
.button:disabled {
opacity: 0.5;
cursor: default;
}
.button.primary {
background: var(--accent);
border-color: var(--accent);
color: var(--accent-text);
font-weight: 600;
}
.button.danger {
color: var(--danger);
border-color: var(--danger);
}
.button.muted {
padding: 0.35rem 0.75rem;
}
.help,
.muted {
color: var(--muted);
font-size: 0.85rem;
}
.banner {
margin-bottom: 1rem;
padding: 0.65rem 0.9rem;
border-radius: var(--radius);
border: 1px solid var(--border);
}
.banner.error {
background: var(--error-bg);
border-color: var(--danger);
}
.banner.warning {
background: var(--warning-bg);
border-color: var(--waiting);
}
.banner.info {
background: var(--info-bg);
border-color: var(--accent);
}
.picker-header {
display: flex;
align-items: center;
gap: 0.75rem;
margin-bottom: 1rem;
}
.picker-header h2 {
flex: 1;
}
.search,
.form input:not([type="checkbox"]),
.form select,
.link input {
padding: 0.45rem 0.6rem;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--bg);
color: var(--text);
font: inherit;
}
.search {
width: 16rem;
}
.sources {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(13rem, 1fr));
gap: 0.9rem;
margin: 0;
padding: 0;
list-style: none;
}
.source {
display: flex;
width: 100%;
height: 100%;
flex-direction: column;
gap: 0.3rem;
padding: 0.6rem;
border: 2px solid var(--border);
border-radius: var(--radius);
background: var(--surface);
color: var(--text);
font: inherit;
text-align: left;
cursor: pointer;
}
.source:hover:not(:disabled) {
border-color: var(--accent);
}
.source.selected {
border-color: var(--accent);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 25%, transparent);
}
.source:disabled {
cursor: default;
}
.source.unavailable {
border-style: dashed;
}
.thumbnail {
display: grid;
aspect-ratio: 16 / 9;
place-items: center;
overflow: hidden;
border-radius: 6px;
background: var(--bg);
}
/* The text keeps its contrast: only the picture fades. The note says why the
source cannot be shared (#17). */
.source:disabled .thumbnail {
opacity: 0.45;
}
.thumbnail img {
width: 100%;
height: 100%;
object-fit: contain;
}
.thumbnail-empty {
color: var(--muted);
font-size: 2.5rem;
}
.source-name {
overflow: hidden;
font-weight: 600;
text-overflow: ellipsis;
white-space: nowrap;
}
.source-size,
.source-note {
color: var(--muted);
font-size: 0.8rem;
}
.waiting {
margin: 0;
color: var(--waiting);
}
.share {
display: grid;
grid-template-columns: minmax(18rem, 22rem) 1fr;
gap: 1.25rem;
align-items: start;
}
@media (max-width: 860px) {
.share {
grid-template-columns: 1fr;
}
}
.card {
padding: 1.1rem;
border: 1px solid var(--border);
border-radius: var(--radius);
background: var(--surface);
}
.qr-card {
display: flex;
flex-direction: column;
gap: 0.9rem;
}
.qr {
padding: 0.75rem;
border-radius: 8px;
background: #ffffff;
line-height: 0;
}
.qr svg {
width: 100%;
height: auto;
}
.link {
display: flex;
flex-direction: column;
gap: 0.35rem;
font-size: 0.85rem;
color: var(--muted);
}
.link-row {
display: flex;
gap: 0.5rem;
}
.link input {
flex: 1;
min-width: 0;
font-family: ui-monospace, monospace;
font-size: 0.8rem;
}
.fingerprint code {
word-break: break-all;
}
.facts {
display: grid;
grid-template-columns: auto 1fr;
gap: 0.4rem 1rem;
margin: 0 0 1.25rem;
}
.facts dt {
color: var(--muted);
}
.facts dd {
margin: 0;
}
.viewers-title {
display: flex;
align-items: baseline;
gap: 0.6rem;
margin-bottom: 0.6rem;
}
.counter {
color: var(--muted);
font-size: 0.85rem;
font-weight: 400;
}
.devices {
margin: 0;
padding: 0;
list-style: none;
}
.devices li {
display: grid;
grid-template-columns: 1fr auto;
align-items: center;
gap: 0.15rem 0.75rem;
padding: 0.6rem 0;
border-top: 1px solid var(--border);
}
.devices li .muted {
grid-column: 1;
}
.devices li .button {
grid-column: 2;
grid-row: 1 / span 2;
}
.device-name {
font-weight: 600;
}
.overlay {
position: fixed;
inset: 0;
display: grid;
place-items: center;
padding: 1rem;
background: rgb(0 0 0 / 45%);
}
.dialog {
width: min(34rem, 100%);
max-height: 100%;
overflow: auto;
padding: 1.25rem;
border-radius: var(--radius);
background: var(--surface);
}
.form {
display: flex;
flex-direction: column;
gap: 0.9rem;
margin-top: 1rem;
}
.field {
display: flex;
flex-direction: column;
gap: 0.3rem;
}
.field label {
font-weight: 600;
}
.field.has-error input,
.field.has-error select {
border-color: var(--danger);
}
.checkbox {
display: flex;
align-items: center;
gap: 0.5rem;
}
.field-error {
color: var(--danger);
font-size: 0.85rem;
}
.confirmation {
margin: 0;
color: var(--live);
}
.dialog-actions {
display: flex;
align-items: center;
gap: 0.6rem;
}
/* Short code (#19): readable from afar, easy to dictate. */
.short-code {
display: flex;
flex-wrap: wrap;
gap: 0.35rem 0.75rem;
align-items: baseline;
font-size: 0.85rem;
}
.short-code > .muted:first-child {
flex-basis: 100%;
}
.code-value {
font:
700 1.6rem / 1.1 ui-monospace,
"SF Mono",
Menlo,
monospace;
letter-spacing: 0.12em;
color: var(--text);
}
.code-expired .code-value {
color: var(--muted);
text-decoration: line-through;
}
.code-new {
margin-left: auto;
}
.warning-text {
color: var(--waiting);
font-weight: 600;
}
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": [
"ES2022",
"DOM",
"DOM.Iterable"
],
"module": "ESNext",
"moduleResolution": "bundler",
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
"verbatimModuleSyntax": true,
"skipLibCheck": true,
"noEmit": true
},
"include": [
"src"
]
}
+16
View File
@@ -0,0 +1,16 @@
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';
// Served by Tauri from `dist`: no server, no remote resource.
export default defineConfig({
plugins: [react()],
clearScreen: false,
build: {
target: 'es2022',
sourcemap: true,
},
server: {
port: 5175,
strictPort: true,
},
});
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "@rustscreen/viewer",
"version": "0.1.1",
"version": "0.5.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@rustscreen/viewer",
"version": "0.1.1",
"version": "0.5.0",
"dependencies": {
"react": "^19.2.0",
"react-dom": "^19.2.0"
+3 -3
View File
@@ -1,14 +1,14 @@
{
"name": "@rustscreen/viewer",
"private": true,
"version": "0.1.1",
"version": "0.5.0",
"type": "module",
"description": "Client navigateur de rustscreen: reçoit le flux WebRTC de l'hôte.",
"description": "rustscreen browser client: receives the WebRTC stream from the host.",
"scripts": {
"dev": "vite",
"build": "tsc --noEmit && vite build",
"preview": "vite preview",
"lint": "biome lint src",
"lint": "biome lint src && node ../../scripts/check-i18n.mjs apps/viewer/src viewer",
"format": "biome format --write src",
"test": "vitest run"
},
+153 -26
View File
@@ -1,16 +1,30 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { ErrorPanel } from './components/ErrorPanel';
import { LanguagePicker } from './components/LanguagePicker';
import { Pairing } from './components/Pairing';
import { StatsBar } from './components/StatsBar';
import { StatusBadge } from './components/StatusBadge';
import { VideoStage } from './components/VideoStage';
import { useI18n } from './i18n';
import { barsVisible, IDLE_DELAY_MS, isCompact, readPinned, savePinned } from './lib/controls';
import { parseRoomLocation, signalingUrl } from './lib/room';
import {
nextRotation,
type Rotation,
readMirror,
readRotation,
saveMirror,
saveRotation,
} from './lib/rotation';
import { type VideoStats, ViewerSession, type ViewerState } from './lib/session';
import { strings } from './strings';
import { applyTheme, nextTheme, readTheme, saveTheme, type Theme } from './lib/theme';
import { useActivity } from './lib/useActivity';
export function App() {
const { t } = useI18n();
const location = useMemo(
() => parseRoomLocation(window.location.pathname, window.location.search),
() => parseRoomLocation(window.location.pathname, window.location.search, window.location.hash),
[],
);
const [state, setState] = useState<ViewerState>({ kind: 'connecting', attempt: 0 });
@@ -18,12 +32,18 @@ export function App() {
const [stats, setStats] = useState<VideoStats | null>(null);
const [attemptKey, setAttemptKey] = useState(0);
const [isFullscreen, setIsFullscreen] = useState(false);
const [theme, setTheme] = useState<Theme>(() => readTheme());
const [rotation, setRotation] = useState<Rotation>(() => readRotation());
const [mirror, setMirror] = useState(() => readMirror());
const [pinned, setPinned] = useState(() => readPinned());
const [held, setHeld] = useState(false);
const active = useActivity(IDLE_DELAY_MS);
const sessionRef = useRef<ViewerSession | null>(null);
const containerRef = useRef<HTMLDivElement | null>(null);
// Une session par montage. Le nettoyage est obligatoire: sans lui, le double
// montage de StrictMode ouvre deux WebSocket et deux négociations.
// biome-ignore lint/correctness/useExhaustiveDependencies: attemptKey est la clé de relance du bouton « réessayer », volontairement sans usage dans le corps.
// One session per mount. The cleanup is mandatory: without it, the double
// mount of StrictMode opens two WebSockets and two negotiations.
// biome-ignore lint/correctness/useExhaustiveDependencies: attemptKey is the restart key of the "retry" button, deliberately unused in the body.
useEffect(() => {
if (!location.ok) return;
const session = new ViewerSession({
@@ -74,48 +94,152 @@ export function App() {
}
}, []);
const cycleTheme = useCallback(() => {
setTheme((current) => {
const next = nextTheme(current);
applyTheme(next);
saveTheme(next);
return next;
});
}, []);
const rotate = useCallback(() => {
setRotation((current) => {
const next = nextRotation(current);
saveRotation(next);
return next;
});
}, []);
const toggleMirror = useCallback(() => {
setMirror((current) => {
saveMirror(!current);
return !current;
});
}, []);
const togglePinned = useCallback(() => {
setPinned((current) => {
savePinned(!current);
return !current;
});
}, []);
// Restarts a series of attempts on the existing session, without reloading
// the page: the requested quality and the wake listeners are kept. A
// session stopped for good is replaced by a new one.
const retry = useCallback(() => {
setState({ kind: 'connecting', attempt: 0 });
setStats(null);
if (sessionRef.current?.retry()) return;
setState({ kind: 'connecting', attempt: 0 });
setAttemptKey((key) => key + 1);
}, []);
if (!location.ok) {
return (
<div className='app app-centered'>
<div className='panel' role='alert'>
<h1>{strings.appName}</h1>
<p>{location.reason === 'missing_token' ? strings.missingToken : strings.missingUrl}</p>
</div>
</div>
);
// Without a session in the address, offer the short code (#19). The bare
// home page is not an error: it is the way in without a camera.
const notice = {
missing_room: null,
missing_token: t('missingToken'),
malformed: t('missingUrl'),
newer_link: t('newerLink'),
}[location.reason];
return <Pairing notice={notice} />;
}
const live = state.kind === 'streaming';
// Décision #65: HTTP assumé sur le LAN. Le spectateur doit savoir ce qui est
// chiffré (le média) et ce qui ne l'est pas (la page et le signalement).
// Decision #65: HTTP on the LAN is assumed. The viewer must know what is
// encrypted (the media) and what is not (the page and signalling).
const insecure =
window.location.protocol === 'http:' &&
window.location.hostname !== 'localhost' &&
window.location.hostname !== '127.0.0.1';
const compact = isCompact(isFullscreen, pinned);
const visible = barsVisible({ compact, live, active, held });
// The bars stay shown while the pointer or the focus is on them: a button
// about to be touched must not disappear.
const hold = {
onPointerEnter: () => setHeld(true),
onPointerLeave: () => setHeld(false),
onFocus: () => setHeld(true),
onBlur: () => setHeld(false),
};
const classes = [
'app',
isFullscreen ? 'app-fullscreen' : '',
compact ? 'app-compact' : '',
visible ? '' : 'app-hidden',
]
.filter(Boolean)
.join(' ');
return (
<div className={`app ${isFullscreen ? 'app-fullscreen' : ''}`} ref={containerRef}>
<header className='topbar'>
<span className='brand'>{strings.appName}</span>
<div className={classes} ref={containerRef}>
<header className='topbar' {...hold}>
<span className='brand'>{t('appName')}</span>
<StatusBadge state={state} />
{insecure && (
<span className='badge badge-warn' title={strings.insecureHint}>
{strings.insecureBadge}
{location.value.fingerprint && (
<span className='badge' title={`${t('fingerprint')}: ${location.value.fingerprint}`}>
{location.value.fingerprint.slice(0, 11)}
</span>
)}
{insecure && (
<span className='badge badge-warn' title={t('insecureHint')}>
{t('insecureBadge')}
</span>
)}
<button
type='button'
className='button button-ghost button-theme'
onClick={cycleTheme}
aria-label={t('themeButton', { current: t(`themes.${theme}`) })}
title={t('themeButton', { current: t(`themes.${theme}`) })}
>
{theme === 'dark' ? '☾' : theme === 'light' ? '☀' : '◐'}
</button>
{live && (
<button
type='button'
className='button button-ghost'
onClick={rotate}
aria-label={t('rotate', { degrees: rotation })}
title={t('rotate', { degrees: rotation })}
>
↻
</button>
)}
{live && (
<button
type='button'
className='button button-ghost'
onClick={toggleMirror}
aria-pressed={mirror}
aria-label={t('mirror')}
title={t('mirror')}
>
⇋
</button>
)}
{live && !isFullscreen && (
<button
type='button'
className='button button-ghost'
onClick={togglePinned}
aria-pressed={pinned}
aria-label={t(pinned ? 'unpin' : 'pin')}
title={t(pinned ? 'unpin' : 'pin')}
>
{pinned ? '▣' : '▢'}
</button>
)}
{live && (
<button
type='button'
className='button button-ghost'
onClick={toggleFullscreen}
aria-label={isFullscreen ? strings.exitFullscreen : strings.fullscreen}
title={isFullscreen ? strings.exitFullscreen : strings.fullscreen}
aria-label={isFullscreen ? t('exitFullscreen') : t('fullscreen')}
title={isFullscreen ? t('exitFullscreen') : t('fullscreen')}
>
{isFullscreen ? '⤡' : '⤢'}
</button>
@@ -126,13 +250,16 @@ export function App() {
<VideoStage
stream={stream}
live={live}
label={live ? strings.streaming : strings.negotiating}
label={live ? t('streaming') : t('negotiating')}
rotation={rotation}
mirror={mirror}
/>
{state.kind === 'failed' && <ErrorPanel state={state} onRetry={retry} />}
</main>
<footer className='footer'>
<footer className='footer' {...hold}>
<StatsBar stats={stats} />
<LanguagePicker />
</footer>
</div>
);
+10 -9
View File
@@ -1,5 +1,5 @@
import { strings } from '../strings';
import type { ViewerState } from '../lib/session';
import { useI18n } from '../i18n';
import { isRetryable, messageFor, type ViewerState } from '../lib/session';
type Props = {
state: Extract<ViewerState, { kind: 'failed' }>;
@@ -7,19 +7,20 @@ type Props = {
};
/**
* Panneau d'erreur. Il dit ce qui s'est passé, si réessayer peut aider, et ne
* propose le bouton que dans ce cas: un bouton qui échoue toujours est pire
* qu'une explication.
* Error panel. It says what happened, whether retrying can help, and offers
* the button only in that case: a button that always fails is worse than an
* explanation.
*/
export function ErrorPanel({ state, onRetry }: Props) {
const retryable = state.code === 'network' || state.code === 'internal';
const { t } = useI18n();
const retryable = isRetryable(state.code);
return (
<div className='panel' role='alert'>
<h2>{strings.failedTitle}</h2>
<p>{state.message}</p>
<h2>{t('failedTitle')}</h2>
<p>{messageFor(state.code, t)}</p>
{retryable && (
<button type='button' className='button' onClick={onRetry}>
{strings.retry}
{t('retry')}
</button>
)}
</div>
@@ -0,0 +1,27 @@
import { useId } from 'react';
import { useI18n } from '../i18n';
/**
* Language picker (#21), among those the host serves. Each one shows in its
* own language: whoever cannot read the current language finds their own.
*/
export function LanguagePicker() {
const { t, language, languages, setLanguage } = useI18n();
const id = useId();
if (languages.length < 2) return null;
return (
<span className='language'>
<label htmlFor={id} className='visually-hidden'>
{t('language')}
</label>
<select id={id} value={language} onChange={(e) => setLanguage(e.target.value)}>
{languages.map((l) => (
<option key={l.code} value={l.code} lang={l.code}>
{l.name}
</option>
))}
</select>
</span>
);
}
+165
View File
@@ -0,0 +1,165 @@
import { type FormEvent, useCallback, useEffect, useRef, useState } from 'react';
import { exchangeCode, qrDetector } from '../lib/pairing';
import { useI18n } from '../i18n';
import { isCompleteCode, normalizeCode, sessionFromScan } from '../lib/room';
import { LanguagePicker } from './LanguagePicker';
/** A sample code, in the format the host shows: not a sentence. */
const SAMPLE_CODE = 'K7M 4PQ';
type Props = {
/** Why we land here without a session, to say before the form. */
notice: string | null;
};
/**
* Home page without a session (#19): type the short code shown by the host,
* or scan its QR code when the browser can.
*/
export function Pairing({ notice }: Props) {
const { t } = useI18n();
const [code, setCode] = useState('');
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [scanning, setScanning] = useState(false);
const [canScan] = useState(() => qrDetector() !== null);
const submit = useCallback(
async (event: FormEvent) => {
event.preventDefault();
const normalized = normalizeCode(code);
if (!isCompleteCode(normalized)) {
setError(t('codeIncomplete'));
return;
}
setBusy(true);
setError(null);
const outcome = await exchangeCode(normalized);
setBusy(false);
switch (outcome.kind) {
case 'accepted':
window.location.assign(outcome.path);
return;
case 'unknown':
setError(t('codeUnknown'));
return;
case 'expired':
setError(t('codeExpired'));
return;
case 'too_many_attempts':
setError(t('codeTooMany', { seconds: outcome.retryAfterS }));
return;
case 'network':
setError(t('codeNetwork'));
}
},
[code, t],
);
return (
<div className='app app-centered'>
<div className='panel pairing'>
<h1>{t('appName')}</h1>
{notice && <p role='alert'>{notice}</p>}
<form onSubmit={submit} className='pairing-form'>
<label htmlFor='code'>{t('codeLabel')}</label>
<input
id='code'
className='pairing-code'
value={code}
onChange={(event) => setCode(event.target.value.toUpperCase())}
autoComplete='off'
autoCapitalize='characters'
spellCheck={false}
maxLength={8}
placeholder={SAMPLE_CODE}
aria-describedby={error ? 'code-error' : undefined}
aria-invalid={error !== null}
/>
<button type='submit' className='button' disabled={busy}>
{t('codeSubmit')}
</button>
</form>
{error && (
<p id='code-error' className='pairing-error' role='alert'>
{error}
</p>
)}
<p className='pairing-hint'>{t('codeHint')}</p>
{canScan && !scanning && (
<button type='button' className='button button-ghost' onClick={() => setScanning(true)}>
{t('scanButton')}
</button>
)}
{scanning && <Scanner onClose={() => setScanning(false)} onError={setError} />}
<LanguagePicker />
</div>
</div>
);
}
/** Rear camera, reading the QR code four times per second. */
function Scanner({ onClose, onError }: { onClose: () => void; onError: (m: string) => void }) {
const { t } = useI18n();
const videoRef = useRef<HTMLVideoElement | null>(null);
useEffect(() => {
const detector = qrDetector();
if (!detector) return;
let stream: MediaStream | null = null;
let timer: ReturnType<typeof setInterval> | undefined;
let stopped = false;
void navigator.mediaDevices
.getUserMedia({ video: { facingMode: 'environment' }, audio: false })
.then((media) => {
if (stopped) {
for (const track of media.getTracks()) track.stop();
return;
}
stream = media;
const video = videoRef.current;
if (!video) return;
video.srcObject = media;
void video.play().catch(() => undefined);
timer = setInterval(() => {
void detector
.detect(video)
.then((codes) => {
for (const found of codes) {
const target = sessionFromScan(found.rawValue);
if (target) {
window.location.assign(target);
return;
}
}
})
.catch(() => undefined);
}, 250);
})
.catch(() => {
onError(t('scanDenied'));
onClose();
});
return () => {
stopped = true;
clearInterval(timer);
for (const track of stream?.getTracks() ?? []) track.stop();
};
}, [onClose, onError, t]);
return (
<div className='scanner'>
<video
ref={videoRef}
className='scanner-video'
playsInline
muted
aria-label={t('scanButton')}
/>
<button type='button' className='button button-ghost' onClick={onClose}>
{t('scanClose')}
</button>
</div>
);
}
+16 -9
View File
@@ -1,18 +1,19 @@
import { useEffect, useRef, useState } from 'react';
import { useI18n } from '../i18n';
import type { VideoStats } from '../lib/session';
import { strings } from '../strings';
type Props = {
stats: VideoStats | null;
};
/**
* Bandeau de statistiques. Le débit n'est pas fourni par `getStats` en une
* valeur: on le calcule entre deux relevés, ce qui évite d'afficher un chiffre
* qui ne veut rien dire sur la première seconde.
* Statistics strip. `getStats` does not give the bitrate as a single value:
* it is computed between two samples, which avoids showing a meaningless
* figure during the first second.
*/
export function StatsBar({ stats }: Props) {
const { t, language } = useI18n();
const previous = useRef<{ bytes: number; at: number } | null>(null);
const [kbps, setKbps] = useState<number | null>(null);
@@ -37,23 +38,29 @@ export function StatsBar({ stats }: Props) {
return (
<dl className='stats'>
<div>
<dt>{strings.statsResolution}</dt>
<dt>{t('statsResolution')}</dt>
<dd>
{stats.width}×{stats.height}
</dd>
</div>
<div>
<dt>{strings.statsRate}</dt>
<dt>{t('statsRate')}</dt>
<dd>{stats.fps}</dd>
</div>
<div>
<dt>{strings.statsFrames}</dt>
<dt>{t('statsFrames')}</dt>
<dd>{formatCount(stats.frames)}</dd>
</div>
{kbps !== null && (
<div>
<dt>{strings.statsBitrate}</dt>
<dd>{kbps >= 1000 ? `${(kbps / 1000).toFixed(1)} Mbit/s` : `${kbps} kbit/s`}</dd>
<dt>{t('statsBitrate')}</dt>
<dd>
{kbps >= 1000
? t('mbps', {
value: (kbps / 1000).toLocaleString(language, { maximumFractionDigits: 1 }),
})
: t('kbps', { value: kbps })}
</dd>
</div>
)}
</dl>
+12 -10
View File
@@ -1,29 +1,31 @@
import { useI18n } from '../i18n';
import type { Translate } from '../lib/i18n';
import type { ViewerState } from '../lib/session';
import { strings } from '../strings';
/** Traduit l'état de session en un libellé court et une couleur. */
export function describe(state: ViewerState): { text: string; tone: string } {
/** Turns the session state into a short label and a colour. */
export function describe(state: ViewerState, t: Translate): { text: string; tone: string } {
switch (state.kind) {
case 'connecting':
return { text: strings.connecting, tone: 'pending' };
return { text: t('connecting'), tone: 'pending' };
case 'negotiating':
return { text: strings.negotiating, tone: 'pending' };
return { text: t('negotiating'), tone: 'pending' };
case 'streaming':
return { text: strings.streaming, tone: 'live' };
return { text: t('streaming'), tone: 'live' };
case 'reconnecting':
return {
text: strings.reconnecting(Math.ceil(state.delayMs / 1000)),
text: t('reconnecting', { seconds: Math.ceil(state.delayMs / 1000) }),
tone: 'pending',
};
case 'ended':
return { text: strings.ended, tone: 'neutral' };
return { text: t('ended'), tone: 'neutral' };
case 'failed':
return { text: strings.failedTitle, tone: 'error' };
return { text: t('failedTitle'), tone: 'error' };
}
}
export function StatusBadge({ state }: { state: ViewerState }) {
const { text, tone } = describe(state);
const { t } = useI18n();
const { text, tone } = describe(state, t);
return (
<span className={`badge badge-${tone}`} role='status' aria-live='polite'>
{tone === 'live' && <span className='badge-dot' aria-hidden='true' />}
+57 -8
View File
@@ -1,17 +1,24 @@
import { useEffect, useRef } from 'react';
import { useEffect, useRef, useState } from 'react';
import { type Rotation, rotatedBox } from '../lib/rotation';
type Props = {
stream: MediaStream | null;
live: boolean;
label: string;
rotation: Rotation;
mirror: boolean;
};
/**
* La scène vidéo. La balise reste montée même sans flux: la démonter pour la
* remonter à chaque négociation ferait sauter le plein écran sur iOS.
* The video stage. The element stays mounted even without a stream:
* unmounting and remounting it at every negotiation would drop full screen on
* iOS. A rotation changes its box and its transform, never the stream (#30).
*/
export function VideoStage({ stream, live, label }: Props) {
export function VideoStage({ stream, live, label, rotation, mirror }: Props) {
const videoRef = useRef<HTMLVideoElement | null>(null);
const stageRef = useRef<HTMLDivElement | null>(null);
const [size, setSize] = useState<{ width: number; height: number } | null>(null);
useEffect(() => {
const video = videoRef.current;
@@ -20,15 +27,57 @@ export function VideoStage({ stream, live, label }: Props) {
video.srcObject = stream;
}
if (stream) {
// `play()` peut être refusé si l'utilisateur n'a pas interagi; la
// vidéo est muette, donc en pratique il passe. On ignore l'échec.
// `play()` may be refused if the user has not interacted; the video
// is muted, so in practice it goes through. The failure is ignored.
void video.play().catch(() => undefined);
}
}, [stream]);
// The turned box depends on the stage size: full screen, switching to
// portrait, the virtual keyboard all change it.
useEffect(() => {
const stage = stageRef.current;
if (!stage || typeof ResizeObserver === 'undefined') return;
const observer = new ResizeObserver(([entry]) => {
if (!entry) return;
const { width, height } = entry.contentRect;
setSize({ width, height });
});
observer.observe(stage);
return () => observer.disconnect();
}, []);
// Without rotation, the element keeps its box: the mirror alone flips it.
const style =
rotation === 0
? mirror
? { transform: 'scaleX(-1)' }
: undefined
: size
? (() => {
const box = rotatedBox(size.width, size.height, rotation, mirror);
return {
inset: 'auto',
left: '50%',
top: '50%',
width: `${box.width}px`,
height: `${box.height}px`,
transform: box.transform,
};
})()
: undefined;
return (
<div className='stage'>
<video ref={videoRef} className='stage-video' playsInline muted autoPlay aria-label={label} />
<div className='stage' ref={stageRef}>
<video
ref={videoRef}
className='stage-video'
style={style}
playsInline
muted
autoPlay
aria-label={label}
/>
{!live && (
<div className='stage-veil' role='status' aria-live='polite'>
<span className='stage-dot' aria-hidden='true' />
+124
View File
@@ -0,0 +1,124 @@
import { createContext, type ReactNode, useCallback, useContext, useMemo, useState } from 'react';
import {
type AvailableLanguage,
type Catalog,
createTranslator,
FALLBACK_LANGUAGE,
pickLanguage,
type Translate,
} from './lib/i18n';
import { browserStorage, readMigrated } from './lib/storage';
/**
* Viewer texts (#21). The catalog comes from the host (`/locales/`): adding a
* language to the host makes it available here, without rebuilding the
* viewer. The choice is kept by the device alone, like the theme.
*/
const KEY = 'rustscreen.language';
/** Key before #83. */
const LEGACY_KEY = 'rustscreen.langue';
type Context = {
t: Translate;
language: string;
languages: AvailableLanguage[];
setLanguage: (code: string) => void;
};
const I18n = createContext<Context | null>(null);
export function useI18n(): Context {
const context = useContext(I18n);
if (!context) throw new Error('useI18n outside of I18nProvider');
return context;
}
type Loaded = { language: string; catalogs: Catalog[] };
export function I18nProvider({
initial,
languages,
children,
}: {
initial: Loaded;
languages: AvailableLanguage[];
children: ReactNode;
}) {
const [loaded, setLoaded] = useState(initial);
const setLanguage = useCallback((code: string) => {
saveLanguage(code);
// The change takes effect on the next render: no reload, the session
// and the stream go on.
void loadCatalogs(code).then((catalogs) => {
if (catalogs.length === 0) return;
document.documentElement.lang = code;
setLoaded({ language: code, catalogs });
});
}, []);
const value = useMemo(
() => ({
t: createTranslator(loaded.language, 'viewer', loaded.catalogs),
language: loaded.language,
languages,
setLanguage,
}),
[loaded, languages, setLanguage],
);
return <I18n.Provider value={value}>{children}</I18n.Provider>;
}
/** The languages the host serves, empty if it does not answer. */
export async function loadLanguages(): Promise<AvailableLanguage[]> {
try {
const response = await fetch('/locales/index.json');
if (!response.ok) return [];
return (await response.json()) as AvailableLanguage[];
} catch {
return [];
}
}
/** The wanted language then English, whichever of the two exist. */
export async function loadCatalogs(code: string): Promise<Catalog[]> {
const codes = code === FALLBACK_LANGUAGE ? [code] : [code, FALLBACK_LANGUAGE];
const catalogs = await Promise.all(
codes.map(async (c) => {
try {
const response = await fetch(`/locales/${encodeURIComponent(c)}.json`);
return response.ok ? ((await response.json()) as Catalog) : null;
} catch {
return null;
}
}),
);
return catalogs.filter((c): c is Catalog => c !== null);
}
/** The choice kept by the device, otherwise the browser language. */
export function initialLanguage(available: AvailableLanguage[]): string {
const codes = available.map((l) => l.code);
const saved = readLanguage();
if (saved && codes.includes(saved)) return saved;
return pickLanguage(navigator.languages ?? [navigator.language], codes);
}
function readLanguage(): string | null {
try {
const storage = browserStorage();
return storage ? readMigrated(storage, KEY, LEGACY_KEY) : null;
} catch {
return null;
}
}
function saveLanguage(code: string): void {
try {
window.localStorage.setItem(KEY, code);
} catch {
// Private browsing: the choice holds for the page only.
}
}
+52
View File
@@ -0,0 +1,52 @@
import { describe, expect, it } from 'vitest';
import { barsVisible, isCompact, readPinned, savePinned } from './controls';
describe('bars that fade out (#31, #81)', () => {
const base = { compact: true, live: true, active: false, held: false };
it('fade out when live, idle, in compact mode', () => {
expect(barsVisible(base)).toBe(false);
});
it('come back on activity, and stay under the pointer or the focus', () => {
expect(barsVisible({ ...base, active: true })).toBe(true);
expect(barsVisible({ ...base, held: true })).toBe(true);
});
it('stay visible when the session is not live', () => {
expect(barsVisible({ ...base, live: false })).toBe(true);
});
it('stay visible when pinned in a window, never in full screen', () => {
expect(isCompact(false, true)).toBe(false);
expect(isCompact(false, false)).toBe(true);
expect(isCompact(true, true)).toBe(true);
});
});
describe('pinned controls', () => {
function memory(initial: Record<string, string> = {}) {
const values = new Map(Object.entries(initial));
return {
values,
getItem: (k: string) => values.get(k) ?? null,
setItem: (k: string, v: string) => void values.set(k, v),
removeItem: (k: string) => void values.delete(k),
};
}
it('are kept by the device', () => {
const storage = memory();
expect(readPinned(storage)).toBe(false);
savePinned(true, storage);
expect(readPinned(storage)).toBe(true);
});
it('migrate the choice stored before #83', () => {
const storage = memory({ 'rustscreen.controles-epingles': '1' });
expect(readPinned(storage)).toBe(true);
expect(storage.values.get('rustscreen.pinned-controls')).toBe('1');
expect(storage.values.has('rustscreen.controles-epingles')).toBe(false);
});
});
+55
View File
@@ -0,0 +1,55 @@
/**
* Viewer bars that fade out (#31 in a window, #81 in full screen).
*
* After a few seconds without activity, the top bar and the footer disappear
* and the picture takes the whole space. A mouse move, a touch or a key brings
* them back. They stay visible as long as the session is not live: a dropout
* must show without touching the screen.
*/
import { browserStorage, type KeyValueStore, readMigrated } from './storage';
/** Delay without activity before hiding the bars. */
export const IDLE_DELAY_MS = 3000;
export type BarsState = {
/** Compact mode: full screen, or a window without pinned controls. */
compact: boolean;
/** The session is live. */
live: boolean;
/** Activity within the last `IDLE_DELAY_MS`. */
active: boolean;
/** The pointer is over a bar, or keyboard focus is in one. */
held: boolean;
};
export function barsVisible({ compact, live, active, held }: BarsState): boolean {
return !compact || !live || active || held;
}
/** Compact mode: always in full screen, by default in a window. */
export function isCompact(fullscreen: boolean, pinned: boolean): boolean {
return fullscreen || !pinned;
}
const KEY = 'rustscreen.pinned-controls';
/** Key before #83. */
const LEGACY_KEY = 'rustscreen.controles-epingles';
export function readPinned(storage: KeyValueStore | null = browserStorage()): boolean {
try {
return storage !== null && readMigrated(storage, KEY, LEGACY_KEY) === '1';
} catch {
return false;
}
}
export function savePinned(
pinned: boolean,
storage: KeyValueStore | null = browserStorage(),
): void {
try {
storage?.setItem(KEY, pinned ? '1' : '0');
} catch {
// Private browsing: the choice holds for the page only.
}
}
+78
View File
@@ -0,0 +1,78 @@
import { describe, expect, it, vi } from 'vitest';
import { deviceId } from './device';
import type { KeyValueStore } from './storage';
function memory(
initial: Record<string, string> = {},
): KeyValueStore & { values: Map<string, string> } {
const values = new Map(Object.entries(initial));
return {
values,
getItem: (k) => values.get(k) ?? null,
setItem: (k, v) => {
values.set(k, v);
},
removeItem: (k) => {
values.delete(k);
},
};
}
const denied: KeyValueStore = {
getItem: () => {
throw new Error('denied');
},
setItem: () => {
throw new Error('denied');
},
removeItem: () => {
throw new Error('denied');
},
};
describe('device id', () => {
it('does without randomUUID, missing outside a secure context (HTTP on the LAN)', () => {
vi.stubGlobal('crypto', { getRandomValues: globalThis.crypto.getRandomValues.bind(crypto) });
try {
expect(deviceId(memory())).toMatch(/^[0-9a-f]{32}$/);
} finally {
vi.unstubAllGlobals();
}
});
it('stays the same from one connection to the next', () => {
const storage = memory();
expect(deviceId(storage)).toBe(deviceId(storage));
});
it('survives a denied storage', () => {
expect(deviceId(denied)).toBe(deviceId(denied));
});
});
describe('device id migration (#83)', () => {
const legacy = '0123456789abcdef0123456789abcdef';
it('keeps the id stored under the old French key, moved to the new one', () => {
const storage = memory({ 'rustscreen.appareil': legacy });
expect(deviceId(storage)).toBe(legacy);
expect(storage.values.get('rustscreen.device')).toBe(legacy);
expect(storage.values.has('rustscreen.appareil')).toBe(false);
expect(deviceId(storage)).toBe(legacy);
});
it('prefers the new key when both exist', () => {
const current = 'fedcba9876543210fedcba9876543210';
const storage = memory({ 'rustscreen.device': current, 'rustscreen.appareil': legacy });
expect(deviceId(storage)).toBe(current);
});
it('keeps the old key when the new one cannot be written', () => {
const storage = memory({ 'rustscreen.appareil': legacy });
storage.setItem = () => {
throw new Error('quota');
};
expect(deviceId(storage)).toBe(legacy);
expect(storage.values.get('rustscreen.appareil')).toBe(legacy);
});
});
+48
View File
@@ -0,0 +1,48 @@
/**
* Id of this device, stable from one visit to the next.
*
* Two constraints:
*
* - the viewer is served over HTTP on the LAN address, which is not a secure
* context: `crypto.randomUUID()` does not exist there, while
* `crypto.getRandomValues()` does. A `randomUUID` made the `hello` fail on
* every device other than the host itself;
* - the host recognises a device it disconnected by this id: drawn at every
* connection, reloading the page would be enough to come back.
*
* Local storage may be denied (private browsing): the id then lasts for the
* page only.
*/
import { browserStorage, type KeyValueStore, readMigrated } from './storage';
const KEY = 'rustscreen.device';
/** Key before #83. Never regenerate an id because of the rename. */
const LEGACY_KEY = 'rustscreen.appareil';
const ID_PATTERN = /^[0-9a-f]{32}$/;
let pageId: string | null = null;
export function deviceId(storage: KeyValueStore | null = browserStorage()): string {
try {
const known = storage ? readMigrated(storage, KEY, LEGACY_KEY) : null;
if (known && ID_PATTERN.test(known)) {
return known;
}
} catch {
// Storage denied: page id below.
}
const fresh = pageId ?? randomId();
pageId = fresh;
try {
storage?.setItem(KEY, fresh);
} catch {
// Same.
}
return fresh;
}
function randomId(): string {
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
}
+55
View File
@@ -0,0 +1,55 @@
import { describe, expect, it } from 'vitest';
import { type Catalog, createTranslator, pickLanguage } from './i18n';
const fr: Catalog = {
viewer: {
greeting: 'Bonjour {name}',
viewers: { '0': 'personne', one: '{count} spectateur', other: '{count} spectateurs' },
},
};
const en: Catalog = {
viewer: {
greeting: 'Hello {name}',
onlyInEnglish: 'Only in English',
viewers: { '0': 'nobody', one: '{count} viewer', other: '{count} viewers' },
},
};
describe('createTranslator (#21)', () => {
it('interpolates the parameters', () => {
const t = createTranslator('fr', 'viewer', [fr, en]);
expect(t('greeting', { name: 'Ana' })).toBe('Bonjour Ana');
});
it('picks the plural form of the language', () => {
const t = createTranslator('fr', 'viewer', [fr, en]);
expect(t('viewers', { count: 0 })).toBe('personne');
expect(t('viewers', { count: 1 })).toBe('1 spectateur');
expect(t('viewers', { count: 3 })).toBe('3 spectateurs');
});
it('falls back to English for a missing key, never to the raw key', () => {
const t = createTranslator('fr', 'viewer', [fr, en]);
expect(t('onlyInEnglish')).toBe('Only in English');
expect(t('no.where')).toBe('');
});
it('a language unknown to Intl breaks nothing', () => {
const t = createTranslator('xx-invalid-%', 'viewer', [en]);
expect(t('viewers', { count: 2 })).toBe('2 viewers');
});
});
describe('pickLanguage', () => {
it('follows the device language, exactly or by its primary language', () => {
expect(pickLanguage(['fr-FR', 'en'], ['en', 'fr'])).toBe('fr');
expect(pickLanguage(['fr-CA'], ['en', 'fr'])).toBe('fr');
expect(pickLanguage(['pt-BR', 'pt'], ['en', 'pt-BR', 'pt'])).toBe('pt-BR');
});
it('falls back to English for a missing language', () => {
expect(pickLanguage(['de-DE', 'it'], ['en', 'fr'])).toBe('en');
expect(pickLanguage([], ['en', 'fr'])).toBe('en');
});
});
+112
View File
@@ -0,0 +1,112 @@
/**
* Translation (#21), without dependencies: key lookup, plurals,
* interpolation, English fallback, language choice.
*
* Texts live in `locales/<language>.json`, at the repository root, one file
* per language, one section per application (`viewer`, `desktop`). Adding a
* language means adding a file: no code changes. The host embeds them and
* serves them to the viewer (`/locales/`), the desktop shell embeds them at
* build time.
*
* This module is pure: the desktop shell imports it as is, without React.
*/
export type Catalog = { [key: string]: string | Catalog };
export type Params = Record<string, string | number>;
export type Translate = (key: string, params?: Params) => string;
/**
* A language on offer, by its code and its name in that language, as listed
* by the host's `/locales/index.json` and the `_language` header of each
* locale file.
*/
export type AvailableLanguage = { code: string; name: string };
/** The fallback language: complete by contract, checked by `check-i18n`. */
export const FALLBACK_LANGUAGE = 'en';
/**
* A translation function for `section` (`viewer`, `desktop`), which looks in
* `catalogs` in order: the chosen language, then English. A key found
* nowhere gives an empty string, never the raw key.
*/
export function createTranslator(
language: string,
section: string,
catalogs: Catalog[],
): Translate {
const rules = pluralRules(language);
return (key, params) => {
for (const catalog of catalogs) {
const value = lookup(catalog, `${section}.${key}`);
if (value === undefined) continue;
const text = typeof value === 'string' ? value : plural(value, rules, params);
if (text !== undefined) return interpolate(text, params);
}
return '';
};
}
function lookup(catalog: Catalog, path: string): string | Catalog | undefined {
let node: string | Catalog | undefined = catalog;
for (const part of path.split('.')) {
if (node === undefined || typeof node === 'string') return undefined;
node = node[part];
}
return node;
}
/**
* A plural is an object of forms: an exact value (`"0"`), then the
* `Intl.PluralRules` category (`one`, `few`, `other`...).
*/
function plural(
forms: Catalog,
rules: Intl.PluralRules,
params: Params | undefined,
): string | undefined {
const count = params?.count;
if (typeof count !== 'number') {
return typeof forms.other === 'string' ? forms.other : undefined;
}
const exact = forms[String(count)];
if (typeof exact === 'string') return exact;
const category = forms[rules.select(count)];
if (typeof category === 'string') return category;
return typeof forms.other === 'string' ? forms.other : undefined;
}
function pluralRules(language: string): Intl.PluralRules {
try {
return new Intl.PluralRules(language);
} catch {
return new Intl.PluralRules(FALLBACK_LANGUAGE);
}
}
function interpolate(text: string, params: Params | undefined): string {
if (!params) return text;
return text.replace(/\{(\w+)\}/g, (whole, name: string) =>
name in params ? String(params[name]) : whole,
);
}
/**
* The language to show: the first of the device preferences that exists,
* exactly (`pt-BR`) or by its primary language (`fr-CA` gives `fr`),
* otherwise English.
*/
export function pickLanguage(preferences: readonly string[], available: readonly string[]): string {
const codes = available.map((code) => code.toLowerCase());
for (const preference of preferences) {
const wanted = preference.toLowerCase();
const exact = codes.indexOf(wanted);
if (exact >= 0) return available[exact] ?? FALLBACK_LANGUAGE;
const primary = wanted.split('-')[0];
const close = codes.findIndex((code) => code.split('-')[0] === primary);
if (close >= 0) return available[close] ?? FALLBACK_LANGUAGE;
}
return codes.includes(FALLBACK_LANGUAGE)
? FALLBACK_LANGUAGE
: (available[0] ?? FALLBACK_LANGUAGE);
}
+50
View File
@@ -0,0 +1,50 @@
/**
* System events announcing that a reconnection is likely to succeed now:
* network back, interface change, device wake-up, page restored from the
* back/forward cache.
*
* This module decides nothing: it notifies the session, which alone knows
* whether it is waiting, has given up or is already connected (see
* `ViewerSession.wake`).
*/
export type WakeReason = 'online' | 'network_change' | 'visible' | 'pageshow';
type NavigatorWithConnection = Navigator & { connection?: EventTarget };
/**
* Attaches the listeners and returns the function that removes them. Each
* target is optional: `navigator.connection` exists neither in Safari nor in
* Firefox, and none of this exists in a test without a DOM.
*/
export function watchLifecycle(onWake: (reason: WakeReason) => void): () => void {
const cleanups: Array<() => void> = [];
const on = (
target: EventTarget | null | undefined,
type: string,
handler: (event: Event) => void,
) => {
if (!target || typeof target.addEventListener !== 'function') return;
target.addEventListener(type, handler);
cleanups.push(() => target.removeEventListener(type, handler));
};
if (typeof window !== 'undefined') {
on(window, 'online', () => onWake('online'));
on(window, 'pageshow', (event) => {
if ((event as PageTransitionEvent).persisted) onWake('pageshow');
});
}
if (typeof document !== 'undefined') {
on(document, 'visibilitychange', () => {
if (document.visibilityState === 'visible') onWake('visible');
});
}
if (typeof navigator !== 'undefined') {
on((navigator as NavigatorWithConnection).connection, 'change', () => onWake('network_change'));
}
return () => {
for (const cleanup of cleanups.splice(0)) cleanup();
};
}
+49
View File
@@ -0,0 +1,49 @@
import { describe, expect, it } from 'vitest';
import { exchangeCode, qrDetector } from './pairing';
function respond(status: number, body: unknown): typeof fetch {
return async () => new Response(JSON.stringify(body), { status });
}
describe('exchangeCode', () => {
it('returns the session path, versioned', async () => {
const outcome = await exchangeCode(
'k7m4pq',
respond(200, {
status: 'accepted',
room: 'abc234',
token: '0123456789abcdef0123456789abcdef',
}),
);
expect(outcome).toEqual({
kind: 'accepted',
path: '/r/abc234?t=0123456789abcdef0123456789abcdef&v=1',
});
});
it('tells an unknown code, an expired one, and too many attempts apart', async () => {
expect(await exchangeCode('x', respond(404, { status: 'unknown' }))).toEqual({
kind: 'unknown',
});
expect(await exchangeCode('x', respond(410, { status: 'expired' }))).toEqual({
kind: 'expired',
});
expect(
await exchangeCode('x', respond(429, { status: 'too_many_attempts', retry_after_s: 42 })),
).toEqual({ kind: 'too_many_attempts', retryAfterS: 42 });
});
it('does not throw when the network fails', async () => {
const broken: typeof fetch = async () => {
throw new TypeError('network');
};
expect(await exchangeCode('x', broken)).toEqual({ kind: 'network' });
});
});
describe('qrDetector', () => {
it('steps aside when the browser has no BarcodeDetector', () => {
expect(qrDetector()).toBeNull();
});
});
+73
View File
@@ -0,0 +1,73 @@
/**
* Pairing without a camera (#19): the short code shown by the host, exchanged
* for the room and the token. And, when the browser allows it, reading the QR
* code from the page itself.
*/
import { LINK_VERSION, type PairingResponse } from '../proto';
export type CodeOutcome =
| { kind: 'accepted'; path: string }
| { kind: 'unknown' }
| { kind: 'expired' }
| { kind: 'too_many_attempts'; retryAfterS: number }
| { kind: 'network' };
/** Exchanges a code for the session path. Never throws. */
export async function exchangeCode(
code: string,
fetchImpl: typeof fetch = fetch,
): Promise<CodeOutcome> {
let body: PairingResponse;
try {
const response = await fetchImpl('/api/code', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code }),
});
body = (await response.json()) as PairingResponse;
} catch {
return { kind: 'network' };
}
switch (body.status) {
case 'accepted':
return {
kind: 'accepted',
path: `/r/${encodeURIComponent(body.room)}?t=${encodeURIComponent(body.token)}&v=${LINK_VERSION}`,
};
case 'unknown':
return { kind: 'unknown' };
case 'expired':
return { kind: 'expired' };
case 'too_many_attempts':
return { kind: 'too_many_attempts', retryAfterS: body.retry_after_s };
default:
return { kind: 'network' };
}
}
/** The subset of the BarcodeDetector API in use. */
type Detector = {
detect(source: CanvasImageSource): Promise<Array<{ rawValue: string }>>;
};
type DetectorConstructor = new (options: { formats: string[] }) => Detector;
/**
* A QR code reader, if this browser exposes one. It also needs a camera, hence
* a secure context: a page served over HTTP on the LAN does not get one, and
* the short code takes over.
*/
export function qrDetector(): Detector | null {
const scope = globalThis as unknown as {
BarcodeDetector?: DetectorConstructor;
isSecureContext?: boolean;
navigator?: Navigator;
};
if (!scope.BarcodeDetector || !scope.isSecureContext) return null;
if (!scope.navigator?.mediaDevices?.getUserMedia) return null;
try {
return new scope.BarcodeDetector({ formats: ['qr_code'] });
} catch {
return null;
}
}
+8 -8
View File
@@ -3,9 +3,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { ViewerSession, type ViewerState } from './session';
/**
* WebSocket qui échoue immédiatement, pour éprouver la reconnexion sans réseau
* ni navigateur. Il n'ouvre jamais: `close` arrive tout de suite, exactement
* comme un hôte éteint.
* WebSocket that fails at once, to exercise reconnection without network or
* browser. It never opens: `close` arrives straight away, exactly like a host
* that is off.
*/
class FailingWebSocket {
static readonly OPEN = 1;
@@ -45,7 +45,7 @@ class StubPeerConnection {
close(): void {}
}
describe('reconnexion', () => {
describe('reconnection', () => {
beforeEach(() => {
vi.useFakeTimers();
FailingWebSocket.instances = [];
@@ -58,7 +58,7 @@ describe('reconnexion', () => {
vi.useRealTimers();
});
it('réessaie, puis abandonne avec un message réseau', async () => {
it('retries, then gives up with a network message', async () => {
const states: ViewerState[] = [];
const session = new ViewerSession({
room: 'abc234',
@@ -70,7 +70,7 @@ describe('reconnexion', () => {
});
session.start();
// Laisse passer les microtâches qui déclenchent la fermeture.
// Lets the microtasks that trigger the close run.
await vi.advanceTimersByTimeAsync(0);
await vi.advanceTimersByTimeAsync(1000);
await vi.advanceTimersByTimeAsync(2000);
@@ -87,7 +87,7 @@ describe('reconnexion', () => {
expect(FailingWebSocket.instances.length).toBeLessThanOrEqual(3);
});
it('stop() coupe la reconnexion et ne rappelle plus l’état', async () => {
it('stop() cuts reconnection and no longer reports the state', async () => {
const states: ViewerState[] = [];
const session = new ViewerSession({
room: 'abc234',
@@ -106,7 +106,7 @@ describe('reconnexion', () => {
expect(states.length).toBe(before);
});
it('refuse de démarrer deux fois après stop()', async () => {
it('refuses to start again after stop()', async () => {
const session = new ViewerSession({
room: 'abc234',
token: '0123456789abcdef0123456789abcdef',
+501
View File
@@ -0,0 +1,501 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { ClientMessage, StreamSettings } from '../proto';
import { ViewerSession, type ViewerState, WAKE_MIN_INTERVAL_MS } from './session';
/**
* Resume after a network change (#39) and after sleep (#42).
*
* A fake host answers like the real one: `welcome` to `hello`, `answer` to the
* offer, `settings_applied` with ITS default setting to a quality request.
* When it is "off" (or the network is cut), the socket closes at once.
*/
const BALANCED: StreamSettings = { quality: 'balanced', max_bitrate_kbps: 3000, max_fps: 30 };
const SHARP: StreamSettings = { quality: 'sharp', max_bitrate_kbps: 8000, max_fps: 60 };
const SAVER: StreamSettings = { quality: 'saver', max_bitrate_kbps: 1200, max_fps: 20 };
const host = { up: false };
type Listener = (event: unknown) => void;
class FakeWebSocket {
static readonly CONNECTING = 0;
static readonly OPEN = 1;
static readonly CLOSING = 2;
static readonly CLOSED = 3;
static instances: FakeWebSocket[] = [];
readyState = FakeWebSocket.CONNECTING;
sent: ClientMessage[] = [];
private listeners = new Map<string, Listener[]>();
constructor(public readonly url: string) {
FakeWebSocket.instances.push(this);
const reachable = host.up;
queueMicrotask(() => {
if (this.readyState !== FakeWebSocket.CONNECTING) return;
if (reachable) {
this.readyState = FakeWebSocket.OPEN;
this.emit('open', {});
} else {
this.drop();
}
});
}
addEventListener(type: string, listener: Listener): void {
const list = this.listeners.get(type) ?? [];
list.push(listener);
this.listeners.set(type, list);
}
send(raw: string): void {
const message = JSON.parse(raw) as ClientMessage;
this.sent.push(message);
if (message.type === 'hello') {
this.reply({
type: 'welcome',
version: 1,
room: 'abc234',
source: null,
settings: BALANCED,
connected: 1,
limit: 4,
});
} else if (message.type === 'offer') {
this.reply({ type: 'answer', sdp: 'v=0' });
} else if (message.type === 'quality_request') {
// Like the current host: it sends back what it applies, not the request.
this.reply({ type: 'settings_applied', settings: BALANCED });
}
}
/** Like a browser: a requested close is notified later. */
close(): void {
if (this.readyState === FakeWebSocket.CLOSED) return;
this.readyState = FakeWebSocket.CLOSING;
queueMicrotask(() => this.drop());
}
/** Dropout as seen by the viewer: network lost or host stopped. */
drop(): void {
if (this.readyState === FakeWebSocket.CLOSED) return;
this.readyState = FakeWebSocket.CLOSED;
this.emit('close', {});
}
private reply(message: unknown): void {
queueMicrotask(() => {
if (this.readyState !== FakeWebSocket.OPEN) return;
this.emit('message', { data: JSON.stringify(message) });
});
}
private emit(type: string, event: unknown): void {
for (const listener of this.listeners.get(type) ?? []) listener(event);
}
}
class FakePeerConnection extends EventTarget {
static instances: FakePeerConnection[] = [];
connectionState: RTCPeerConnectionState = 'new';
iceGatheringState: RTCIceGatheringState = 'complete';
localDescription: { type: string; sdp: string } | null = null;
constructor() {
super();
FakePeerConnection.instances.push(this);
}
addTransceiver(): void {}
async createOffer() {
return { type: 'offer', sdp: 'v=0' };
}
async setLocalDescription(description: { type: string; sdp: string }) {
this.localDescription = description;
}
async setRemoteDescription() {
queueMicrotask(() => {
if (host.up && this.connectionState === 'new') this.setConnectionState('connected');
});
}
/** Like the browser: `close()` fires no event. */
close(): void {
this.connectionState = 'closed';
}
setConnectionState(state: RTCPeerConnectionState): void {
this.connectionState = state;
this.dispatchEvent(new Event('connectionstatechange'));
}
}
class FakeDocument extends EventTarget {
visibilityState: DocumentVisibilityState = 'visible';
setVisibility(state: DocumentVisibilityState): void {
this.visibilityState = state;
this.dispatchEvent(new Event('visibilitychange'));
}
}
let fakeWindow: EventTarget;
let fakeDocument: FakeDocument;
let connection: EventTarget;
function newSession(
states: ViewerState[],
extra: { maxAttempts?: number; quality?: StreamSettings } = {},
) {
return new ViewerSession({
room: 'abc234',
token: '0123456789abcdef0123456789abcdef',
wsUrl: 'ws://192.168.1.20:8099/ws',
onState: (state) => states.push(state),
onStream: () => undefined,
...extra,
});
}
/** Lets the microtasks run (open, host replies). */
async function settle(ms = 0): Promise<void> {
await vi.advanceTimersByTimeAsync(ms);
}
function lastSocket(): FakeWebSocket {
const ws = FakeWebSocket.instances.at(-1);
if (!ws) throw new Error('no socket');
return ws;
}
function lastPeer(): FakePeerConnection {
const pc = FakePeerConnection.instances.at(-1);
if (!pc) throw new Error('no WebRTC connection');
return pc;
}
/** Clean cut: the socket drops, then the WebRTC connection fails. */
function cut(): void {
host.up = false;
const pc = lastPeer();
lastSocket().drop();
pc.setConnectionState('failed');
}
function goOnline(): void {
fakeWindow.dispatchEvent(new Event('online'));
}
/** Runs until giving up, host unreachable. */
async function exhaust(): Promise<void> {
for (let i = 0; i < 10; i += 1) await settle(15_000);
}
describe('resume after a network change or sleep', () => {
beforeEach(() => {
vi.useFakeTimers();
host.up = false;
FakeWebSocket.instances = [];
FakePeerConnection.instances = [];
fakeWindow = new EventTarget();
fakeDocument = new FakeDocument();
connection = new EventTarget();
vi.stubGlobal('WebSocket', FakeWebSocket);
vi.stubGlobal('RTCPeerConnection', FakePeerConnection);
vi.stubGlobal('window', fakeWindow);
vi.stubGlobal('document', fakeDocument);
vi.stubGlobal('navigator', { userAgent: 'test', platform: 'test', connection });
});
afterEach(() => {
vi.unstubAllGlobals();
vi.useRealTimers();
});
it('Wi-Fi to Ethernet: `online` restarts at once, the stream is back within 5 s', async () => {
const states: ViewerState[] = [];
host.up = true;
const session = newSession(states);
session.start();
await settle();
expect(states.at(-1)?.kind).toBe('streaming');
const cutAt = Date.now();
cut();
await settle();
expect(states.at(-1)?.kind).toBe('reconnecting');
// Wi-Fi is gone, the first attempts fail.
await settle(3000);
expect(states.at(-1)?.kind).toBe('reconnecting');
const sockets = FakeWebSocket.instances.length;
// Ethernet arrives: no waiting for the timer (4 s at this point).
host.up = true;
goOnline();
await settle();
expect(FakeWebSocket.instances.length).toBe(sockets + 1);
expect(states.at(-1)?.kind).toBe('streaming');
expect(Date.now() - cutAt).toBeLessThan(5000);
session.stop();
});
it('`change` on navigator.connection restarts while waiting, and counts as an attempt', async () => {
const states: ViewerState[] = [];
const session = newSession(states, { maxAttempts: 6 });
session.start();
await settle();
await settle(1000);
await settle(2000);
// Three attempts made, the fourth waits 4 s.
expect(FakeWebSocket.instances).toHaveLength(3);
expect(states.at(-1)).toMatchObject({ kind: 'reconnecting', attempt: 3, delayMs: 4000 });
connection.dispatchEvent(new Event('change'));
await settle();
expect(FakeWebSocket.instances).toHaveLength(4);
expect(states).toContainEqual({ kind: 'connecting', attempt: 4 });
// The failure of this attempt resumes with the next delay, not the first.
expect(states.at(-1)).toMatchObject({ kind: 'reconnecting', attempt: 4, delayMs: 8000 });
session.stop();
});
it('limits restarts to one every 2 s, even when events pour in', async () => {
const states: ViewerState[] = [];
const session = newSession(states);
session.start();
await settle();
expect(FakeWebSocket.instances).toHaveLength(1);
// Interface change: `online` and `change` arrive together.
goOnline();
connection.dispatchEvent(new Event('change'));
fakeDocument.setVisibility('visible');
await settle();
expect(FakeWebSocket.instances).toHaveLength(2);
await settle(WAKE_MIN_INTERVAL_MS - 500);
const before = FakeWebSocket.instances.length;
goOnline();
await settle();
expect(FakeWebSocket.instances).toHaveLength(before);
await settle(500);
const afterInterval = FakeWebSocket.instances.length;
goOnline();
await settle();
expect(FakeWebSocket.instances).toHaveLength(afterInterval + 1);
session.stop();
});
it('leaves a streaming session alone', async () => {
const states: ViewerState[] = [];
host.up = true;
const session = newSession(states);
session.start();
await settle();
expect(states.at(-1)?.kind).toBe('streaming');
goOnline();
connection.dispatchEvent(new Event('change'));
fakeDocument.setVisibility('visible');
await settle();
expect(FakeWebSocket.instances).toHaveLength(1);
expect(states.at(-1)?.kind).toBe('streaming');
session.stop();
});
it('after giving up, returning to the foreground opens ONE new series that ends', async () => {
const states: ViewerState[] = [];
const session = newSession(states, { maxAttempts: 3 });
session.start();
await exhaust();
expect(states.at(-1)).toMatchObject({ kind: 'failed', code: 'network' });
expect(FakeWebSocket.instances).toHaveLength(3);
// Going to sleep: nothing happens.
fakeDocument.setVisibility('hidden');
await exhaust();
expect(FakeWebSocket.instances).toHaveLength(3);
// Wake-up, host still off: a series of three, then failure, no loop.
fakeDocument.setVisibility('visible');
await exhaust();
expect(FakeWebSocket.instances).toHaveLength(6);
expect(states.at(-1)).toMatchObject({ kind: 'failed', code: 'network' });
await exhaust();
expect(FakeWebSocket.instances).toHaveLength(6);
session.stop();
});
it('after giving up, `online` restarts and gets the stream back if the host returned', async () => {
const states: ViewerState[] = [];
const session = newSession(states, { maxAttempts: 2 });
session.start();
await exhaust();
expect(states.at(-1)?.kind).toBe('failed');
host.up = true;
goOnline();
await settle();
expect(states.at(-1)?.kind).toBe('streaming');
session.stop();
});
it('`pageshow` restarts only for a page restored from the cache', async () => {
const states: ViewerState[] = [];
const session = newSession(states, { maxAttempts: 2 });
session.start();
await exhaust();
expect(FakeWebSocket.instances).toHaveLength(2);
fakeWindow.dispatchEvent(Object.assign(new Event('pageshow'), { persisted: false }));
await settle();
expect(FakeWebSocket.instances).toHaveLength(2);
fakeWindow.dispatchEvent(Object.assign(new Event('pageshow'), { persisted: true }));
await settle();
expect(FakeWebSocket.instances).toHaveLength(3);
session.stop();
});
it('wake-up on a silently dead transport: reconnection, and the close of the old socket does not break the new one', async () => {
const states: ViewerState[] = [];
host.up = true;
const session = newSession(states);
session.start();
await settle();
expect(states.at(-1)?.kind).toBe('streaming');
// The device slept: the connection died without any event being
// handled, the socket still believes it is open.
lastPeer().connectionState = 'disconnected';
fakeDocument.setVisibility('visible');
await settle();
expect(FakeWebSocket.instances).toHaveLength(2);
expect(FakeWebSocket.instances[0]?.readyState).toBe(FakeWebSocket.CLOSED);
expect(states.at(-1)?.kind).toBe('streaming');
await settle(30_000);
expect(FakeWebSocket.instances).toHaveLength(2);
expect(states.at(-1)?.kind).toBe('streaming');
session.stop();
});
it('"Retry" starts a series without waiting for the interval, and nothing after stop()', async () => {
const states: ViewerState[] = [];
const session = newSession(states, { maxAttempts: 2 });
session.start();
await exhaust();
goOnline();
await exhaust();
expect(FakeWebSocket.instances).toHaveLength(4);
expect(states.at(-1)?.kind).toBe('failed');
host.up = true;
expect(session.retry()).toBe(true);
await settle();
expect(states.at(-1)?.kind).toBe('streaming');
session.stop();
expect(session.retry()).toBe(false);
goOnline();
await settle(WAKE_MIN_INTERVAL_MS);
expect(FakeWebSocket.instances).toHaveLength(5);
});
it('stop() removes the system listeners', async () => {
const session = newSession([], { maxAttempts: 1 });
session.start();
await exhaust();
session.stop();
goOnline();
fakeDocument.setVisibility('visible');
connection.dispatchEvent(new Event('change'));
await settle();
expect(FakeWebSocket.instances).toHaveLength(1);
});
});
describe('stable quality across reconnections', () => {
beforeEach(() => {
vi.useFakeTimers();
host.up = true;
FakeWebSocket.instances = [];
FakePeerConnection.instances = [];
vi.stubGlobal('WebSocket', FakeWebSocket);
vi.stubGlobal('RTCPeerConnection', FakePeerConnection);
vi.stubGlobal('navigator', { userAgent: 'test', platform: 'test' });
});
afterEach(() => {
vi.unstubAllGlobals();
vi.useRealTimers();
});
function qualityRequests(ws: FakeWebSocket): StreamSettings[] {
return ws.sent.flatMap((message) =>
message.type === 'quality_request' ? [message.settings] : [],
);
}
async function cutAndResume(states: ViewerState[]): Promise<void> {
cut();
await settle();
host.up = true;
await settle(1000);
expect(states.at(-1)?.kind).toBe('streaming');
}
it('three dropouts in a row keep the initial quality, never the minimum', async () => {
const states: ViewerState[] = [];
const session = newSession(states, { quality: SHARP });
session.start();
await settle();
expect(states.at(-1)?.kind).toBe('streaming');
for (let i = 0; i < 3; i += 1) await cutAndResume(states);
expect(FakeWebSocket.instances).toHaveLength(4);
for (const ws of FakeWebSocket.instances) {
expect(qualityRequests(ws)).toEqual([SHARP]);
// Requested after `welcome`, before the offer.
const kinds = ws.sent.map((message) => message.type);
expect(kinds).toEqual(['hello', 'quality_request', 'offer']);
}
// The host reply (its default setting) does not overwrite the choice.
expect(session.requestedQuality).toEqual(SHARP);
expect(session.requestedQuality).not.toEqual(SAVER);
session.stop();
});
it('the user last choice survives dropouts', async () => {
const states: ViewerState[] = [];
const session = newSession(states);
session.start();
await settle();
expect(qualityRequests(lastSocket())).toEqual([]);
session.setQuality(SAVER);
session.setQuality(SHARP);
await settle();
expect(qualityRequests(lastSocket())).toEqual([SAVER, SHARP]);
for (let i = 0; i < 3; i += 1) await cutAndResume(states);
for (const ws of FakeWebSocket.instances.slice(1)) {
expect(qualityRequests(ws)).toEqual([SHARP]);
}
expect(session.requestedQuality).toEqual(SHARP);
session.stop();
});
it('without a choice, no quality request: the host keeps its setting', async () => {
const states: ViewerState[] = [];
const session = newSession(states);
session.start();
await settle();
for (let i = 0; i < 3; i += 1) await cutAndResume(states);
for (const ws of FakeWebSocket.instances) {
expect(qualityRequests(ws)).toEqual([]);
}
session.stop();
});
});
+67 -9
View File
@@ -1,9 +1,15 @@
import { describe, expect, it } from 'vitest';
import { parseRoomLocation, signalingUrl } from './room';
import {
isCompleteCode,
normalizeCode,
parseRoomLocation,
sessionFromScan,
signalingUrl,
} from './room';
describe('parseRoomLocation', () => {
it('extrait la room et le jeton', () => {
it('extracts the room and the token', () => {
const result = parseRoomLocation('/r/abc234', '?t=0123456789abcdef0123456789abcdef');
expect(result).toEqual({
ok: true,
@@ -11,11 +17,11 @@ describe('parseRoomLocation', () => {
});
});
it('refuse une adresse sans room', () => {
it('rejects an address without a room', () => {
expect(parseRoomLocation('/', '')).toEqual({ ok: false, reason: 'missing_room' });
});
it('distingue un jeton absent d’un jeton mal formé', () => {
it('tells a missing token from a malformed one', () => {
expect(parseRoomLocation('/r/abc234', '')).toEqual({
ok: false,
reason: 'missing_token',
@@ -26,14 +32,14 @@ describe('parseRoomLocation', () => {
});
});
it('refuse une room avec un caractère ambigu', () => {
it('rejects a room with an ambiguous character', () => {
expect(parseRoomLocation('/r/abc0o1', '?t=0123456789abcdef0123456789abcdef')).toEqual({
ok: false,
reason: 'malformed',
});
});
it('normalise une room en majuscules', () => {
it('normalises an upper case room', () => {
const result = parseRoomLocation('/r/ABC234', '?t=0123456789ABCDEF0123456789ABCDEF');
expect(result).toEqual({
ok: true,
@@ -41,17 +47,69 @@ describe('parseRoomLocation', () => {
});
});
it('ignore les segments supplémentaires', () => {
it('ignores extra segments', () => {
const result = parseRoomLocation('/r/abc234/extra', '?t=0123456789abcdef0123456789abcdef');
expect(result.ok).toBe(true);
});
});
describe('versioned link (#19)', () => {
const token = '0123456789abcdef0123456789abcdef';
it('reads a version 1 link and its fingerprint', () => {
const fp = 'ab'.repeat(32);
const result = parseRoomLocation('/r/abc234', `?t=${token}&v=1`, `#fp=${fp}`);
expect(result).toEqual({
ok: true,
value: { room: 'abc234', token, fingerprint: Array(32).fill('AB').join(':') },
});
});
it('accepts a link without version, the one of earlier releases', () => {
expect(parseRoomLocation('/r/abc234', `?t=${token}`).ok).toBe(true);
});
it('says a link comes from a newer version', () => {
expect(parseRoomLocation('/r/abc234', `?t=${token}&v=2`)).toEqual({
ok: false,
reason: 'newer_link',
});
});
it('ignores a malformed fingerprint', () => {
const result = parseRoomLocation('/r/abc234', `?t=${token}&v=1`, '#fp=zz');
expect(result).toEqual({ ok: true, value: { room: 'abc234', token } });
});
});
describe('scanned QR code', () => {
it('follows a session URL', () => {
const url = 'http://192.168.1.20:8099/r/abc234?t=0123456789abcdef0123456789abcdef&v=1';
expect(sessionFromScan(url)).toBe(url);
});
it('rejects what is not a session', () => {
expect(sessionFromScan('hello')).toBeNull();
expect(sessionFromScan('javascript:alert(1)')).toBeNull();
expect(sessionFromScan('https://example.com/')).toBeNull();
});
});
describe('short code', () => {
it('is typed as it is shown', () => {
expect(normalizeCode(' K7M 4PQ ')).toBe('k7m4pq');
expect(normalizeCode('k7m-4pq')).toBe('k7m4pq');
expect(isCompleteCode('k7m4pq')).toBe(true);
expect(isCompleteCode('k7m4p')).toBe(false);
expect(isCompleteCode('k7m4p0')).toBe(false);
});
});
describe('signalingUrl', () => {
it('suit le schéma de la page', () => {
it('follows the page scheme', () => {
expect(signalingUrl({ protocol: 'http:', host: '127.0.0.1:8099' })).toBe(
'ws://127.0.0.1:8099/ws',
);
expect(signalingUrl({ protocol: 'https:', host: 'hote.local' })).toBe('wss://hote.local/ws');
expect(signalingUrl({ protocol: 'https:', host: 'host.local' })).toBe('wss://host.local/ws');
});
});
+64 -15
View File
@@ -1,47 +1,96 @@
/**
* Lecture de la session dans l'URL.
* Reading the session from the URL.
*
* Forme attendue: `/r/<room>?t=<jeton>`. Les deux valeurs sont validées ici
* plutôt que dans les composants, pour qu'un test puisse les couvrir et qu'une
* URL mal formée produise un message clair au lieu d'une session vide.
* Expected form: `/r/<room>?t=<token>&v=<version>`, followed over HTTPS by
* `#fp=<fingerprint>` (#19). Values are validated here rather than in the
* components, so that a test can cover them and a malformed URL gives a clear
* message instead of an empty session.
*/
import { LINK_VERSION } from '../proto';
export type RoomLocation = {
room: string;
token: string;
/** SHA-256 fingerprint of the certificate, as hex pairs, over HTTPS. */
fingerprint?: string;
};
export type RoomLocationResult =
| { ok: true; value: RoomLocation }
| { ok: false; reason: 'missing_room' | 'missing_token' | 'malformed' };
| { ok: false; reason: 'missing_room' | 'missing_token' | 'malformed' | 'newer_link' };
/** Six caractères, alphabet sans ambiguïté, aligné sur `RoomId` côté Rust. */
/** Six characters, unambiguous alphabet, aligned with `RoomId` on the Rust side. */
const ROOM_PATTERN = /^[2-9a-hjkmnp-z]{6}$/;
/** Jeton hexadécimal de 128 bits. */
/** 128-bit hex token. */
const TOKEN_PATTERN = /^[0-9a-f]{32}$/;
export function parseRoomLocation(pathname: string, search: string): RoomLocationResult {
/** SHA-256 fingerprint: 64 hex digits. */
const FINGERPRINT_PATTERN = /^[0-9a-f]{64}$/;
export function parseRoomLocation(pathname: string, search: string, hash = ''): RoomLocationResult {
const segments = pathname.split('/').filter(Boolean);
// Deux formes acceptées: `/r/<room>` et `/<room>`. Le préfixe `r` évite de
// confondre une room avec un chemin d'asset servi par le même serveur.
// Two accepted forms: `/r/<room>` and `/<room>`. The `r` prefix avoids
// mistaking a room for an asset path served by the same server.
const raw = segments[0] === 'r' ? segments[1] : segments[0];
if (!raw) {
return { ok: false, reason: 'missing_room' };
}
// L'hôte normalise en minuscules; on fait pareil pour qu'une URL recopiée à
// la main fonctionne malgré une majuscule.
// The host normalises to lower case; so does this, so that a URL copied by
// hand works despite a capital letter.
const room = raw.toLowerCase();
const token = (new URLSearchParams(search).get('t') ?? '').toLowerCase();
const params = new URLSearchParams(search);
// Without `v`, it is a link from 0.4 or earlier: same format as version
// 1. A newer version says so, instead of being misread.
const version = Number(params.get('v') ?? '1');
if (!Number.isInteger(version) || version < 1) {
return { ok: false, reason: 'malformed' };
}
if (version > LINK_VERSION) {
return { ok: false, reason: 'newer_link' };
}
const token = (params.get('t') ?? '').toLowerCase();
if (!token) {
return { ok: false, reason: 'missing_token' };
}
if (!ROOM_PATTERN.test(room) || !TOKEN_PATTERN.test(token)) {
return { ok: false, reason: 'malformed' };
}
return { ok: true, value: { room, token } };
const fp = new URLSearchParams(hash.replace(/^#/, '')).get('fp')?.toLowerCase();
const value: RoomLocation = { room, token };
if (fp && FINGERPRINT_PATTERN.test(fp)) {
value.fingerprint = fp.match(/../g)?.join(':').toUpperCase();
}
return { ok: true, value };
}
/** URL du canal de signalement, qui suit le schéma de la page. */
/**
* The path to open for a scanned QR code, or `null` if it does not carry a
* rustscreen session. Only `http` and `https` are followed: a QR code can
* contain anything.
*/
export function sessionFromScan(text: string): string | null {
let url: URL;
try {
url = new URL(text.trim());
} catch {
return null;
}
if (url.protocol !== 'http:' && url.protocol !== 'https:') return null;
const parsed = parseRoomLocation(url.pathname, url.search, url.hash);
return parsed.ok ? url.href : null;
}
/** Short code typed by hand: six characters of the room alphabet. */
export function normalizeCode(input: string): string {
return input.replace(/[\s-]/g, '').toLowerCase();
}
export function isCompleteCode(code: string): boolean {
return ROOM_PATTERN.test(code);
}
/** URL of the signalling channel, which follows the page scheme. */
export function signalingUrl(location: { protocol: string; host: string }): string {
const scheme = location.protocol === 'https:' ? 'wss' : 'ws';
return `${scheme}://${location.host}/ws`;
+77
View File
@@ -0,0 +1,77 @@
import { describe, expect, it } from 'vitest';
import {
displayedArea,
nextRotation,
readMirror,
readRotation,
rotatedBox,
saveMirror,
} from './rotation';
function memory(initial: Record<string, string> = {}) {
const values = new Map(Object.entries(initial));
return {
values,
getItem: (k: string) => values.get(k) ?? null,
setItem: (k: string, v: string) => void values.set(k, v),
removeItem: (k: string) => void values.delete(k),
};
}
describe('rotation (#30)', () => {
it('makes a full turn in steps of 90 degrees', () => {
expect(nextRotation(0)).toBe(90);
expect(nextRotation(270)).toBe(0);
});
it('swaps the box width and height on a quarter turn', () => {
expect(rotatedBox(1000, 600, 90)).toMatchObject({ width: 600, height: 1000 });
expect(rotatedBox(1000, 600, 180)).toMatchObject({ width: 1000, height: 600 });
expect(rotatedBox(1000, 600, 270).transform).toContain('rotate(270deg)');
});
it('keeps the whole picture and fills the stage in portrait', () => {
// Tablet in portrait (800×1280), shared screen at 1920×1080.
const stage = { width: 800, height: 1280 };
const video = { width: 1920, height: 1080 };
const upright = displayedArea(stage, video, 0);
const turned = displayedArea(stage, video, 90);
// Without rotation, the picture (800×450) fills barely more than a third of the stage.
expect((upright.width * upright.height) / (800 * 1280)).toBeLessThan(0.36);
// Turned, it fits whole and takes the full available height.
expect(turned.width).toBeLessThanOrEqual(800);
expect(turned.height).toBeLessThanOrEqual(1280);
expect(Math.max(turned.width / 800, turned.height / 1280)).toBeCloseTo(1);
// Turned (720×1280), it fills 90 % of it: the bars stay thin.
expect((turned.width * turned.height) / (800 * 1280)).toBeGreaterThan(0.89);
});
it('ignores an invalid stored value', () => {
expect(readRotation(memory({ 'rustscreen.rotation': '45' }))).toBe(0);
expect(readRotation(memory({ 'rustscreen.rotation': '270' }))).toBe(270);
});
});
describe('mirror (#29)', () => {
it('flips the picture in screen space, after the rotation', () => {
expect(rotatedBox(1000, 600, 90, true).transform).toBe(
'translate(-50%, -50%) scaleX(-1) rotate(90deg)',
);
expect(rotatedBox(1000, 600, 0, false).transform).not.toContain('scaleX');
});
it('is kept by the device', () => {
const storage = memory();
expect(readMirror(storage)).toBe(false);
saveMirror(true, storage);
expect(readMirror(storage)).toBe(true);
});
it('migrates the choice stored before #83', () => {
const storage = memory({ 'rustscreen.miroir': '1' });
expect(readMirror(storage)).toBe(true);
expect(storage.values.get('rustscreen.mirror')).toBe('1');
expect(storage.values.has('rustscreen.miroir')).toBe(false);
});
});
+96
View File
@@ -0,0 +1,96 @@
/**
* Rotation of the stream in the viewer (#30), in steps of 90 degrees.
*
* A video turned a quarter turn swaps its width and height: the element is
* therefore given the box of the turned stage, then rotated.
* `object-fit: contain` keeps the whole picture in that box, cropping nothing
* and with no bars wider than needed. Everything happens in the page: no
* message to the host, no reconnection.
*/
import { browserStorage, type KeyValueStore, readMigrated } from './storage';
export type Rotation = 0 | 90 | 180 | 270;
const KEY = 'rustscreen.rotation';
export function nextRotation(rotation: Rotation): Rotation {
return ((rotation + 90) % 360) as Rotation;
}
/**
* Size and transform of the video element in a `width`×`height` stage.
*
* The mirror (#29) applies in screen space, after the rotation: text reads
* backwards for whoever looks at the screen, and the right way round in a
* teleprompter's reflection, whatever the tablet's orientation.
*/
export function rotatedBox(
width: number,
height: number,
rotation: Rotation,
mirror = false,
): { width: number; height: number; transform: string } {
const quarter = rotation === 90 || rotation === 270;
return {
width: quarter ? height : width,
height: quarter ? width : height,
transform: `translate(-50%, -50%)${mirror ? ' scaleX(-1)' : ''} rotate(${rotation}deg)`,
};
}
const MIRROR_KEY = 'rustscreen.mirror';
/** Key before #83. */
const LEGACY_MIRROR_KEY = 'rustscreen.miroir';
export function readMirror(storage: KeyValueStore | null = browserStorage()): boolean {
try {
return storage !== null && readMigrated(storage, MIRROR_KEY, LEGACY_MIRROR_KEY) === '1';
} catch {
return false;
}
}
export function saveMirror(
mirror: boolean,
storage: KeyValueStore | null = browserStorage(),
): void {
try {
storage?.setItem(MIRROR_KEY, mirror ? '1' : '0');
} catch {
// Private browsing: the choice holds for the page only.
}
}
type Size = { width: number; height: number };
/**
* Part of the stage the picture fills, to check that no rotation wastes
* space: it is what `contain` shows in the turned box.
*/
export function displayedArea(stage: Size, video: Size, rotation: Rotation): Size {
const quarter = rotation === 90 || rotation === 270;
const [vw, vh] = quarter ? [video.height, video.width] : [video.width, video.height];
const scale = Math.min(stage.width / vw, stage.height / vh);
return { width: vw * scale, height: vh * scale };
}
export function readRotation(storage: KeyValueStore | null = browserStorage()): Rotation {
try {
const value = Number(storage?.getItem(KEY));
if (value === 90 || value === 180 || value === 270) return value;
} catch {
// Storage denied: no rotation.
}
return 0;
}
export function saveRotation(
rotation: Rotation,
storage: KeyValueStore | null = browserStorage(),
): void {
try {
storage?.setItem(KEY, String(rotation));
} catch {
// Same.
}
}
+40 -10
View File
@@ -1,41 +1,71 @@
import { describe, expect, it } from 'vitest';
import { backoffDelay, isTerminal, messageFor } from './session';
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);
}
});
});
describe('messageFor', () => {
it('traduit un code connu', () => {
expect(messageFor('bad_token')).toContain('jeton');
describe('isRetryable', () => {
it('offers a new series after a network give-up or a passing error', () => {
expect(isRetryable('network')).toBe(true);
expect(isRetryable('internal')).toBe(true);
});
it('retombe sur un message réseau pour un code inconnu', () => {
expect(messageFor('quelque_chose_de_nouveau')).toContain('Connexion perdue');
it('restarts neither a refusal on principle nor a protocol error', () => {
for (const code of [
'bad_token',
'bad_version',
'room_full',
'protocol_violation',
'unsupported',
]) {
expect(isRetryable(code)).toBe(false);
}
});
});
describe('messageFor', () => {
const t = createTranslator('fr', 'viewer', [
{
viewer: {
networkFallback: 'Connexion perdue.',
errors: { bad_token: 'Jeton refusé.', token_expired: 'Jeton expiré.' },
},
},
]);
it('translates a known code', () => {
expect(messageFor('bad_token', t)).toBe('Jeton refusé.');
expect(messageFor('token_expired', t)).not.toBe(messageFor('bad_token', t));
});
it('falls back to the network message for an unknown code (newer host)', () => {
expect(messageFor('something_new', t)).toBe('Connexion perdue.');
});
});
+225 -53
View File
@@ -1,22 +1,27 @@
/**
* 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 } from '../proto';
import { errorMessages, strings } from '../strings';
import type { ClientMessage, DeviceInfo, ServerMessage, StreamSettings } from '../proto';
import type { Translate } from './i18n';
import { deviceId } from './device';
import { type WakeReason, watchLifecycle } from './lifecycle';
export type ViewerErrorCode =
| 'bad_token'
| 'token_expired'
| 'bad_version'
| 'room_full'
| 'protocol_violation'
| 'internal'
| 'kicked'
| 'share_ended'
| 'network'
| 'unsupported';
@@ -25,7 +30,7 @@ export type ViewerState =
| { kind: 'negotiating' }
| { kind: 'streaming' }
| { kind: 'reconnecting'; attempt: number; delayMs: number }
| { kind: 'failed'; code: ViewerErrorCode; message: string }
| { kind: 'failed'; code: ViewerErrorCode }
| { kind: 'ended'; reason: string };
export type SessionOptions = {
@@ -34,29 +39,65 @@ export type SessionOptions = {
wsUrl: string;
deviceName?: string;
maxAttempts?: number;
/**
* Quality requested by the viewer. It is sent again after every
* `welcome`, resumes included: a dropout never degrades it.
*/
quality?: StreamSettings;
/** Listens to network, visibility and `pageshow` (default: yes). */
watchLifecycle?: boolean;
onState: (state: ViewerState) => void;
onStream: (stream: MediaStream | null) => void;
};
/** Codes après lesquels réessayer ne sert à rien: l'hôte refuse par principe. */
const TERMINAL_CODES: ReadonlySet<string> = new Set(['bad_token', 'bad_version', 'room_full']);
/** Codes after which retrying is useless: the host refuses on principle. */
const TERMINAL_CODES: ReadonlySet<string> = new Set([
'bad_token',
'token_expired',
'bad_version',
'room_full',
'kicked',
'share_ended',
]);
/**
* Codes after which a new series of attempts can help: the network or the
* host may have come back. The "Retry" button and wake-ups use them.
*/
const RETRYABLE_CODES: ReadonlySet<string> = new Set(['network', 'internal']);
const DEFAULT_MAX_ATTEMPTS = 6;
const MAX_BACKOFF_MS = 15_000;
/** Délai avant la n-ième tentative, plafonné. Fonction pure, testée. */
/**
* Minimum gap between two restarts triggered by the system. Switching from
* Wi-Fi to Ethernet fires `online` and `change` almost together, a wake-up
* fires `visibilitychange` and sometimes `pageshow`: one restart is enough.
*/
export const WAKE_MIN_INTERVAL_MS = 2000;
/** Delay before the n-th attempt, capped. Pure function, tested. */
export function backoffDelay(attempt: number): number {
const safe = Math.max(1, attempt);
return Math.min(1000 * 2 ** (safe - 1), MAX_BACKOFF_MS);
}
/** Un code d'erreur d'hôte est-il définitif ? Fonction pure, testée. */
/** Is a host error code final? Pure function, tested. */
export function isTerminal(code: string): boolean {
return TERMINAL_CODES.has(code);
}
export function messageFor(code: string): string {
return errorMessages[code] ?? strings.networkFallback;
/** Can a new series of attempts help? Pure function, tested. */
export function isRetryable(code: string): boolean {
return RETRYABLE_CODES.has(code);
}
/**
* The message for an error code, in the language of `t`. A code this viewer
* does not know (newer host) becomes the generic network message.
*/
export function messageFor(code: string, t: Translate): string {
return t(`errors.${code}`) || t('networkFallback');
}
export class ViewerSession {
@@ -64,36 +105,136 @@ export class ViewerSession {
private pc: RTCPeerConnection | null = null;
private retryTimer: ReturnType<typeof setTimeout> | null = null;
private attempt = 0;
/** Final stop: unmount, refusal on principle, end of session. */
private stopped = false;
/**
* Temporary give-up: attempts exhausted or transient host error. The
* "Retry" button or a system wake-up starts a new series.
*/
private halted = false;
private streaming = false;
private started = false;
private lastWakeAt = Number.NEGATIVE_INFINITY;
private quality: StreamSettings | null;
private unwatch: (() => void) | null = null;
private readonly maxAttempts: number;
constructor(private readonly options: SessionOptions) {
this.maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
this.quality = options.quality ?? null;
}
start(): void {
if (this.stopped) return;
if (this.stopped || this.started) return;
this.started = true;
if (typeof RTCPeerConnection === 'undefined') {
this.options.onState({
kind: 'failed',
code: 'unsupported',
message: strings.unsupported,
});
this.stopped = true;
this.options.onState({ kind: 'failed', code: 'unsupported' });
return;
}
if (this.options.watchLifecycle !== false) {
this.unwatch = watchLifecycle((reason) => this.wake(reason));
}
this.connect();
}
/** Idempotent: appelable depuis un nettoyage React, un unmount, un bouton. */
/** Idempotent: callable from a React cleanup, an unmount, a button. */
stop(): void {
this.stopped = true;
this.unwatch?.();
this.unwatch = null;
this.clearRetryTimer();
this.teardown();
this.options.onStream(null);
}
/**
* "Retry" button: after a give-up, starts a full series of attempts again,
* without reloading the page. Returns `false` if the session is stopped for
* good (refusal on principle, end): a new one must then be created.
*/
retry(): boolean {
if (this.stopped || !this.started) return false;
if (this.halted) this.restartSeries();
return true;
}
/**
* The system signals that the network or the device is back. Restarts at
* once if the session is waiting (retry timer), has given up, or holds an
* already dead transport; leaves a working session alone.
*
* Guards against a loop: at most one restart per `WAKE_MIN_INTERVAL_MS`, a
* restart while waiting counts as an attempt, and after a give-up a restart
* opens ONE series, which ends again in the failed state if the host stays
* away.
*
* Returns `true` if a connection was restarted.
*/
wake(_reason?: WakeReason): boolean {
if (this.stopped || !this.started) return false;
const now = Date.now();
if (now - this.lastWakeAt < WAKE_MIN_INTERVAL_MS) return false;
if (this.halted) {
this.lastWakeAt = now;
this.restartSeries();
return true;
}
if (this.retryTimer !== null) {
this.lastWakeAt = now;
this.clearRetryTimer();
this.connect();
return true;
}
if (this.transportDead()) {
this.lastWakeAt = now;
if (this.streaming) {
this.streaming = false;
this.attempt = 0;
}
this.connect();
return true;
}
return false;
}
/**
* Changes the requested quality. It is sent at once if signalling is open,
* and sent again at every resume.
*/
setQuality(settings: StreamSettings): void {
this.quality = settings;
this.send({ type: 'quality_request', settings } as ClientMessage);
}
/** Quality the viewer requests, as they chose it. */
get requestedQuality(): StreamSettings | null {
return this.quality;
}
private restartSeries(): void {
this.halted = false;
this.attempt = 0;
this.clearRetryTimer();
this.connect();
}
private clearRetryTimer(): void {
if (this.retryTimer !== null) {
clearTimeout(this.retryTimer);
this.retryTimer = null;
}
this.teardown();
this.options.onStream(null);
}
/** Closed signalling or a dropped WebRTC connection, with no resume planned. */
private transportDead(): boolean {
const ws = this.ws;
if (!ws || ws.readyState === WebSocket.CLOSING || ws.readyState === WebSocket.CLOSED) {
return true;
}
const state = this.pc?.connectionState;
return state === 'failed' || state === 'disconnected';
}
private connect(): void {
@@ -110,26 +251,30 @@ export class ViewerSession {
}
this.ws = ws;
// Each listener checks it still talks to the current socket: the close
// of an old socket arrives afterwards, and without this guard it would
// cut the new connection that just replaced it.
const current = () => !this.stopped && this.ws === ws;
ws.addEventListener('open', () => {
if (this.stopped) return;
if (!current()) return;
ws.send(JSON.stringify(this.hello()));
});
ws.addEventListener('message', (event) => {
if (this.stopped) return;
if (!current()) return;
void this.onServerMessage(event.data);
});
ws.addEventListener('close', () => {
if (this.stopped) return;
if (!current()) return;
this.onTransportLost();
});
ws.addEventListener('error', () => {
// `close` suit toujours: on y traite la reconnexion.
// `close` always follows: reconnection is handled there.
});
}
private hello(): ClientMessage {
const device: DeviceInfo = {
id: crypto.randomUUID(),
id: deviceId(),
name: this.options.deviceName ?? defaultDeviceName(),
user_agent: navigator.userAgent,
platform: navigator.platform ?? null,
@@ -149,12 +294,17 @@ export class ViewerSession {
try {
message = JSON.parse(raw) as ServerMessage;
} catch {
this.fail('protocol_violation', messageFor('protocol_violation'));
this.fail('protocol_violation');
return;
}
switch (message.type) {
case 'welcome':
// The chosen quality survives resumes: the host starts again from
// its default setting at every session, so it is asked again.
if (this.quality) {
this.send({ type: 'quality_request', settings: this.quality } as ClientMessage);
}
await this.negotiate();
break;
case 'answer':
@@ -162,25 +312,29 @@ export class ViewerSession {
try {
await this.pc.setRemoteDescription({ type: 'answer', sdp: message.sdp });
} catch {
this.fail('protocol_violation', messageFor('protocol_violation'));
this.fail('protocol_violation');
}
break;
case 'error':
if (isTerminal(message.code)) {
this.fail(message.code as ViewerErrorCode, messageFor(message.code));
this.fail(message.code as ViewerErrorCode);
} else {
this.fail('internal', messageFor(message.code));
this.fail('internal');
}
break;
case 'bye':
this.stop();
this.options.onState({ kind: 'ended', reason: message.reason });
break;
case 'source_changed':
case 'settings_applied':
// What the host applies does not replace what the viewer
// requests: otherwise the default setting sent back after a
// resume would overwrite the user's choice.
break;
case 'source_changed':
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;
@@ -191,14 +345,16 @@ export class ViewerSession {
this.emit({ kind: 'negotiating' });
const pc = new RTCPeerConnection({ iceServers: [] });
this.pc = pc;
const current = () => !this.stopped && this.pc === pc;
pc.addTransceiver('video', { direction: 'recvonly' });
pc.addEventListener('track', (event) => {
if (!current()) return;
const [stream] = event.streams;
this.options.onStream(stream ?? new MediaStream([event.track]));
});
pc.addEventListener('connectionstatechange', () => {
if (this.stopped) return;
if (!current()) return;
if (pc.connectionState === 'connected') {
this.streaming = true;
this.attempt = 0;
@@ -212,14 +368,15 @@ export class ViewerSession {
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
await waitForIceGathering(pc, 3000);
if (!current()) return;
const sdp = pc.localDescription?.sdp;
if (!sdp) {
this.fail('protocol_violation', messageFor('protocol_violation'));
this.fail('protocol_violation');
return;
}
this.send({ type: 'offer', sdp } as ClientMessage);
} catch {
this.onTransportLost();
if (current()) this.onTransportLost();
}
}
@@ -230,7 +387,7 @@ export class ViewerSession {
}
private onTransportLost(): void {
if (this.stopped) return;
if (this.stopped || this.halted) return;
this.teardown();
if (this.streaming) {
this.streaming = false;
@@ -242,7 +399,7 @@ export class ViewerSession {
private scheduleRetry(): void {
if (this.stopped) return;
if (this.attempt >= this.maxAttempts) {
this.fail('network', messageFor('network'));
this.fail('network');
return;
}
const delayMs = backoffDelay(this.attempt);
@@ -253,27 +410,38 @@ export class ViewerSession {
}, delayMs);
}
private fail(code: ViewerErrorCode, message: string): void {
private fail(code: ViewerErrorCode): void {
if (isRetryable(code)) {
// Temporary give-up: the wake listeners stay attached to start a
// new series when the network or the device comes back.
this.halted = true;
this.streaming = false;
this.clearRetryTimer();
this.teardown();
this.options.onStream(null);
this.emit({ kind: 'failed', code });
return;
}
this.stop();
this.options.onState({ kind: 'failed', code, message });
this.options.onState({ kind: 'failed', code });
}
private teardown(): void {
if (this.ws) {
this.ws.onopen = null;
this.ws.onmessage = null;
this.ws.onclose = null;
this.ws.onerror = null;
try {
this.ws.close();
} catch {
// Une socket déjà fermée n'est pas une erreur.
}
const ws = this.ws;
// Reset before `close()`: the listeners then see a socket that is no
// longer the current one and ignore its close.
this.ws = null;
try {
ws.close();
} catch {
// An already closed socket is not an error.
}
}
if (this.pc) {
this.pc.close();
const pc = this.pc;
this.pc = null;
pc.close();
}
}
@@ -281,7 +449,7 @@ export class ViewerSession {
if (!this.stopped) this.options.onState(state);
}
/** Statistiques de la piste entrante, pour l'affichage. */
/** Statistics of the incoming track, for display. */
async stats(): Promise<VideoStats | null> {
const pc = this.pc;
if (!pc) return null;
@@ -314,6 +482,10 @@ export type VideoStats = {
height: number;
};
/**
* Name shown to the host for this device. The values are data sent in the
* `hello` and displayed by the host, kept as they were.
*/
function defaultDeviceName(): string {
const ua = navigator.userAgent;
if (/iPad|Tablet/i.test(ua)) return 'Tablette';
+51
View File
@@ -0,0 +1,51 @@
/**
* Choices kept by the browser in `localStorage`.
*
* Storage may be denied (private browsing): every caller then falls back to
* a value that lasts for the page only.
*
* Keys used to be French (`rustscreen.appareil`, `rustscreen.miroir`...).
* They were renamed to English, and a device that visited before keeps its
* choices: `readMigrated` reads the old key once, writes the new one and
* removes the old one. This matters most for the device id, which the host
* uses to recognise a device it already admitted or banned.
*/
export type KeyValueStore = Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>;
/** `window.localStorage`, or `null` when the browser denies it. */
export function browserStorage(): Storage | null {
try {
return window.localStorage;
} catch {
return null;
}
}
/**
* The value under `key`, or else the one under `legacyKey`, moved to `key`.
*
* `translate` maps an old value to the new one, `null` dropping it. The old
* key is removed only once the new one is written: a failed write keeps the
* old value for the next visit. May throw if reading is denied.
*/
export function readMigrated(
storage: KeyValueStore,
key: string,
legacyKey: string,
translate: (legacy: string) => string | null = (legacy) => legacy,
): string | null {
const current = storage.getItem(key);
if (current !== null) return current;
const legacy = storage.getItem(legacyKey);
if (legacy === null) return null;
const value = translate(legacy);
if (value === null) return null;
try {
storage.setItem(key, value);
storage.removeItem(legacyKey);
} catch {
// Write denied: the value still holds for this page.
}
return value;
}
+68
View File
@@ -0,0 +1,68 @@
import { describe, expect, it } from 'vitest';
import type { KeyValueStore } from './storage';
import { nextTheme, readTheme, saveTheme } from './theme';
function memory(): KeyValueStore {
const values = new Map<string, string>();
return {
getItem: (key) => values.get(key) ?? null,
setItem: (key, value) => {
values.set(key, value);
},
removeItem: (key) => {
values.delete(key);
},
};
}
describe('theme (#28)', () => {
it('follows the system on first visit', () => {
expect(readTheme(memory())).toBe('system');
expect(readTheme(null)).toBe('system');
});
it('keeps the device choice', () => {
const storage = memory();
saveTheme('dark', storage);
expect(readTheme(storage)).toBe('dark');
});
it('ignores an unknown value or a denied storage', () => {
const storage = memory();
storage.setItem('rustscreen.theme', 'violet');
expect(readTheme(storage)).toBe('system');
const denied = {
getItem: () => {
throw new Error('denied');
},
setItem: () => {
throw new Error('denied');
},
removeItem: () => {
throw new Error('denied');
},
};
expect(readTheme(denied)).toBe('system');
expect(() => saveTheme('light', denied)).not.toThrow();
});
it('cycles through the three values', () => {
expect(nextTheme('system')).toBe('light');
expect(nextTheme('light')).toBe('dark');
expect(nextTheme('dark')).toBe('system');
});
it('translates and rewrites a value stored before #83', () => {
for (const [legacy, theme] of [
['systeme', 'system'],
['clair', 'light'],
['sombre', 'dark'],
] as const) {
const storage = memory();
storage.setItem('rustscreen.theme', legacy);
expect(readTheme(storage)).toBe(theme);
expect(storage.getItem('rustscreen.theme')).toBe(theme);
}
});
});
+53
View File
@@ -0,0 +1,53 @@
/**
* Viewer theme (#28): the device's by default, light or dark on request. The
* choice is kept by the device, not by the host: two tablets may prefer
* opposite themes.
*
* The value is also the `data-theme` attribute of the root element, which
* the style sheet reads.
*/
import { browserStorage, type KeyValueStore } from './storage';
export type Theme = 'system' | 'light' | 'dark';
const KEY = 'rustscreen.theme';
const ORDER: readonly Theme[] = ['system', 'light', 'dark'];
/** Values stored before #83, under the same key. */
const LEGACY_VALUES: Readonly<Record<string, Theme>> = {
systeme: 'system',
clair: 'light',
sombre: 'dark',
};
export function readTheme(storage: KeyValueStore | null = browserStorage()): Theme {
try {
const raw = storage?.getItem(KEY);
if (raw && (ORDER as readonly string[]).includes(raw)) return raw as Theme;
const migrated = raw ? LEGACY_VALUES[raw] : undefined;
if (migrated) {
saveTheme(migrated, storage);
return migrated;
}
} catch {
// Storage denied (private browsing): the system theme.
}
return 'system';
}
export function saveTheme(theme: Theme, storage: KeyValueStore | null = browserStorage()): void {
try {
storage?.setItem(KEY, theme);
} catch {
// Same: the choice holds for the page only.
}
}
/** The next theme, for a single button that cycles through all three. */
export function nextTheme(theme: Theme): Theme {
return ORDER[(ORDER.indexOf(theme) + 1) % ORDER.length] ?? 'system';
}
/** Sets the theme on the root element: the style sheet does the rest. */
export function applyTheme(theme: Theme, root: HTMLElement = document.documentElement): void {
root.dataset.theme = theme;
}
+26
View File
@@ -0,0 +1,26 @@
import { useEffect, useState } from 'react';
/**
* True for `delayMs` after the last mouse move, touch or key press. The timer
* is restarted only when needed: a moving mouse does not cause one render per
* pixel.
*/
export function useActivity(delayMs: number, activeInitially = true): boolean {
const [active, setActive] = useState(activeInitially);
useEffect(() => {
let timer: ReturnType<typeof setTimeout> | undefined;
const wake = () => {
setActive(true);
clearTimeout(timer);
timer = setTimeout(() => setActive(false), delayMs);
};
const events = ['pointermove', 'pointerdown', 'keydown', 'touchstart'] as const;
for (const e of events) window.addEventListener(e, wake, { passive: true });
timer = setTimeout(() => setActive(false), delayMs);
return () => {
clearTimeout(timer);
for (const e of events) window.removeEventListener(e, wake);
};
}, [delayMs]);
return active;
}
+29 -7
View File
@@ -1,13 +1,35 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { App } from './App';
import { I18nProvider, initialLanguage, loadCatalogs, loadLanguages } from './i18n';
import { applyTheme, readTheme } from './lib/theme';
import './styles.css';
const root = document.getElementById('root');
if (!root) throw new Error('élément racine absent');
// Before the first render: no white flash on a device set to dark.
applyTheme(readTheme());
createRoot(root).render(
<StrictMode>
<App />
</StrictMode>,
);
const root = document.getElementById('root');
if (!root) throw new Error('root element missing');
async function start(element: HTMLElement) {
const languages = await loadLanguages();
const language = initialLanguage(languages);
const catalogs = await loadCatalogs(language);
if (catalogs.length === 0) {
// Without texts, the interface cannot say anything: this one message
// stays hard-coded, in both complete languages, for lack of better.
element.textContent =
'rustscreen: textes de l’interface introuvables, rechargez la page. / Interface texts not found, reload the page.';
return;
}
document.documentElement.lang = language;
createRoot(element).render(
<StrictMode>
<I18nProvider initial={{ language, catalogs }} languages={languages}>
<App />
</I18nProvider>
</StrictMode>,
);
}
void start(root);
+1 -1
View File
@@ -5,6 +5,6 @@ import type { SessionToken } from "./SessionToken";
import type { StreamSettings } from "./StreamSettings";
/**
* Ce que le spectateur envoie à l'hôte.
* What the viewer sends to the host.
*/
export type ClientMessage = { "type": "hello", version: number, room: RoomId, token: SessionToken, device: DeviceInfo, } | { "type": "offer", sdp: string, } | { "type": "ice_candidate", candidate: string, sdp_mid: string | null, sdp_mline_index: number | null, } | { "type": "quality_request", settings: StreamSettings, } | { "type": "bye" };
+1 -1
View File
@@ -3,6 +3,6 @@ import type { DeviceId } from "./DeviceId";
export type DeviceInfo = { id: DeviceId,
/**
* Nom affiché côté hôte, modifiable par l'un ou l'autre.
* Name shown on the host side, editable by either side.
*/
name: string, user_agent: string | null, platform: string | null, };
+1 -1
View File
@@ -1,3 +1,3 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type ErrorCode = "bad_version" | "bad_token" | "room_full" | "source_unavailable" | "protocol_violation" | "internal";
export type ErrorCode = "bad_version" | "bad_token" | "token_expired" | "room_full" | "source_unavailable" | "protocol_violation" | "internal" | "kicked" | "share_ended";
+6
View File
@@ -0,0 +1,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* The short code typed by the viewer.
*/
export type PairingRequest = { code: string, };
+8
View File
@@ -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 { RoomId } from "./RoomId";
import type { SessionToken } from "./SessionToken";
/**
* 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, };
+1 -1
View File
@@ -1,6 +1,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* Profil de qualité, repris du vocabulaire de Deskreen.
* Quality preset, borrowed from Deskreen's vocabulary.
*/
export type QualityPreset = "saver" | "balanced" | "sharp";
+2 -2
View File
@@ -1,7 +1,7 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* 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;
+2 -2
View File
@@ -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, };
+1 -1
View File
@@ -1,6 +1,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* 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;
+1 -1
View File
@@ -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, };
+2 -2
View File
@@ -1,7 +1,7 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* 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";
+8 -3
View File
@@ -1,9 +1,11 @@
// 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';
export type { ServerMessage } from './ServerMessage';
export type { PairingRequest } from './PairingRequest';
export type { PairingResponse } from './PairingResponse';
export type { DeviceId } from './DeviceId';
export type { DeviceInfo } from './DeviceInfo';
export type { QualityPreset } from './QualityPreset';
@@ -14,5 +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 of the QR code link format, in step with `LINK_VERSION` (rs-proto). */
export const LINK_VERSION = 1;
-40
View File
@@ -1,40 +0,0 @@
/**
* Libellés de l'interface, centralisés.
*
* L'internationalisation complète (issue #21) remplacera ce module par i18next
* avec le même jeu de clés. Écrire les textes en dur dans les composants
* rendrait cette étape mécanique et coûteuse.
*/
export const strings = {
appName: 'rustscreen',
connecting: 'Connexion à la session…',
negotiating: 'Négociation du flux…',
streaming: 'En direct',
reconnecting: (seconds: number) => `Reconnexion dans ${seconds} s…`,
ended: 'Session terminée',
failedTitle: 'Impossible de se connecter',
retry: 'Réessayer',
fullscreen: 'Plein écran',
exitFullscreen: 'Quitter le plein écran',
statsFrames: 'images',
statsRate: 'i/s',
statsBitrate: 'débit',
statsResolution: 'résolution',
missingUrl: 'Cette adresse ne contient pas de session. Scannez le QR code affiché par l’hôte.',
missingToken: 'Jeton absent de l’adresse. Scannez le QR code plutôt que de recopier l’URL.',
unsupported: 'Ce navigateur ne prend pas en charge WebRTC.',
networkFallback: 'Connexion perdue. Vérifiez que vous êtes sur le même réseau que l’hôte.',
insecureBadge: 'non chiffré',
insecureHint:
'La page et le signalement circulent en clair sur le réseau local. Le flux vidéo, lui, est chiffré de bout en bout (DTLS-SRTP).',
} as const;
export const errorMessages: Record<string, string> = {
bad_token: 'Cette session n’accepte pas ce jeton. Demandez un nouveau QR code à l’hôte.',
bad_version: 'L’hôte et ce spectateur ne parlent pas la même version du protocole.',
room_full: 'La session a atteint son nombre maximum de spectateurs.',
protocol_violation: 'L’échange avec l’hôte a échoué (protocole).',
internal: 'L’hôte a rencontré une erreur interne.',
network: 'Connexion perdue. Vérifiez que vous êtes sur le même réseau que l’hôte.',
unsupported: strings.unsupported,
};
+193 -12
View File
@@ -1,15 +1,56 @@
/* 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;
--surface: #ffffff;
--surface-2: #eef1f5;
--border: #d9dee5;
--fg: #18202a;
--muted: #56606f;
--accent: #2563eb;
--accent-fg: #ffffff;
--live: #166534;
--warn: #854d0e;
--error: #b91c1c;
--veil: rgb(245 246 248 / 82%);
--radius: 10px;
font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
}
:root[data-theme="dark"] {
color-scheme: dark;
--bg: #0d1116;
--surface: #151b23;
--surface-2: #10161d;
--border: #26303c;
--fg: #e9eef5;
--muted: #97a5b6;
--accent: #4c9aff;
--accent-fg: #06121f;
--live: #3ddc84;
--warn: #f2c94c;
--error: #ff6b6b;
--radius: 10px;
font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
--veil: rgb(13 17 22 / 72%);
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
color-scheme: dark;
--bg: #0d1116;
--surface: #151b23;
--surface-2: #10161d;
--border: #26303c;
--fg: #e9eef5;
--muted: #97a5b6;
--accent: #4c9aff;
--accent-fg: #06121f;
--live: #3ddc84;
--warn: #f2c94c;
--error: #ff6b6b;
--veil: rgb(13 17 22 / 72%);
}
}
* {
@@ -30,6 +71,7 @@ body {
}
.app {
position: relative;
display: flex;
min-height: 100%;
flex-direction: column;
@@ -77,10 +119,13 @@ body {
background: #000;
}
/* 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;
width: 100%;
height: 100%;
max-height: 100%;
object-fit: contain;
background: #000;
}
@@ -92,8 +137,8 @@ body {
gap: 0.6rem;
align-items: center;
justify-content: center;
background: rgb(13 17 22 / 72%);
color: var(--muted);
background: var(--veil);
color: var(--fg);
font-size: 0.95rem;
}
@@ -124,24 +169,24 @@ body {
padding: 0.25rem 0.6rem;
border: 1px solid var(--border);
border-radius: 999px;
background: #10161d;
background: var(--surface-2);
color: var(--muted);
font-size: 0.82rem;
white-space: nowrap;
}
.badge-live {
border-color: rgb(61 220 132 / 35%);
border-color: color-mix(in srgb, var(--live) 40%, transparent);
color: var(--live);
}
.badge-warn {
border-color: rgb(251 202 4 / 35%);
color: #f2c94c;
border-color: color-mix(in srgb, var(--warn) 40%, transparent);
color: var(--warn);
}
.badge-error {
border-color: rgb(255 107 107 / 35%);
border-color: color-mix(in srgb, var(--error) 40%, transparent);
color: var(--error);
}
@@ -178,13 +223,13 @@ body {
border: 1px solid transparent;
border-radius: 8px;
background: var(--accent);
color: #06121f;
color: var(--accent-fg);
font: inherit;
font-weight: 600;
cursor: pointer;
}
.topbar .button {
.topbar .button-theme {
margin-left: auto;
}
@@ -204,11 +249,44 @@ body {
}
.footer {
display: flex;
align-items: center;
min-height: 2.75rem;
border-top: 1px solid var(--border);
background: var(--surface);
}
/* Language picker (#21): discreet, at the end of the footer. */
.language {
margin-left: auto;
padding: 0 1rem;
}
.language select {
padding: 0.25rem 0.4rem;
border: 1px solid var(--border);
border-radius: 6px;
background: var(--surface);
color: var(--fg);
font: inherit;
font-size: 0.82rem;
}
.pairing .language {
display: block;
margin-top: 1rem;
padding: 0;
}
.visually-hidden {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
.stats {
display: flex;
flex-wrap: wrap;
@@ -244,3 +322,106 @@ body {
padding: 0.5rem 0.75rem;
}
}
/* Home without a session: short code and scan (#19). */
.pairing {
width: min(26rem, 100%);
}
.pairing-form {
display: flex;
flex-wrap: wrap;
gap: 0.6rem;
align-items: center;
margin-bottom: 0.75rem;
}
.pairing-form label {
flex-basis: 100%;
color: var(--muted);
font-size: 0.9rem;
}
.pairing-code {
flex: 1;
min-width: 9rem;
padding: 0.5rem 0.7rem;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--bg);
color: var(--fg);
font:
600 1.4rem / 1.2 ui-monospace,
"SF Mono",
Menlo,
monospace;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.pairing-code:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
.panel .pairing-error {
color: var(--error);
}
.panel .pairing-hint {
font-size: 0.88rem;
}
.scanner {
display: flex;
flex-direction: column;
gap: 0.6rem;
}
.scanner-video {
width: 100%;
aspect-ratio: 1;
object-fit: cover;
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;
}
}
+34 -2
View File
@@ -1,8 +1,40 @@
import { defineConfig } from 'vite';
import { readdirSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import react from '@vitejs/plugin-react';
import { defineConfig, type Plugin } from 'vite';
/**
* In development (`npm run dev`), nobody serves `/locales/`: this plugin does
* it from `locales/` at the repository root, like the host in production.
*/
function locales(): Plugin {
const dir = join(__dirname, '../../locales');
return {
name: 'rustscreen-locales',
configureServer(server) {
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 (files.includes(name)) {
body = readFileSync(join(dir, name), 'utf8');
}
if (body === undefined) return next();
response.setHeader('Content-Type', 'application/json; charset=utf-8');
response.end(body);
});
},
};
}
export default defineConfig({
plugins: [react()],
plugins: [react(), locales()],
build: {
target: 'es2022',
sourcemap: true,
+4 -2
View File
@@ -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
+3 -1
View File
@@ -11,7 +11,9 @@
"docs/**/*.json",
"!**/dist",
"!**/node_modules",
"!apps/viewer/src/proto/**"
"!apps/viewer/src/proto/**",
"!apps/desktop/src/bindings/**",
"!apps/desktop/src-tauri/**"
]
},
"formatter": {
Loaded 100 of 202 files, more files were not shown because too many files have changed in this diff. Show more