Compare commits

..
15 Commits
Author SHA1 Message Date
showdown d29ca34b9a Ring decoder: coarse-to-fine sync search (2x faster), lab phone at 960px, bench cpu throttling 2026-11-16 18:27:34 +01:00
showdown fe1da7ea1c Ring code: static logo, stronger dark/light contrast, cross-fade on code change 2026-11-16 18:19:40 +01:00
showdown 112ba3967d Merge ring code lab (not wired into the app yet) 2026-11-16 18:15:22 +01:00
showdown 38557b3958 Ring code v2: logo disc locator, projective rectification, animated dashes, lab pages, bench tool 2026-11-16 18:15:22 +01:00
showdown 4784aaa67d WIP ring code: qr-anchored prototype, encoder, bench, lab pages 2026-11-16 18:00:24 +01:00
showdown 766426b328 Voter dialogs focus their title, no focus ring on Annuler 2026-11-16 17:28:50 +01:00
showdown d07667efee Admin: real sliding switch for enrollment, role=switch 2026-11-16 17:02:45 +01:00
showdown 40e0c7c479 Configurable heartbeat, test that a dead peer doesn't stop pings 2026-11-16 14:47:47 +01:00
showdown eae125a469 Websocket sends: per-send timeout, parallel broadcast, heartbeat never dies 2026-11-16 14:35:53 +01:00
showdown e3605c48ec Hide presence QR when every voter is a code holder 2026-11-16 14:05:56 +01:00
showdown b2b598d236 Vote-time presence scan, rescue codes, websocket heartbeat
Each vote can require N fresh codes read off the projector (default 3,
off for rooms without a projector); voters enrolled with a paper or
rescue code are exempt. Rescue codes enroll a phone without camera.
Projector keeps the QR up while such a vote is open. Server pings every
socket every 25s so proxies keep them open. Composer no longer closes on
enter. Schema migrates existing databases.
2026-11-16 13:48:53 +01:00
showdown e328a0983f Admin: tabs, question composer dialog, settings autosave
Default answers Pour/Contre/Abstention/NPPPAV, svg icons instead of status
dots, no live/open status labels, inclusive wording across the UI and docs.
2026-11-16 13:26:46 +01:00
showdown 74c9b34ec1 Silence per-connection uvicorn logs (client ip + timing) 2026-11-16 13:13:48 +01:00
showdown 9f54677e5d Pelican/pterodactyl deploy support: run.py, requirements.txt, SERVER_PORT, ready marker 2026-11-16 13:00:28 +01:00
showdown e526edd75e RotatyVote: in-person anonymous voting with rotating QR enrollment
Starlette backend with sqlite, rotating HMAC QR tokens pushed to a
key-protected projector page, multi-scan enrollment, optional one-time
paper codes, anonymous ballots split from participation, live question
push over websockets, e2e tests over HTTP and TLS.
2026-11-16 12:58:26 +01:00
43 changed files with 537 additions and 4027 deletions
-1
View File
@@ -7,4 +7,3 @@ __pycache__/
.claude/ .claude/
docs/video/ docs/video/
tools/bench_out/ tools/bench_out/
static/ringlab/tmp/
+1 -1
View File
@@ -30,4 +30,4 @@ RV_TEST_TLS=1 uv run pytest
2. Les deux suites de tests passent (HTTP et TLS). 2. Les deux suites de tests passent (HTTP et TLS).
3. Décrivez ce qui change et comment vous l'avez vérifié. 3. Décrivez ce qui change et comment vous l'avez vérifié.
En contribuant, vous acceptez que votre code soit publié sous la licence du projet : MIT avec la condition Commons Clause (voir [LICENSE](LICENSE)). En contribuant, vous acceptez que votre code soit publié sous licence MIT.
-23
View File
@@ -1,26 +1,3 @@
"Commons Clause" License Condition v1.0
The Software is provided to you by the Licensor under the License, as defined
below, subject to the following condition.
Without limiting other conditions in the License, the grant of rights under the
License will not include, and the License does not grant to you, the right to
Sell the Software.
For purposes of the foregoing, "Sell" means practicing any or all of the rights
granted to you under the License to provide to third parties, for a fee or
other consideration (including without limitation fees for hosting or
consulting/support services related to the Software), a product or service
whose value derives, entirely or substantially, from the functionality of the
Software. Any license notice or attribution required by the License must also
include this Commons Clause License Condition notice.
Software: RotatyVote
License: MIT
Licensor: Showdown76py
---
MIT License MIT License
Copyright (c) 2026 Showdown76py Copyright (c) 2026 Showdown76py
+18 -46
View File
@@ -1,6 +1,6 @@
# rotatyvote # RotatyVote
**rotaty**vote est une app web qui permet d'effectuer des votes anonymes, en s'assurant que la personne est présente physiquement. Un code scannable dynamique est projeté au tableau. Pour s'inscrire, le téléphone effectue plusieurs lectures. Le code ne peut pas être partagé en photo ou vidéo. Vote anonyme en présentiel. Un QR code projeté change toutes les 0,5 à 2 s. Pour s'inscrire, le téléphone doit en lire plusieurs à la suite (5 par défaut), ce qui oblige à être devant l'écran.
![projecteur](docs/screenshots/6-projecteur-qr-et-question.jpg) ![projecteur](docs/screenshots/6-projecteur-qr-et-question.jpg)
@@ -15,7 +15,7 @@ Ouvrez `http://localhost:8000`, créez un scrutin, ouvrez le lien projecteur sur
### HTTPS obligatoire ### HTTPS obligatoire
Les téléphones n'ouvrent la caméra qu'en HTTPS. Il y a donc 3 options possibles : Les téléphones n'ouvrent la caméra qu'en HTTPS. Trois options :
| Option | Variables | | Option | Variables |
|---|---| |---|---|
@@ -23,7 +23,7 @@ Les téléphones n'ouvrent la caméra qu'en HTTPS. Il y a donc 3 options possibl
| Reverse proxy (Caddy, nginx) | `BEHIND_PROXY=1` | | Reverse proxy (Caddy, nginx) | `BEHIND_PROXY=1` |
| Tunnel (Cloudflare Tunnel, etc.) | `BEHIND_PROXY=1` | | Tunnel (Cloudflare Tunnel, etc.) | `BEHIND_PROXY=1` |
Dans tous les cas, définissez `PUBLIC_URL=https://vote.example.org` (pour l'affichage sur le site) Dans tous les cas, définissez `PUBLIC_URL=https://vote.example.org` : c'est l'adresse encodée dans les QR codes.
Caddy : Caddy :
@@ -55,44 +55,28 @@ location / {
| `PUBLIC_URL` | origine du projecteur | URL encodée dans les QR | | `PUBLIC_URL` | origine du projecteur | URL encodée dans les QR |
| `PORT` / `HOST` | `8000` / `0.0.0.0` | écoute | | `PORT` / `HOST` | `8000` / `0.0.0.0` | écoute |
| `DB_PATH` | `rotatyvote.db` | base SQLite | | `DB_PATH` | `rotatyvote.db` | base SQLite |
| `CREATE_PASSWORD` | vide | mot de passe pour créer un scrutin, optionnel | | `CREATE_PASSWORD` | vide | mot de passe pour créer un scrutin |
| `TOKEN_GRACE_MS` | `2500` | tolérance réseau sur un code | | `TOKEN_GRACE_MS` | `2500` | tolérance réseau sur un code |
| `MAX_TRIALS` | `50` | essais `/essai` ouverts en même temps |
## Déroulé ## Déroulé
1. Créer le scrutin, garder le lien admin (clé dans l'URL). 1. Créer le scrutin, garder le lien admin (clé dans l'URL, non récupérable).
2. Ouvrir les inscriptions. Le projecteur affiche le code dyanmique et le nombre d'inscriptions. 2. Ouvrir les inscriptions. Le projecteur affiche le QR rotatif et le nombre d'inscriptions.
3. Fermer les inscriptions quand tout le monde est inscrit. 3. Fermer les inscriptions quand tout le monde est inscrit.
4. Lancer les questions préparées ou en créer en direct. Les téléphones les reçoivent en temps réel. 4. Lancer les questions préparées ou en créer en direct. Les téléphones les reçoivent instantanément.
5. Clore, publier les résultats à l'écran. Les votes comptés à la main (bulletins papier, main levée) s'ajoutent avec « Votes en plus » : ils restent séparés des votes par téléphone et s'affichent en orange hachuré. Vous pouvez à la fin, exporter les résultats en JSON. 5. Clore, publier les résultats à l'écran, exporter en JSON.
Avant votre vote, `/essai` lance un scrutin jetable sur l'écran à tester. On vise l'écran avec son téléphone depuis le fond de la salle. Dès la première inscription, une question d'essai s'ouvre pour essayer aussi le vote et ses 3 secondes de confirmation. Personne ne reçoit le lien d'administration, et l'essai est effacé au bout de 2 h, même sans mot de passe de création. ## Sécurité : ce qui est garanti, ce qui ne l'est pas
## Code circulaire **Présence à l'inscription.** Chaque code est un HMAC du créneau horaire, valable environ 3 s. Il faut N codes distincts en une fenêtre courte : une photo ou une capture partagée ne suffit pas.
Par défaut, le projecteur affiche un code circulaire dyanmique. Le QR classique reste disponible par scrutin (Inscriptions > Code projeté). Cette option peut être avantagueuse si vous avez des soucis de lecture de code au tableau à cause de la distance, des reflets, de l'angle de vue, etc. **Présence au vote (activée par défaut).** Pour valider un bulletin, le téléphone doit lire 3 codes frais sur le projecteur, qui garde le QR affiché pendant chaque vote. Un téléphone inscrit puis emporté hors de la salle ne peut donc plus voter. Les personnes inscrites avec un code papier ou un code de secours en sont dispensées. Désactivable (Inscriptions > Sécurité) pour une salle sans vidéoprojecteur.
Spécifications techniques de notre code circulaire dynamique : **Anonymat.** Deux tables séparées : `participation` (qui a voté à quelle question) et `ballots` (quel choix), écrites dans la même transaction. Aucune colonne ne relie un bulletin à la personne qui a voté, aucun horodatage, identifiants aléatoires, journal SQLite non-WAL, `secure_delete`, aucun log de connexion. Les codes de présence sont vérifiés puis oubliés. Les résultats restent cachés pendant le vote, admin compris. Un vote est définitif.
- L'anneau intérieur porte un motif fixe qui donne l'orientation. Les 3 autres portent "un jeton" : 16 bits de créneau et 32 bits de signature HMAC, protégés par un code Reed-Solomon (12, 6) qui corrige 3 octets illisibles.
- Le téléphone repère le disque central, corrige la perspective à partir des anneaux (deux cercles concentriques suffisent à retrouver l'horizon), lit les segments puis corrige les erreurs.
- La longueur et l'opacité des segments varient en continu, dans des bornes qui ne touchent jamais la donnée.
- Il reste tout de même un petit QR fixe, dans le coin de l'écran, pour ouvrir la page de vote.
- Signature de 32 bits sur le jeton. Il ne vaut que pendant environ 3 s et le serveur doit le recevoir en ligne. Même à 1 000 essais par seconde, la probabilité de deviner un jeton valide pendant sa durée de vie est d'environ 7 × 10⁻⁷, et il en faut 5 distincts pour s'inscrire.
- De loin : le téléphone cherche le disque sur une copie réduite de l'image, puis lit un recadrage à la résolution du capteur. Le disque est repéré par rapport au blanc qui l'entoure, pas par un seuil global. Repère pratique : rester à moins de 10 fois le diamètre du code (un code de 1 m se lit jusqu'à 10 m environ).
## Sécurité - garanties de sécurité de rotatyvote
**Présence à l'inscription.** Chaque code est un HMAC du créneau horaire, valable environ 3 s. Il faut N codes distincts en une fenêtre courte : une photo ou une vidéo ne suffit pas.
**Présence au vote (activée par défaut).** Pour valider un bulletin, le téléphone doit lire le code sur le projecteur, pour vérifier la présence dans la salle. Un téléphone inscrit puis emporté hors de la salle ne peut donc plus voter. (Désactivable (Inscriptions > Sécurité) pour une salle sans vidéoprojecteur.)
**Anonymat.** Deux tables séparées : `participation` (qui a voté à quelle question) et `ballots` (quel choix), écrites dans la même transaction. Aucune colonne ne relie un bulletin à la personne qui a voté, aucun horodatage, identifiants aléatoires, journal SQLite non-WAL, `secure_delete`, aucun log de connexion. Les codes de présence sont vérifiés puis oubliés. Les résultats restent cachés pendant le vote y compris pour les administrateurs. Par conscéquent, un vote est définitif.
**Un vote par inscription et par question.** Imposé par la base (clé primaire), y compris en requêtes simultanées. **Un vote par inscription et par question.** Imposé par la base (clé primaire), y compris en requêtes simultanées.
**Une personne, un vote (garanti seulement avec le code papier).** Le même QR vaut pour toute la salle. Bien que des protections sont mises en place, aucun site web ne peut identifier un téléphone de façon fiable. En navigation privée ou par script, une personne présente peut créer plusieurs inscriptions. Avec « Code papier obligatoire », chaque inscription consomme un code à usage unique remis à l'émargement (testé en accès simultanés : un code, une inscription). Le code n'est jamais relié au bulletin. **Une personne, un vote : garanti seulement avec le code papier.** Le même QR vaut pour toute la salle, et aucun site web ne peut identifier un téléphone de façon fiable : en navigation privée ou par script, une personne présente peut créer plusieurs inscriptions. Avec « Code papier obligatoire », chaque inscription consomme un code à usage unique remis à l'émargement (testé en accès simultanés : un code, une inscription). Le code n'est jamais relié au bulletin.
Il est conseillé de compter le nombre de personnes présentes, et de vérifier que le compte est bon, ou d'imposer un plafond.
**Caméra cassée.** Les codes de secours permettent de s'inscrire sans scanner. À remettre après vérification sur place : ils dispensent aussi du scan au vote. **Caméra cassée.** Les codes de secours permettent de s'inscrire sans scanner. À remettre après vérification sur place : ils dispensent aussi du scan au vote.
@@ -103,12 +87,12 @@ Il est conseillé de compter le nombre de personnes présentes, et de vérifier
| Photo ou capture du QR envoyée à quelqu'un | Aucun : le code expire en ~3 s et il en faut plusieurs | Intégrée | | Photo ou capture du QR envoyée à quelqu'un | Aucun : le code expire en ~3 s et il en faut plusieurs | Intégrée |
| Lien projecteur divulgué | Le QR peut être affiché ailleurs | Clé masquée de l'URL, révocable (Partage > Nouveau lien) | | Lien projecteur divulgué | Le QR peut être affiché ailleurs | Clé masquée de l'URL, révocable (Partage > Nouveau lien) |
| Téléphone inscrit confié à une personne absente | Vote à distance | Scan au moment du vote | | Téléphone inscrit confié à une personne absente | Vote à distance | Scan au moment du vote |
| Retransmission vidéo en direct de l'écran, ou relais des codes par script sophistiqué | Une personne absente peut s'inscrire et voter en direct | Code papier obligatoire (sans code, pas d'inscription). A défaut, compteur affiché et fermeture rapide des inscriptions | | Retransmission vidéo en direct de l'écran, ou relais des codes par script | Une personne absente peut s'inscrire et voter en direct | Code papier obligatoire (sans code, pas d'inscription) ; à défaut, compteur affiché et fermeture rapide des inscriptions |
| Code papier ou de secours confié à une personne absente | Elle vote à la place de la personne présente, sans voix supplémentaire | Équivaut à une procuration ; remettre les codes en main propre | | Code papier ou de secours confié à une personne absente | Elle vote à la place de la personne présente, sans voix supplémentaire | Équivaut à une procuration ; remettre les codes en main propre |
**Hors périmètre.** Une personne malveillante qui administre le serveur (elle pourrait modifier le code). L'infrastructure de rotatyvote ne permet pas de mettre en place des vérifications pour ce risque. **Hors périmètre.** Une personne malveillante qui administre le serveur (elle pourrait modifier le code). Pour cette menace, il faut un système de vote vérifiable de bout en bout.
## Tests (pour les constributeurs) ## Tests
```bash ```bash
uv run pytest uv run pytest
@@ -132,18 +116,6 @@ Les tests lancent un vrai serveur et lisent les codes sur le WebSocket du projec
- schéma anonyme ; - schéma anonyme ;
- scan de présence au vote, codes de secours, code papier en accès simultanés. - scan de présence au vote, codes de secours, code papier en accès simultanés.
## Écriture du source code
L'intelligence artificielle générative a partiellement contribué à l'écriture de ce code. Modèle : Claude Opus 5.5.
## Licence ## Licence
MIT avec la condition Commons Clause, voir [LICENSE](LICENSE). MIT, voir [LICENSE](LICENSE). Contributions : [CONTRIBUTING.md](CONTRIBUTING.md).
- Tout le monde peut utiliser RotatyVote gratuitement, entreprises comprises, y compris pour ses propres votes.
- Vous pouvez modifier le code et le partager gratuitement, sous la même licence.
- Vous ne pouvez pas le vendre, ni vendre un logiciel ou un service (hébergement, support, intégration) dont la valeur repose entièrement ou en grande partie sur lui.
Ce n'est donc pas une licence open source au sens de l'OSI, mais le code reste public. Les versions publiées avant ce changement restent sous MIT seule.
Contributions : [CONTRIBUTING.md](CONTRIBUTING.md).
Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

-1
View File
@@ -2,7 +2,6 @@
name = "rotatyvote" name = "rotatyvote"
version = "0.1.0" version = "0.1.0"
requires-python = ">=3.11" requires-python = ">=3.11"
license = { file = "LICENSE" }
dependencies = [ dependencies = [
"segno>=1.6.6", "segno>=1.6.6",
"starlette>=1.10.0", "starlette>=1.10.0",
+47 -305
View File
@@ -1,6 +1,5 @@
import asyncio import asyncio
import contextlib import contextlib
import hmac
import json import json
import logging import logging
from dataclasses import dataclass, field from dataclasses import dataclass, field
@@ -12,14 +11,14 @@ from starlette.applications import Starlette
from starlette.exceptions import HTTPException from starlette.exceptions import HTTPException
from starlette.middleware import Middleware from starlette.middleware import Middleware
from starlette.requests import Request from starlette.requests import Request
from starlette.responses import FileResponse, JSONResponse, RedirectResponse, Response from starlette.responses import FileResponse, JSONResponse, Response
from starlette.routing import Mount, Route, WebSocketRoute from starlette.routing import Mount, Route, WebSocketRoute
from starlette.staticfiles import StaticFiles from starlette.staticfiles import StaticFiles
from starlette.websockets import WebSocket, WebSocketDisconnect from starlette.websockets import WebSocket, WebSocketDisconnect
from . import config, ringcode from . import config
from .db import DB, open_db from .db import DB, open_db
from .tokens import check_key, current_slot, make_pass, new_key, now_ms, sha, verify_pass from .tokens import check_key, current_slot, make_token, new_key, now_ms, sha, verify_token
log = logging.getLogger("rotatyvote") log = logging.getLogger("rotatyvote")
STATIC = Path(__file__).resolve().parent.parent / "static" STATIC = Path(__file__).resolve().parent.parent / "static"
@@ -51,52 +50,11 @@ def clear_attempts(pid):
del attempts[k] del attempts[k]
# camera app scans, in memory like attempts: (pid, voter id) -> pass end, claim nonce -> (pid, minted at)
passes: dict[tuple[str, str], int] = {}
claims: dict[str, tuple[str, int, int]] = {} # nonce -> (pid, minted at, ms the code was off screen)
def grant_pass(pid, vid):
now = now_ms()
if len(passes) > 20000:
for k in [k for k, t in passes.items() if t < now]:
del passes[k]
passes[(pid, vid)] = now + config.PASS_HOLD_MS
def has_pass(pid, vid):
return passes.get((pid, vid), 0) >= now_ms()
def mint_claim(pid, late):
now = now_ms()
if len(claims) > 20000:
for k in [k for k, (_, t, _) in claims.items() if now - t > config.PASS_CLAIM_TTL_MS]:
del claims[k]
nonce = new_key()
claims[nonce] = (pid, now, late)
return nonce
def pass_on(p):
# the classic qr is the camera app code itself, it can't be turned off there
return bool(p["camera_pass"]) or p["code_style"] == "qr"
def pass_late(p, tok):
"""ms since the camera app code left the screen (<= 0 still shown), None if forged or past PASS_GRACE_MS"""
slot = verify_pass(p["secret"], p["id"], tok[:40], config.PASS_ROTATE_MS, config.PASS_GRACE_MS)
return None if slot is None else now_ms() - (slot + 1) * config.PASS_ROTATE_MS
def q_public(q, with_results: bool): def q_public(q, with_results: bool):
d = { d = {
"id": q["id"], "text": q["text"], "kind": q["kind"], "options": json.loads(q["options"]), "id": q["id"], "text": q["text"], "kind": q["kind"], "options": json.loads(q["options"]),
"max_choices": q["max_choices"], "allow_blank": bool(q["allow_blank"]), "state": q["state"], "max_choices": q["max_choices"], "allow_blank": bool(q["allow_blank"]), "state": q["state"],
"results_public": bool(q["results_public"]), "shown": bool(q["shown"]), "shared": bool(q["shared"]), "results_public": bool(q["results_public"]), "participants": db.participants(q["id"]),
"participants": db.participants(q["id"]),
# how many were added by hand, never how they split while the vote is open
"extra_ballots": db.extra(q)["ballots"],
} }
# nobody, admin included, sees tallies while a question is open # nobody, admin included, sees tallies while a question is open
if with_results and q["state"] == "closed": if with_results and q["state"] == "closed":
@@ -113,12 +71,11 @@ def admin_state(pid):
"scans_required": p["scans_required"], "enrollment_open": bool(p["enrollment_open"]), "scans_required": p["scans_required"], "enrollment_open": bool(p["enrollment_open"]),
"max_voters": p["max_voters"], "expected": p["expected"], "max_voters": p["max_voters"], "expected": p["expected"],
"require_code": bool(p["require_code"]), "focus_qid": p["focus_qid"], "require_code": bool(p["require_code"]), "focus_qid": p["focus_qid"],
"vote_scans": p["vote_scans"], "code_style": p["code_style"], "entry_big": bool(p["entry_big"]), "vote_scans": p["vote_scans"],
"camera_pass": bool(p["camera_pass"]), "share_key": p["share_key"],
}, },
"voters": db.voter_count(pid), "voters": db.voter_count(pid),
"codes": codes_summary(pid), "codes": codes_summary(pid),
"questions": [{**q_public(q, True), "extra": db.extra(q)} for q in db.questions(pid)], "questions": [q_public(q, True) for q in db.questions(pid)],
"screens": len(hub.screens.get(pid, ())), "screens": len(hub.screens.get(pid, ())),
"public_url": config.PUBLIC_URL, "public_url": config.PUBLIC_URL,
} }
@@ -159,8 +116,7 @@ def screen_state(pid):
"type": "state", "title": p["title"], "enrollment_open": bool(p["enrollment_open"]), "type": "state", "title": p["title"], "enrollment_open": bool(p["enrollment_open"]),
"voters": db.voter_count(pid), "expected": p["expected"], "max_voters": p["max_voters"], "voters": db.voter_count(pid), "expected": p["expected"], "max_voters": p["max_voters"],
"scans_required": p["scans_required"], "interval_ms": p["interval_ms"], "focus": focus, "scans_required": p["scans_required"], "interval_ms": p["interval_ms"], "focus": focus,
"presence": presence_check(p), "vote_scans": p["vote_scans"], "code_style": p["code_style"], "presence": presence_check(p), "vote_scans": p["vote_scans"],
"entry_big": bool(p["entry_big"]), "camera_pass": pass_on(p),
} }
@@ -174,43 +130,14 @@ def voter_state(pid, voter):
d["voted"] = q["id"] in voted d["voted"] = q["id"] in voted
qs.append(d) qs.append(d)
scans = 0 if voter["via_code"] else p["vote_scans"] scans = 0 if voter["via_code"] else p["vote_scans"]
return {"type": "state", "title": p["title"], "enrolled": True, "questions": qs, "vote_scans": scans, return {"type": "state", "title": p["title"], "enrolled": True, "questions": qs, "vote_scans": scans}
"code_style": p["code_style"], "camera_pass": pass_on(p)}
def qr_modules(url: str, error="m"): def qr_modules(url: str):
qr = segno.make(url, error=error, micro=False) qr = segno.make(url, error="m", micro=False)
return ["".join("1" if b else "0" for b in row) for row in qr.matrix] return ["".join("1" if b else "0" for b in row) for row in qr.matrix]
def pass_slot():
return now_ms() // config.PASS_ROTATE_MS
def entry_qr(base: str, p, slot: int):
"""qr for the phone's camera app: opens the voting page and proves presence (/V/pid/code redirects).
upper case keeps it in qr alphanumeric mode, a smaller symbol"""
pid, rot = p["id"], config.PASS_ROTATE_MS
if not pass_on(p):
# camera app scans turned off: a plain link to the page, it never changes
return {"type": "entry", "modules": qr_modules(f"{base}/V/{pid}".upper(), error="q"), "url": f"{base}/v/{pid}"}
url = f"{base}/V/{pid}/{make_pass(p['secret'], pid, slot)}".upper()
# level q survives a glare patch or a smudge on a quarter of the symbol. 33 modules w/ the code
return {"type": "entry", "modules": qr_modules(url, error="q"), "url": f"{base}/v/{pid}",
"token": make_pass(p["secret"], pid, slot), "slot": slot, "interval_ms": rot, "valid_until": (slot + 1) * rot}
def resolve_token(p, tok: str, grace_ms: int):
"""full slot for a fresh, authentic ring token 'r<s16>.<mac>', else None"""
if not tok.startswith("r"):
return None
iv, now = p["interval_ms"], now_ms()
slot = ringcode.resolve(p["secret"], p["id"], iv, tok, current_slot(iv, now), (iv + grace_ms) // iv + 1)
if slot is None or not 0 <= now - slot * iv <= iv + grace_ms:
return None
return slot
class Hub: class Hub:
def __init__(self): def __init__(self):
self.screens: dict[str, dict[WebSocket, str]] = {} # ws -> origin self.screens: dict[str, dict[WebSocket, str]] = {} # ws -> origin
@@ -269,13 +196,6 @@ class Hub:
return return
await self.send_all(conns, voter_state(pid, v)) await self.send_all(conns, voter_state(pid, v))
async def send_entry(self, p, screens, slot, kind="entry"):
by_origin: dict[str, list[WebSocket]] = {}
for ws, origin in list(screens.items()):
by_origin.setdefault(config.PUBLIC_URL or origin, []).append(ws)
for base, conns in by_origin.items():
await self.send_all(conns, {**entry_qr(base, p, slot), "type": kind})
def ensure_ticker(self, pid): def ensure_ticker(self, pid):
t = self.tickers.get(pid) t = self.tickers.get(pid)
if t and not t.done(): if t and not t.done():
@@ -285,31 +205,23 @@ class Hub:
self.tickers[pid] = asyncio.get_running_loop().create_task(self._tick(pid)) self.tickers[pid] = asyncio.get_running_loop().create_task(self._tick(pid))
async def _tick(self, pid): async def _tick(self, pid):
last_pass = -1
try: try:
while True: while True:
p = db.poll(pid) p = db.poll(pid)
screens = self.screens.get(pid) screens = self.screens.get(pid)
if not p or not needs_qr(p) or not screens: if not p or not needs_qr(p) or not screens:
return return
ps = pass_slot()
if p["code_style"] == "qr":
# the classic qr is the camera app code itself, in the middle of the screen
if ps != last_pass:
last_pass = ps
await self.send_entry(p, screens, ps, "qr")
await asyncio.sleep(max(0.01, ((ps + 1) * config.PASS_ROTATE_MS - now_ms()) / 1000))
continue
if ps != last_pass and pass_on(p):
last_pass = ps
await self.send_entry(p, screens, ps)
iv = p["interval_ms"] iv = p["interval_ms"]
slot = current_slot(iv) slot = current_slot(iv)
# the screen draws the rings itself, it only needs the bits for this slot token = make_token(p["secret"], pid, iv, slot)
await self.send_all(screens, { by_origin: dict[str, list[WebSocket]] = {}
"type": "ring", "bits": ringcode.render_bits(p["secret"], pid, iv, slot), for ws, origin in list(screens.items()):
"token": ringcode.token(p["secret"], pid, iv, slot), "slot": slot, by_origin.setdefault(config.PUBLIC_URL or origin, []).append(ws)
"interval_ms": iv, "valid_until": (slot + 1) * iv}) for base, conns in by_origin.items():
url = f"{base}/v/{pid}#{token}"
msg = {"type": "qr", "url": url, "modules": qr_modules(url), "slot": slot,
"interval_ms": iv, "valid_until": (slot + 1) * iv}
await self.send_all(conns, msg)
await asyncio.sleep(max(0.01, ((slot + 1) * iv - now_ms()) / 1000)) await asyncio.sleep(max(0.01, ((slot + 1) * iv - now_ms()) / 1000))
except asyncio.CancelledError: except asyncio.CancelledError:
pass pass
@@ -462,15 +374,9 @@ async def create_poll(request: Request):
expected = opt_int(d.get("expected"), 1, 100000, "expected") expected = opt_int(d.get("expected"), 1, 100000, "expected")
max_voters = opt_int(d.get("max_voters"), 1, 100000, "max_voters") max_voters = opt_int(d.get("max_voters"), 1, 100000, "max_voters")
vote_scans = clamp_int(d.get("vote_scans", config.DEFAULT_VOTE_SCANS), 0, config.MAX_VOTE_SCANS, "vote_scans") vote_scans = clamp_int(d.get("vote_scans", config.DEFAULT_VOTE_SCANS), 0, config.MAX_VOTE_SCANS, "vote_scans")
code_style = d.get("code_style", "ring")
if code_style not in ("ring", "qr"):
return err("bad_code_style")
questions = [parse_question(q) for q in (d.get("questions") or [])] questions = [parse_question(q) for q in (d.get("questions") or [])]
pid, admin_key, screen_key = db.create_poll(title, interval, scans, bool(d.get("require_code")), pid, admin_key, screen_key = db.create_poll(title, interval, scans, bool(d.get("require_code")),
expected, max_voters, vote_scans, code_style) expected, max_voters, vote_scans)
# the giant entry qr beside the ring is the default: people open the page from the back rows
db.update_poll(pid, entry_big=int(d.get("entry_big", True) is not False),
camera_pass=int(d.get("camera_pass", True) is not False))
for q in questions: for q in questions:
db.add_question(pid, *q) db.add_question(pid, *q)
codes = int(d.get("codes") or 0) codes = int(d.get("codes") or 0)
@@ -479,18 +385,6 @@ async def create_poll(request: Request):
return JSONResponse({"id": pid, "admin_key": admin_key, "screen_key": screen_key}) return JSONResponse({"id": pid, "admin_key": admin_key, "screen_key": screen_key})
async def create_trial(request: Request):
# no password even when creation is locked: a trial only enrolls, nobody gets its admin key
db.purge_trials(config.TRIAL_TTL_MS)
if db.trial_count() >= config.MAX_TRIALS:
return err("too_many_trials", 429)
pid, _, screen_key = db.create_poll("Essai", 800, 5, False, None, 200, config.DEFAULT_VOTE_SCANS, "ring",
trial=True)
db.add_question(pid, "Le vote d'essai fonctionne ?", "single", ["Oui", "Non"], 1, False)
db.update_poll(pid, enrollment_open=1, entry_big=1)
return JSONResponse({"id": pid, "screen_key": screen_key})
async def admin_get(request: Request): async def admin_get(request: Request):
pid = request.path_params["pid"] pid = request.path_params["pid"]
require_admin(request, pid) require_admin(request, pid)
@@ -499,7 +393,7 @@ async def admin_get(request: Request):
async def admin_patch(request: Request): async def admin_patch(request: Request):
pid = request.path_params["pid"] pid = request.path_params["pid"]
require_admin(request, pid) p = require_admin(request, pid)
d = await body(request) d = await body(request)
upd = {} upd = {}
if "title" in d: if "title" in d:
@@ -519,14 +413,6 @@ async def admin_patch(request: Request):
upd["expected"] = opt_int(d["expected"], 1, 100000, "expected") upd["expected"] = opt_int(d["expected"], 1, 100000, "expected")
if "require_code" in d: if "require_code" in d:
upd["require_code"] = int(bool(d["require_code"])) upd["require_code"] = int(bool(d["require_code"]))
if "code_style" in d:
if d["code_style"] not in ("ring", "qr"):
return err("bad_code_style")
upd["code_style"] = d["code_style"]
if "entry_big" in d:
upd["entry_big"] = int(bool(d["entry_big"]))
if "camera_pass" in d:
upd["camera_pass"] = int(bool(d["camera_pass"]))
if "vote_scans" in d: if "vote_scans" in d:
upd["vote_scans"] = clamp_int(d["vote_scans"], 0, config.MAX_VOTE_SCANS, "vote_scans") upd["vote_scans"] = clamp_int(d["vote_scans"], 0, config.MAX_VOTE_SCANS, "vote_scans")
if "focus_qid" in d: if "focus_qid" in d:
@@ -538,9 +424,6 @@ async def admin_patch(request: Request):
if any(k in upd for k in ("interval_ms", "scans_required", "require_code")) or upd.get("enrollment_open") == 0: if any(k in upd for k in ("interval_ms", "scans_required", "require_code")) or upd.get("enrollment_open") == 0:
# rules changed mid-way: half-done attempts start over # rules changed mid-way: half-done attempts start over
clear_attempts(pid) clear_attempts(pid)
if ("camera_pass" in upd or "code_style" in upd) and hub.screens.get(pid):
# switched off: the rotating qr on screen must turn back into the plain link now, not at the next tick
await hub.send_entry(db.poll(pid), hub.screens[pid], pass_slot())
hub.refresh(pid, voters=True) hub.refresh(pid, voters=True)
return JSONResponse({"ok": True}) return JSONResponse({"ok": True})
@@ -555,30 +438,9 @@ async def admin_rotate_screen_key(request: Request):
return JSONResponse({"screen_key": key}) return JSONResponse({"screen_key": key})
async def admin_share_key(request: Request):
pid = request.path_params["pid"]
require_admin(request, pid)
# POST makes a new link (the old one dies), DELETE turns the link off
key = new_key() if request.method == "POST" else None
db.update_poll(pid, share_key=key)
hub.refresh(pid)
return JSONResponse({"share_key": key})
async def shared_results(request: Request):
pid = request.path_params["pid"]
p = get_poll(pid)
auth = request.headers.get("authorization", "")
key = auth[7:] if auth.lower().startswith("bearer ") else ""
if not p["share_key"] or not hmac.compare_digest(key.encode(), p["share_key"].encode()):
return err("bad_share_key", 403)
qs = [q_public(q, True) for q in db.questions(pid) if q["state"] == "closed" and q["shared"]]
return JSONResponse({"title": p["title"], "questions": qs})
async def admin_add_question(request: Request): async def admin_add_question(request: Request):
pid = request.path_params["pid"] pid = request.path_params["pid"]
require_admin(request, pid) p = require_admin(request, pid)
d = await body(request) d = await body(request)
qid = db.add_question(pid, *parse_question(d)) qid = db.add_question(pid, *parse_question(d))
if d.get("open"): if d.get("open"):
@@ -606,47 +468,12 @@ async def admin_question_action(request: Request):
if st != "open": if st != "open":
return err("not_open") return err("not_open")
db.set_question(qid, state="closed") db.set_question(qid, state="closed")
elif action == "reopen":
# a late vote can still come in, but never once the room has seen the tally
if st != "closed":
return err("not_closed")
if q["shown"]:
return err("already_shown")
db.set_question(qid, state="open")
db.update_poll(pid, focus_qid=qid)
elif action in ("publish", "unpublish"): elif action in ("publish", "unpublish"):
if st != "closed": if st != "closed":
return err("not_closed") return err("not_closed")
db.set_question(qid, results_public=int(action == "publish")) db.set_question(qid, results_public=int(action == "publish"))
if action == "publish":
db.set_question(qid, shown=1)
if action == "publish": if action == "publish":
db.update_poll(pid, focus_qid=qid) db.update_poll(pid, focus_qid=qid)
elif action in ("share", "unshare"):
if st != "closed":
return err("not_closed")
db.set_question(qid, shared=int(action == "share"))
# people outside the room have seen the tally, same lock as publish
if action == "share":
db.set_question(qid, shown=1)
elif action == "extra":
if st == "draft":
return err("not_open")
d = await body(request)
n = len(json.loads(q["options"]))
counts = d.get("counts")
if not isinstance(counts, list) or len(counts) != n:
return err("bad_extra")
counts = [clamp_int(c, 0, 100000, "counts") for c in counts]
blank = clamp_int(d.get("blank", 0), 0, 100000, "blank") if q["allow_blank"] else 0
# single choice: one ballot per answer. multi: the count of ballots is given (at least the biggest answer)
if q["kind"] == "multi":
ballots = clamp_int(d.get("ballots", max(counts, default=0) + blank), 0, 100000, "ballots")
if ballots < max(counts, default=0) + blank or ballots > sum(counts) + blank:
return err("bad_extra")
else:
ballots = sum(counts) + blank
db.set_question(qid, extra=json.dumps({"counts": counts, "blank": blank, "ballots": ballots}))
elif action == "focus": elif action == "focus":
db.update_poll(pid, focus_qid=qid) db.update_poll(pid, focus_qid=qid)
elif action == "delete": elif action == "delete":
@@ -698,53 +525,22 @@ async def voter_me(request: Request):
"type": "state", "title": p["title"], "enrolled": False, "type": "state", "title": p["title"], "enrolled": False,
"enrollment_open": bool(p["enrollment_open"]), "scans_required": p["scans_required"], "enrollment_open": bool(p["enrollment_open"]), "scans_required": p["scans_required"],
"require_code": bool(p["require_code"]), "need_code": presence and bool(p["require_code"]), "require_code": bool(p["require_code"]), "need_code": presence and bool(p["require_code"]),
"code_style": p["code_style"], "camera_pass": pass_on(p),
"count": len(a.slots) if a else 0, "count": len(a.slots) if a else 0,
}) })
def _finish_enroll(pid, att_id, code=None, with_pass=False): def _finish_enroll(pid, att_id, code=None):
cred, e = db.enroll(pid, code) cred, e = db.enroll(pid, code)
if e: if e:
return None, e return None, e
attempts.pop((pid, att_id), None) attempts.pop((pid, att_id), None)
if with_pass:
grant_pass(pid, db.voter_by_cred(pid, cred)["id"])
resp = JSONResponse({"status": "enrolled"}) resp = JSONResponse({"status": "enrolled"})
set_cookie(resp, voter_cookie(pid), cred, 7 * 24 * 3600) set_cookie(resp, voter_cookie(pid), cred, 7 * 24 * 3600)
resp.delete_cookie(attempt_cookie(pid), path="/") resp.delete_cookie(attempt_cookie(pid), path="/")
# a trial has no admin: the first enrolled phone opens the sample question so the vote can be tried too hub.refresh(pid)
p = db.poll(pid)
if p["trial"] and not p["focus_qid"]:
q = next((q for q in db.questions(pid) if q["state"] == "draft"), None)
if q:
db.set_question(q["id"], state="open")
db.update_poll(pid, focus_qid=q["id"])
hub.refresh(pid, voters=True)
return resp, None return resp, None
def _attempt(request, pid):
"""this device's enrollment attempt, from its cookie, or a fresh one (then the cookie must be set)"""
if len(attempts) > 50000:
prune_attempts()
att_id = request.cookies.get(attempt_cookie(pid))
if att_id and (pid, att_id) in attempts:
return att_id, attempts[(pid, att_id)], None
att_id = new_key()
attempts[(pid, att_id)] = Attempt()
return att_id, attempts[(pid, att_id)], att_id
def _expire(a, p, now):
# scans must land in one short window, and a proven presence only waits so long for its paper code
if a.presence_ms:
if now - a.presence_ms > config.CODE_ENTRY_TTL_S * 1000:
a.slots.clear(); a.first_ms = 0; a.presence_ms = 0
elif a.first_ms and now - a.first_ms > p["scans_required"] * p["interval_ms"] + config.ATTEMPT_SLACK_MS:
a.slots.clear(); a.first_ms = 0
async def voter_scan(request: Request): async def voter_scan(request: Request):
pid = request.path_params["pid"] pid = request.path_params["pid"]
p = get_poll(pid) p = get_poll(pid)
@@ -753,14 +549,27 @@ async def voter_scan(request: Request):
return JSONResponse({"status": "enrolled"}) return JSONResponse({"status": "enrolled"})
if not p["enrollment_open"]: if not p["enrollment_open"]:
return JSONResponse({"status": "closed"}) return JSONResponse({"status": "closed"})
att_id, a, fresh_cookie = _attempt(request, pid) if len(attempts) > 50000:
prune_attempts()
att_id = request.cookies.get(attempt_cookie(pid))
fresh_cookie = None
if not att_id or (pid, att_id) not in attempts:
att_id = new_key()
fresh_cookie = att_id
attempts[(pid, att_id)] = Attempt()
a = attempts[(pid, att_id)]
now = now_ms() now = now_ms()
a.last_ms = now a.last_ms = now
required = p["scans_required"] required = p["scans_required"]
_expire(a, p, now) window = required * p["interval_ms"] + config.ATTEMPT_SLACK_MS
if a.presence_ms:
if now - a.presence_ms > config.CODE_ENTRY_TTL_S * 1000:
a.slots.clear(); a.first_ms = 0; a.presence_ms = 0
elif a.first_ms and now - a.first_ms > window:
a.slots.clear(); a.first_ms = 0
status = "progress" status = "progress"
slot = resolve_token(p, str(d.get("token", ""))[:64], config.TOKEN_GRACE_MS) slot = verify_token(p["secret"], pid, p["interval_ms"], str(d.get("token", ""))[:64], config.TOKEN_GRACE_MS)
accepted = False accepted = False
if slot is not None and not a.presence_ms and slot not in a.slots: if slot is not None and not a.presence_ms and slot not in a.slots:
if not a.first_ms: if not a.first_ms:
@@ -784,57 +593,6 @@ async def voter_scan(request: Request):
return resp return resp
async def camera_pass(request: Request):
"""the entry qr read by the camera app lands here. strict cookies may not come along on a navigation
from another app, so check the code now and hand the page a one-time claim it redeems with its cookies"""
pid = request.path_params["pid"].lower()
p = db.poll(pid)
if p and not pass_on(p):
return RedirectResponse(f"/v/{pid}", status_code=303)
late = pass_late(p, request.path_params["tok"]) if p else None
# 303 + the no-store every response gets: the camera app never reuses an old redirect
return RedirectResponse(f"/v/{pid}#" + (f"c={mint_claim(pid, late)}" if late is not None else "cam=expired"),
status_code=303)
async def voter_pass(request: Request):
"""one camera app scan = presence: enrolls this phone, or covers its votes for PASS_HOLD_MS.
takes the claim from camera_pass, or the code itself when the page's own camera read the qr"""
pid = request.path_params["pid"]
p = get_poll(pid)
d = await body(request)
if not pass_on(p):
return JSONResponse({"status": "off"})
now = now_ms()
if d.get("claim"):
c = claims.pop(str(d["claim"])[:64], None)
late = c[2] if c and c[0] == pid and now - c[1] <= config.PASS_CLAIM_TTL_MS else None
else:
late = pass_late(p, str(d.get("token", "")))
if late is None:
return JSONResponse({"status": "expired"})
v = current_voter(request, pid)
if v:
grant_pass(pid, v["id"])
return JSONResponse({"status": "pass", "hold_ms": config.PASS_HOLD_MS})
if not p["enrollment_open"]:
return JSONResponse({"status": "closed"})
# joining is where a forwarded link hurts most: the code must be read almost live
if late > config.PASS_ENROLL_GRACE_MS:
return JSONResponse({"status": "late"})
att_id, a, fresh_cookie = _attempt(request, pid)
a.last_ms = a.presence_ms = now
if p["require_code"]:
resp = JSONResponse({"status": "need_code"})
else:
resp, e = _finish_enroll(pid, att_id, with_pass=True)
if not resp:
return JSONResponse({"status": e})
if fresh_cookie and p["require_code"]:
set_cookie(resp, attempt_cookie(pid), fresh_cookie, 900)
return resp
async def voter_rescue(request: Request): async def voter_rescue(request: Request):
"""enrollment with a one-time rescue code, for phones whose camera can't scan""" """enrollment with a one-time rescue code, for phones whose camera can't scan"""
pid = request.path_params["pid"] pid = request.path_params["pid"]
@@ -853,7 +611,7 @@ async def voter_rescue(request: Request):
async def voter_code(request: Request): async def voter_code(request: Request):
pid = request.path_params["pid"] pid = request.path_params["pid"]
get_poll(pid) p = get_poll(pid)
d = await body(request) d = await body(request)
if current_voter(request, pid): if current_voter(request, pid):
return JSONResponse({"status": "enrolled"}) return JSONResponse({"status": "enrolled"})
@@ -896,21 +654,17 @@ async def voter_vote(request: Request):
if len(choices) > q["max_choices"]: if len(choices) > q["max_choices"]:
return err("too_many_choices") return err("too_many_choices")
p = db.poll(pid) p = db.poll(pid)
need = 0 if v["via_code"] or has_pass(pid, v["id"]) else p["vote_scans"] need = 0 if v["via_code"] else p["vote_scans"]
if need: if need:
# proof of presence at vote time: fresh distinct codes read off the projector. # proof of presence at vote time: fresh distinct codes read off the projector.
# checked then dropped, nothing about them is stored next to the ballot # checked then dropped, nothing about them is stored next to the ballot
tokens = d.get("presence") tokens = d.get("presence")
if not isinstance(tokens, list): if not isinstance(tokens, list):
return err("presence_required") return err("presence_required")
# a slow phone can take well over need * interval to see enough distinct codes, so the codes may span window = config.TOKEN_GRACE_MS + need * p["interval_ms"]
# the same slack as an enrollment, as long as one of them is fresh: the phone sees the screen right now slots = {verify_token(p["secret"], pid, p["interval_ms"], str(t)[:64], window) for t in tokens[:20]}
tokens = [str(t)[:64] for t in tokens[:20]]
window = config.ATTEMPT_SLACK_MS + need * p["interval_ms"]
slots = {resolve_token(p, t, window) for t in tokens}
slots.discard(None) slots.discard(None)
fresh = any(resolve_token(p, t, config.TOKEN_GRACE_MS) is not None for t in tokens) if len(slots) < need:
if len(slots) < need or not fresh:
return err("presence_required") return err("presence_required")
e = db.cast(pid, qid, v["id"], choices) e = db.cast(pid, qid, v["id"], choices)
if e: if e:
@@ -949,7 +703,6 @@ async def ws_screen(ws: WebSocket):
scheme = "https" if ws.url.scheme == "wss" or config.BEHIND_PROXY else "http" scheme = "https" if ws.url.scheme == "wss" or config.BEHIND_PROXY else "http"
origin = f"{scheme}://{public_host(ws)}" origin = f"{scheme}://{public_host(ws)}"
hub.screens.setdefault(pid, {})[ws] = origin hub.screens.setdefault(pid, {})[ws] = origin
await hub.send(ws, entry_qr(config.PUBLIC_URL or origin, p, pass_slot()))
await hub.send(ws, screen_state(pid)) await hub.send(ws, screen_state(pid))
hub.ensure_ticker(pid) hub.ensure_ticker(pid)
hub.refresh(pid) hub.refresh(pid)
@@ -1001,8 +754,7 @@ async def ws_voter(ws: WebSocket):
CSP = ("default-src 'self'; script-src 'self'; worker-src 'self' blob:; style-src 'self'; " CSP = ("default-src 'self'; script-src 'self'; worker-src 'self' blob:; style-src 'self'; "
"img-src 'self' data: blob:; media-src 'self' blob: mediastream:; connect-src 'self' ws: wss:; " "img-src 'self' data: blob:; media-src 'self' blob: mediastream:; connect-src 'self' ws: wss:; "
# same origin only: the duplicated-screen page shows the admin page in a side panel "frame-ancestors 'none'; base-uri 'none'; form-action 'self'; object-src 'none'")
"frame-ancestors 'self'; base-uri 'none'; form-action 'self'; object-src 'none'")
class SecurityHeaders: class SecurityHeaders:
@@ -1021,7 +773,7 @@ class SecurityHeaders:
(b"content-security-policy", CSP.encode()), (b"content-security-policy", CSP.encode()),
(b"referrer-policy", b"no-referrer"), (b"referrer-policy", b"no-referrer"),
(b"x-content-type-options", b"nosniff"), (b"x-content-type-options", b"nosniff"),
(b"x-frame-options", b"SAMEORIGIN"), (b"x-frame-options", b"DENY"),
(b"permissions-policy", b"camera=(self), microphone=(), geolocation=()"), (b"permissions-policy", b"camera=(self), microphone=(), geolocation=()"),
] ]
if not path.startswith("/static/vendor/"): if not path.startswith("/static/vendor/"):
@@ -1057,31 +809,21 @@ routes = [
Route("/", page("index.html")), Route("/", page("index.html")),
Route("/admin/{pid}", page("admin.html")), Route("/admin/{pid}", page("admin.html")),
Route("/screen/{pid}", page("screen.html")), Route("/screen/{pid}", page("screen.html")),
# duplicated screen: the projector view with the admin in a drawer, opened with the admin key
Route("/present/{pid}", page("screen.html")),
Route("/essai", page("essai.html")),
Route("/v/{pid}", page("vote.html")), Route("/v/{pid}", page("vote.html")),
Route("/r/{pid}", page("results.html")),
Route("/V/{pid}/{tok}", camera_pass),
Route("/V/{pid}", lambda r: RedirectResponse(f"/v/{r.path_params['pid'].lower()}", status_code=301)),
Route("/api/config", public_config, methods=["GET"]), Route("/api/config", public_config, methods=["GET"]),
Route("/api/polls", create_poll, methods=["POST"]), Route("/api/polls", create_poll, methods=["POST"]),
Route("/api/trial", create_trial, methods=["POST"]),
Route("/api/polls/{pid}", admin_get, methods=["GET"]), Route("/api/polls/{pid}", admin_get, methods=["GET"]),
Route("/api/polls/{pid}", admin_patch, methods=["PATCH"]), Route("/api/polls/{pid}", admin_patch, methods=["PATCH"]),
Route("/api/polls/{pid}/screen-key", admin_rotate_screen_key, methods=["POST"]), Route("/api/polls/{pid}/screen-key", admin_rotate_screen_key, methods=["POST"]),
Route("/api/polls/{pid}/share-key", admin_share_key, methods=["POST", "DELETE"]),
Route("/api/polls/{pid}/questions", admin_add_question, methods=["POST"]), Route("/api/polls/{pid}/questions", admin_add_question, methods=["POST"]),
Route("/api/polls/{pid}/questions/{qid:int}/{action}", admin_question_action, methods=["POST"]), Route("/api/polls/{pid}/questions/{qid:int}/{action}", admin_question_action, methods=["POST"]),
Route("/api/polls/{pid}/codes", admin_codes, methods=["GET", "POST"]), Route("/api/polls/{pid}/codes", admin_codes, methods=["GET", "POST"]),
Route("/api/polls/{pid}/export", admin_export, methods=["GET"]), Route("/api/polls/{pid}/export", admin_export, methods=["GET"]),
Route("/api/r/{pid}", shared_results, methods=["GET"]),
Route("/api/v/{pid}/me", voter_me, methods=["GET"]), Route("/api/v/{pid}/me", voter_me, methods=["GET"]),
Route("/api/v/{pid}/scan", voter_scan, methods=["POST"]), Route("/api/v/{pid}/scan", voter_scan, methods=["POST"]),
Route("/api/v/{pid}/code", voter_code, methods=["POST"]), Route("/api/v/{pid}/code", voter_code, methods=["POST"]),
Route("/api/v/{pid}/vote", voter_vote, methods=["POST"]), Route("/api/v/{pid}/vote", voter_vote, methods=["POST"]),
Route("/api/v/{pid}/rescue", voter_rescue, methods=["POST"]), Route("/api/v/{pid}/rescue", voter_rescue, methods=["POST"]),
Route("/api/v/{pid}/pass", voter_pass, methods=["POST"]),
WebSocketRoute("/ws/{pid}/screen", ws_screen), WebSocketRoute("/ws/{pid}/screen", ws_screen),
WebSocketRoute("/ws/{pid}/admin", ws_admin), WebSocketRoute("/ws/{pid}/admin", ws_admin),
WebSocketRoute("/ws/{pid}/voter", ws_voter), WebSocketRoute("/ws/{pid}/voter", ws_voter),
-14
View File
@@ -25,24 +25,10 @@ CODE_ENTRY_TTL_S = 180
# keepalive for websockets, proxies drop idle ones (cloudflare ~100s) # keepalive for websockets, proxies drop idle ones (cloudflare ~100s)
HEARTBEAT_S = float(os.environ.get("HEARTBEAT_S", "25")) HEARTBEAT_S = float(os.environ.get("HEARTBEAT_S", "25"))
# entry qr read by the phone's own camera app: one scan proves presence (browsers with the camera blocked).
# a new code every 3 s. once off the screen it still validates a vote for 12 s, an enrollment for 4 s only,
# and a scan covers votes for 10 s
PASS_ROTATE_MS = 3000
PASS_GRACE_MS = 12000
PASS_ENROLL_GRACE_MS = 4000
PASS_HOLD_MS = int(os.environ.get("PASS_HOLD_MS", "10000"))
# the redirect hands the page a one-time claim: slow page loads on a crowded network don't eat the window
PASS_CLAIM_TTL_MS = 20000
# codes needed to confirm each vote, 0 turns the check off # codes needed to confirm each vote, 0 turns the check off
DEFAULT_VOTE_SCANS = 3 DEFAULT_VOTE_SCANS = 3
MAX_VOTE_SCANS = 5 MAX_VOTE_SCANS = 5
# throwaway polls from /essai: deleted after this, and only so many alive at once
TRIAL_TTL_MS = 2 * 3600 * 1000
MAX_TRIALS = int(os.environ.get("MAX_TRIALS", "50"))
MIN_INTERVAL_MS = 300 MIN_INTERVAL_MS = 300
MAX_INTERVAL_MS = 5000 MAX_INTERVAL_MS = 5000
MIN_SCANS = 2 MIN_SCANS = 2
+6 -41
View File
@@ -20,7 +20,6 @@ CREATE TABLE IF NOT EXISTS polls(
expected INTEGER, expected INTEGER,
require_code INTEGER NOT NULL DEFAULT 0, require_code INTEGER NOT NULL DEFAULT 0,
vote_scans INTEGER NOT NULL DEFAULT 0, vote_scans INTEGER NOT NULL DEFAULT 0,
code_style TEXT NOT NULL DEFAULT 'qr',
focus_qid INTEGER, focus_qid INTEGER,
created_at INTEGER NOT NULL created_at INTEGER NOT NULL
); );
@@ -86,15 +85,6 @@ class DB:
("polls", "vote_scans", "INTEGER NOT NULL DEFAULT 0"), ("polls", "vote_scans", "INTEGER NOT NULL DEFAULT 0"),
("voters", "via_code", "INTEGER NOT NULL DEFAULT 0"), ("voters", "via_code", "INTEGER NOT NULL DEFAULT 0"),
("access_codes", "rescue", "INTEGER NOT NULL DEFAULT 0"), ("access_codes", "rescue", "INTEGER NOT NULL DEFAULT 0"),
("polls", "code_style", "TEXT NOT NULL DEFAULT 'qr'"),
("polls", "trial", "INTEGER NOT NULL DEFAULT 0"),
("questions", "shown", "INTEGER NOT NULL DEFAULT 0"),
("polls", "entry_big", "INTEGER NOT NULL DEFAULT 0"),
("questions", "extra", "TEXT"),
("polls", "camera_pass", "INTEGER NOT NULL DEFAULT 1"),
# read-only results link. kept in clear so the admin can copy it again, it only shows tallies
("polls", "share_key", "TEXT"),
("questions", "shared", "INTEGER NOT NULL DEFAULT 0"),
): ):
cols = {r[1] for r in self.c.execute(f"PRAGMA table_info({table})")} cols = {r[1] for r in self.c.execute(f"PRAGMA table_info({table})")}
if col not in cols: if col not in cols:
@@ -117,42 +107,25 @@ class DB:
return self.c.execute(sql, args).fetchall() return self.c.execute(sql, args).fetchall()
def create_poll(self, title, interval_ms, scans_required, require_code, expected, max_voters, vote_scans=0, def create_poll(self, title, interval_ms, scans_required, require_code, expected, max_voters, vote_scans=0):
code_style="qr", trial=False):
pid = new_id() pid = new_id()
while self.one("SELECT 1 FROM polls WHERE id=?", pid): while self.one("SELECT 1 FROM polls WHERE id=?", pid):
pid = new_id() pid = new_id()
admin_key, screen_key = new_key(), new_key() admin_key, screen_key = new_key(), new_key()
self.c.execute( self.c.execute(
"INSERT INTO polls(id,title,admin_hash,screen_hash,secret,interval_ms,scans_required," "INSERT INTO polls(id,title,admin_hash,screen_hash,secret,interval_ms,scans_required,"
"require_code,expected,max_voters,vote_scans,code_style,trial,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)", "require_code,expected,max_voters,vote_scans,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)",
(pid, title, sha(admin_key), sha(screen_key), secrets.token_bytes(32), interval_ms, (pid, title, sha(admin_key), sha(screen_key), secrets.token_bytes(32), interval_ms,
scans_required, int(require_code), expected, max_voters, vote_scans, code_style, int(trial), now_ms()), scans_required, int(require_code), expected, max_voters, vote_scans, now_ms()),
) )
return pid, admin_key, screen_key return pid, admin_key, screen_key
def purge_trials(self, max_age_ms):
old = [r["id"] for r in self.all("SELECT id FROM polls WHERE trial=1 AND created_at<?", now_ms() - max_age_ms)]
with self.tx() as c:
for pid in old:
qids = "SELECT id FROM questions WHERE poll_id=?"
c.execute(f"DELETE FROM ballots WHERE question_id IN ({qids})", (pid,))
c.execute(f"DELETE FROM participation WHERE question_id IN ({qids})", (pid,))
for table, col in (("questions", "poll_id"), ("voters", "poll_id"), ("access_codes", "poll_id"),
("polls", "id")):
c.execute(f"DELETE FROM {table} WHERE {col}=?", (pid,))
return old
def trial_count(self):
return self.one("SELECT COUNT(*) n FROM polls WHERE trial=1")["n"]
def poll(self, pid): def poll(self, pid):
return self.one("SELECT * FROM polls WHERE id=?", pid) return self.one("SELECT * FROM polls WHERE id=?", pid)
def update_poll(self, pid, **fields): def update_poll(self, pid, **fields):
allowed = {"title", "interval_ms", "scans_required", "enrollment_open", "max_voters", allowed = {"title", "interval_ms", "scans_required", "enrollment_open", "max_voters",
"expected", "require_code", "focus_qid", "vote_scans", "code_style", "entry_big", "camera_pass", "expected", "require_code", "focus_qid", "vote_scans"}
"share_key"}
fields = {k: v for k, v in fields.items() if k in allowed} fields = {k: v for k, v in fields.items() if k in allowed}
if not fields: if not fields:
return return
@@ -230,7 +203,7 @@ class DB:
return self.all("SELECT * FROM questions WHERE poll_id=? ORDER BY position", pid) return self.all("SELECT * FROM questions WHERE poll_id=? ORDER BY position", pid)
def set_question(self, qid, **fields): def set_question(self, qid, **fields):
allowed = {"state", "results_public", "shown", "extra", "shared"} allowed = {"state", "results_public"}
fields = {k: v for k, v in fields.items() if k in allowed} fields = {k: v for k, v in fields.items() if k in allowed}
sets = ",".join(f"{k}=?" for k in fields) sets = ",".join(f"{k}=?" for k in fields)
self.c.execute(f"UPDATE questions SET {sets} WHERE id=?", (*fields.values(), qid)) self.c.execute(f"UPDATE questions SET {sets} WHERE id=?", (*fields.values(), qid))
@@ -274,15 +247,7 @@ class DB:
for i in ch: for i in ch:
if 0 <= i < len(counts): if 0 <= i < len(counts):
counts[i] += 1 counts[i] += 1
return {"counts": counts, "blank": blank, "ballots": total, "extra": self.extra(q)} return {"counts": counts, "blank": blank, "ballots": total}
def extra(self, q):
"""votes added by hand (paper, show of hands), kept apart from the phone ballots"""
n = len(json.loads(q["options"]))
e = json.loads(q["extra"]) if q["extra"] else {}
counts = (list(e.get("counts") or []) + [0] * n)[:n]
blank = e.get("blank", 0)
return {"counts": counts, "blank": blank, "ballots": e.get("ballots", sum(counts) + blank)}
def ballots(self, qid): def ballots(self, qid):
# pk is random so this order is meaningless, which is the point # pk is random so this order is meaningless, which is the point
+2 -1
View File
@@ -1,4 +1,4 @@
"""ring code: a dark disc with the logo in the middle (anchors the geometry) plus rotating rings of dashes """ring code: a static qr in the middle (opens the page, anchors geometry) plus rotating rings of dashes
that carry the time token. layout and bit order must match static/js/ringcode.js exactly. that carry the time token. layout and bit order must match static/js/ringcode.js exactly.
payload = slot mod 2^16 (2 bytes) + first 4 bytes of the token hmac, reed-solomon(12, 6) over gf(256), payload = slot mod 2^16 (2 bytes) + first 4 bytes of the token hmac, reed-solomon(12, 6) over gf(256),
@@ -8,6 +8,7 @@ import hmac
SYNC = "010001100101001000111111" # 24 sectors, min distance 12 to any of its rotations SYNC = "010001100101001000111111" # 24 sectors, min distance 12 to any of its rotations
RING_SECTORS = (24, 28, 32, 36) # ring 0 is sync, 1..3 carry 96 data bits RING_SECTORS = (24, 28, 32, 36) # ring 0 is sync, 1..3 carry 96 data bits
NSYM = 6 # rs parity bytes, fixes up to 3 bad bytes NSYM = 6 # rs parity bytes, fixes up to 3 bad bytes
SLOT_BITS = 16
_EXP = [0] * 512 _EXP = [0] * 512
_LOG = [0] * 256 _LOG = [0] * 256
+15 -16
View File
@@ -29,31 +29,30 @@ def check_key(given: str | None, stored_hash: str) -> bool:
return hmac.compare_digest(sha(given), stored_hash) return hmac.compare_digest(sha(given), stored_hash)
def _mac(secret: bytes, poll_id: str, interval_ms: int, slot: int) -> str:
msg = f"{poll_id}:{interval_ms}:{slot}".encode()
# 72 bits is plenty for a code that lives ~3s, keeps the QR small
return base64.urlsafe_b64encode(hmac.new(secret, msg, hashlib.sha256).digest()[:9]).decode()
def current_slot(interval_ms: int, at_ms: int | None = None) -> int: def current_slot(interval_ms: int, at_ms: int | None = None) -> int:
return (at_ms if at_ms is not None else now_ms()) // interval_ms return (at_ms if at_ms is not None else now_ms()) // interval_ms
def _pass_mac(secret: bytes, poll_id: str, slot: int) -> str: def make_token(secret: bytes, poll_id: str, interval_ms: int, slot: int) -> str:
# 50 bits in qr alphanumeric charset (base32 upper), the code lives ~15 s and is checked online only return f"{slot}.{_mac(secret, poll_id, interval_ms, slot)}"
d = hmac.new(secret, f"pass:{poll_id}:{slot}".encode(), hashlib.sha256).digest()
return base64.b32encode(d[:7]).decode()[:10]
def make_pass(secret: bytes, poll_id: str, slot: int) -> str: def verify_token(secret: bytes, poll_id: str, interval_ms: int, token: str, grace_ms: int) -> int | None:
return f"{slot}-{_pass_mac(secret, poll_id, slot)}" """returns the slot if the token is authentic and fresh, else None"""
def verify_pass(secret: bytes, poll_id: str, token: str, rotate_ms: int, grace_ms: int) -> int | None:
"""camera app code from the entry qr: slot if authentic and shown less than rotate + grace ago"""
try: try:
slot_s, mac = token.upper().split("-", 1) slot_s, mac = token.split(".", 1)
slot = int(slot_s) slot = int(slot_s)
# compare_digest raises on non ascii str
if not hmac.compare_digest(mac.encode(), _pass_mac(secret, poll_id, slot).encode()):
return None
except (ValueError, AttributeError): except (ValueError, AttributeError):
return None return None
age = now_ms() - slot * rotate_ms if not hmac.compare_digest(mac, _mac(secret, poll_id, interval_ms, slot)):
if age < 0 or age > rotate_ms + grace_ms: return None
age = now_ms() - slot * interval_ms
if age < 0 or age > interval_ms + grace_ms:
return None return None
return slot return slot
+3 -64
View File
@@ -42,28 +42,11 @@
<section data-panel="enroll" class="no-print" hidden> <section data-panel="enroll" class="no-print" hidden>
<div class="card"> <div class="card">
<label for="s-code-style">Code projeté</label>
<select id="s-code-style">
<option value="ring">Cercle animé</option>
<option value="qr">QR classique</option>
</select>
<label for="s-camera">Scan avec l'appareil photo</label>
<select id="s-camera">
<option value="1">Autorisé</option>
<option value="0">Désactivé</option>
</select>
<label for="s-entry-big">QR d'entrée</label>
<select id="s-entry-big">
<option value="0">Dans le coin</option>
<option value="1">Grand, à côté du cercle</option>
</select>
<div class="row"> <div class="row">
<div> <div>
<label for="s-interval">Rotation du code</label> <label for="s-interval">Rotation du QR</label>
<select id="s-interval"> <select id="s-interval">
<option value="500">0,5 s</option> <option value="500">0,5 s</option>
<option value="700">0,7 s</option>
<option value="800">0,8 s</option>
<option value="1000">1 s</option> <option value="1000">1 s</option>
<option value="1500">1,5 s</option> <option value="1500">1,5 s</option>
<option value="2000">2 s</option> <option value="2000">2 s</option>
@@ -122,27 +105,12 @@
<button id="screen-rotate" class="small" type="button">Nouveau lien</button> <button id="screen-rotate" class="small" type="button">Nouveau lien</button>
</div> </div>
<div class="share-row"> <div class="share-row">
<div><b>Écran dupliqué</b><span class="muted">Projection et gestion sur le même écran</span></div> <div><b>Résultats</b><span class="muted">Bulletins anonymes et décomptes</span></div>
<a id="open-present" class="btn small" href="#" target="_blank" rel="noopener">Ouvrir</a> <button id="export" class="small" type="button">Exporter</button>
</div> </div>
<div class="share-row">
<div><b>Résultats</b><span class="muted">Exporter en texte ou JSON (anonyme)</span></div>
<div class="code-actions">
<button id="export-text" class="small" type="button">Texte</button>
<button id="export" class="small" type="button">JSON</button>
</div>
</div>
</div>
<div class="card share-list" id="share-card">
<div class="share-row">
<div><b>Lien des résultats</b><span class="muted" id="share-summary"></span></div>
<div class="code-actions" id="share-actions"></div>
</div>
<div id="share-qs"></div>
</div> </div>
</section> </section>
<section id="codes-sheet" class="card" hidden> <section id="codes-sheet" class="card" hidden>
<div class="no-print actions"><button id="codes-close" class="small" type="button">Fermer</button><button id="codes-do-print" class="small primary" type="button">Imprimer</button></div> <div class="no-print actions"><button id="codes-close" class="small" type="button">Fermer</button><button id="codes-do-print" class="small primary" type="button">Imprimer</button></div>
<h2 id="codes-title"></h2> <h2 id="codes-title"></h2>
@@ -151,35 +119,6 @@
</div> </div>
</main> </main>
<dialog id="extra-dlg">
<form method="dialog" id="extra-form">
<h2>Votes en plus</h2>
<p class="muted" id="extra-q"></p>
<div id="extra-fields"></div>
<p class="hint">Bulletins papier, vote à main levée… Ils s'ajoutent aux votes par téléphone et s'affichent en orange hachuré.</p>
<div class="actions">
<button value="cancel" type="submit">Annuler</button>
<span class="spacer"></span>
<button value="ok" class="primary" type="submit">Enregistrer</button>
</div>
</form>
</dialog>
<dialog id="export-dlg">
<form method="dialog">
<h2>Exporter les résultats</h2>
<select id="ex-scope" aria-label="Questions"></select>
<div class="templates" id="ex-formats" role="radiogroup" aria-label="Modèle"></div>
<pre id="ex-preview" tabindex="0"></pre>
<div class="actions">
<button value="cancel" type="submit">Fermer</button>
<span class="spacer"></span>
<button id="ex-download" type="button">Télécharger</button>
<button id="ex-copy" class="primary" type="button">Copier</button>
</div>
</form>
</dialog>
<dialog id="composer"> <dialog id="composer">
<form method="dialog" id="q-form"> <form method="dialog" id="q-form">
<h2>Nouvelle question</h2> <h2>Nouvelle question</h2>
+6 -27
View File
@@ -54,36 +54,15 @@
.share-row > div:first-child { display: grid; } .share-row > div:first-child { display: grid; }
.share-row .muted { font-size: .85rem; } .share-row .muted { font-size: .85rem; }
#composer, #extra-dlg, #export-dlg { border: none; border-radius: 24px; padding: 24px; width: min(94vw, 560px); background: var(--surface); color: var(--ink); } #composer { border: none; border-radius: 24px; padding: 24px; width: min(94vw, 560px); background: var(--surface); color: var(--ink); }
#composer::backdrop, #extra-dlg::backdrop, #export-dlg::backdrop { background: rgba(28, 32, 54, .45); backdrop-filter: blur(2px); } #composer::backdrop { background: rgba(28, 32, 54, .45); backdrop-filter: blur(2px); }
#composer[open], #extra-dlg[open], #export-dlg[open] { animation: rise .2s ease-out; } #composer[open] { animation: rise .2s ease-out; }
#composer h2, #extra-dlg h2, #export-dlg h2 { font-size: 1.3rem; } #composer h2 { font-size: 1.3rem; }
.spacer { flex: 1; } .spacer { flex: 1; }
@media (max-width: 560px) { @media (max-width: 560px) {
.summary-row > * { flex: 1 1 auto; } .summary-row > * { flex: 1 1 auto; }
#composer .actions button, #extra-dlg .actions button, #export-dlg .actions button { flex: 1 1 100%; } #composer .actions button { flex: 1 1 100%; }
#composer .spacer, #extra-dlg .spacer, #export-dlg .spacer { display: none; } #composer .spacer { display: none; }
} }
#q-opts { min-height: 132px; } #q-opts { min-height: 132px; }
.extra-row { margin: 8px 0; display: grid; grid-template-columns: 1fr 110px; gap: 12px; align-items: center; font-weight: 600; }
.extra-row input { text-align: right; }
#export-dlg { width: min(94vw, 720px); }
#ex-scope { margin-bottom: 12px; }
#ex-scope[hidden] { display: none; }
#ex-formats button[aria-checked="true"] { background: var(--mark); border-color: var(--mark); color: var(--ink); }
#ex-preview {
margin: 12px 0 0; padding: 14px 16px; max-height: 50vh; overflow: auto; background: var(--bg); border-radius: var(--r-field);
font: .82rem/1.5 ui-monospace, "SF Mono", Menlo, Consolas, monospace; white-space: pre; tab-size: 4;
}
#ex-preview.empty { white-space: normal; color: var(--ink-3); font-family: var(--sans); text-align: center; padding: 32px 16px; }
#share-qs { border-top: 1.5px solid var(--bg); padding: 6px 0 10px; }
#share-qs:empty { display: none; }
.share-q { display: flex; gap: 10px; align-items: flex-start; padding: 8px 0; font-weight: 500; cursor: pointer; }
.share-q input { margin-top: 3px; flex: none; }
.share-none { margin: 8px 0; font-size: .85rem; }
.q .copy-btn { margin-left: auto; padding: 7px 9px; border-radius: 10px; border: 1.5px solid var(--line); color: var(--ink-2); }
+3 -35
View File
@@ -116,11 +116,6 @@ button:disabled { opacity: .35; cursor: not-allowed; transform: none; }
.bar-label { overflow-wrap: anywhere; } .bar-label { overflow-wrap: anywhere; }
.bar-track { height: 12px; background: var(--bg); border-radius: 99px; overflow: hidden; } .bar-track { height: 12px; background: var(--bg); border-radius: 99px; overflow: hidden; }
.bar-fill { height: 100%; background: var(--ink-3); border-radius: 99px; transition: width .6s cubic-bezier(.2, .8, .2, 1); } .bar-fill { height: 100%; background: var(--ink-3); border-radius: 99px; transition: width .6s cubic-bezier(.2, .8, .2, 1); }
/* one bar = phone ballots then hand-added votes, hatched orange */
.bar-stack { height: 100%; display: flex; border-radius: 99px; overflow: hidden; transition: width .6s cubic-bezier(.2, .8, .2, 1); }
.bar-stack > div { flex: 1 1 0; border-radius: 0; height: 100%; }
.bar-extra, .progress > .p-extra { background: repeating-linear-gradient(-45deg, #f08a24 0 5px, #f9c58f 5px 10px); }
.extra-note { color: #b85e0b; font-weight: 600; }
.bar-row.lead .bar-fill { background: var(--mark); } .bar-row.lead .bar-fill { background: var(--mark); }
.bar-row.lead .bar-label { font-weight: 700; } .bar-row.lead .bar-label { font-weight: 700; }
.bar-num { font: 700 1rem var(--round); min-width: 80px; text-align: right; } .bar-num { font: 700 1rem var(--round); min-width: 80px; text-align: right; }
@@ -129,21 +124,11 @@ button:disabled { opacity: .35; cursor: not-allowed; transform: none; }
.progress { height: 8px; background: var(--bg); border-radius: 99px; overflow: hidden; margin-top: 6px; } .progress { height: 8px; background: var(--bg); border-radius: 99px; overflow: hidden; margin-top: 6px; }
.progress > div { height: 100%; background: var(--ink); border-radius: 99px; transition: width .3s; } .progress > div { height: 100%; background: var(--ink); border-radius: 99px; transition: width .3s; }
.progress { display: flex; }
.progress > .p-extra { border-radius: 0 99px 99px 0; }
.progress > div:not(:last-child) { border-radius: 99px 0 0 99px; }
.ring { display: block; overflow: visible; } .ring { display: block; overflow: visible; }
.ring .seg, .ring .fill { fill: none; stroke-linecap: round; } .ring .seg { fill: none; stroke: var(--line); stroke-linecap: round; transition: stroke .3s; }
.ring .seg { stroke: var(--line); } .ring .seg.on { stroke: var(--ink); }
/* empty fill sits one length ahead (offset set in js) and hidden, so the round cap dot doesn't show */ .ring .seg.last { stroke: var(--mark); }
.ring .fill {
stroke: var(--ink); opacity: 0;
transition: stroke-dashoffset .5s cubic-bezier(.3, .7, .2, 1), opacity .12s, stroke .22s;
}
.ring .fill.on { opacity: 1; }
.ring .fill.last { stroke: var(--mark); }
@media (prefers-reduced-motion: reduce) { .ring .fill { transition: opacity .2s, stroke .2s; } }
.ring text { font: 700 20px var(--round); fill: var(--ink); } .ring text { font: 700 20px var(--round); fill: var(--ink); }
.codes-print { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 8px; margin-top: 12px; } .codes-print { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 8px; margin-top: 12px; }
@@ -169,20 +154,3 @@ button:disabled { opacity: .35; cursor: not-allowed; transform: none; }
.card { padding: 0; } .card { padding: 0; }
.code-cell { break-inside: avoid; } .code-cell { break-inside: avoid; }
} }
.center { text-align: center; }
/* created poll: the two windows it opens */
.duo { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin: 2px 0 6px; }
.duo.stack { grid-template-columns: 1fr; margin-top: 12px; }
.duo .pane { display: grid; gap: 10px; background: var(--bg); border-radius: var(--r-field); padding: 14px; }
.duo .pane-head { display: flex; align-items: center; gap: 12px; }
.duo .pane .linkbox input { background: var(--surface); }
.duo p { margin: 0; display: grid; gap: 1px; min-width: 0; }
.duo b { font: 700 .92rem var(--round); }
.duo span { font-size: .78rem; color: var(--ink-3); }
details.advanced { margin-top: 14px; }
details.advanced summary { font-size: .82rem; color: var(--ink-3); cursor: pointer; width: fit-content; padding: 4px 0; }
details.advanced summary:hover { color: var(--ink-2); }
details.advanced[open] summary { color: var(--ink-2); }
.mode-title { font-size: 1.05rem; margin: 22px 0 2px; }
.mode-title + .hint { margin: 0 0 8px; }
+9 -127
View File
@@ -8,51 +8,14 @@ body.screen {
.s-tools { display: flex; gap: 10px; align-items: center; } .s-tools { display: flex; gap: 10px; align-items: center; }
:fullscreen .s-tools button { display: none; } :fullscreen .s-tools button { display: none; }
/* definite tracks: percentage heights below resolve the same in every engine */ .s-main { min-height: 0; display: grid; padding: 1vh 4vw; }
.s-main { min-height: 0; display: grid; grid-template-rows: minmax(0, 1fr); padding: 1vh 4vw; }
.s-enroll { display: grid; grid-template-columns: auto 1fr; grid-template-rows: minmax(0, 1fr); gap: 5vw; align-items: center; min-height: 0; height: 100%; } .s-enroll { display: grid; grid-template-columns: auto 1fr; gap: 5vw; align-items: center; min-height: 0; }
.qr-wrap { .qr-wrap {
height: 100%; max-height: 74vh; aspect-ratio: 1; display: grid; grid-template-rows: 1fr auto; height: 100%; max-height: 74vh; aspect-ratio: 1; display: grid; grid-template-rows: 1fr auto;
background: #fff; border-radius: 28px; padding: 2vh; gap: 1.4vh; background: #fff; border-radius: 28px; padding: 2vh; gap: 1.4vh;
} }
.qr-wrap.ring { background: transparent; padding: 0; } #qr { width: 100%; height: 100%; min-height: 0; image-rendering: pixelated; image-rendering: crisp-edges; object-fit: contain; }
/* the entry qr docks in the bottom right corner, outside the layout: the ring never shrinks for it.
the column under it keeps that much room free (body.has-entry) */
body.screen { --dock-qr: clamp(150px, min(34vh, 24vw), 480px); --dock-h: calc(var(--dock-qr) + 2.4vh + 2.9rem); }
/* with a question on screen the qr leaves the question some height */
body.split-on { --dock-qr: clamp(130px, min(26vh, 19vw), 380px); }
.entry {
position: fixed; right: 1.2vw; bottom: 1.5vh; z-index: 5; display: grid; justify-items: center; gap: .8vh;
background: var(--surface); border-radius: 18px; padding: 1.2vh; text-align: center; max-width: 40vw;
}
.entry canvas { width: var(--dock-qr); height: auto; aspect-ratio: 1; image-rendering: pixelated; }
.entry div { display: grid; gap: .2vh; font-size: clamp(.7rem, .95vw, 1rem); color: var(--ink-2); overflow-wrap: break-word; }
.entry b { color: var(--ink); font-weight: 700; }
body.has-entry .s-main:not(.split) .s-steps, body.has-entry .s-main.split #focus { padding-bottom: var(--dock-h); }
/* big mode: the entry qr takes the right column beside the ring, the steps give it the room.
translate, not transform: the entrance animation owns transform */
body.entry-big { --dock-qr: clamp(180px, min(58vh, 34vw), 640px); }
body.entry-big .entry { top: 50%; bottom: auto; right: max(4vw, calc((50vw - var(--dock-qr)) / 2 - 2vw)); translate: 0 -46%; padding: 2vh; gap: 1.2vh; }
body.entry-big .entry div { font-size: clamp(.9rem, 1.4vw, 1.6rem); }
body.entry-big .s-main:not(.split) .s-steps { visibility: hidden; }
body.entry-q-on { --dock-qr: clamp(160px, min(52vh, 32vw), 580px); }
/* width 0 + min-width 100%: a long question wraps to the qr's width instead of widening the block */
.entry-q { display: grid; gap: .6vh; padding-bottom: 1vh; margin-bottom: .4vh; border-bottom: 2px solid var(--bg); width: 0; min-width: 100%; }
.entry-q > b { font: 700 clamp(1rem, 1.7vw, 2rem) var(--round); color: var(--ink); line-height: 1.15; }
.entry-q > span { font: 600 clamp(.85rem, 1.2vw, 1.4rem) var(--round); color: var(--ink-2); }
/* open vote above the big qr: its options and the turnout bar, smaller than in the question block */
body.entry-q-on.entry-opts-on { --dock-qr: clamp(150px, min(48vh, 30vw), 540px); }
.entry-opts { list-style: none; padding: 0; margin: .2vh 0 0; display: flex; flex-wrap: wrap; justify-content: center; gap: .6vh .5vw; }
.entry-opts li { font: 600 clamp(.8rem, 1.15vw, 1.35rem) var(--round); background: var(--bg); border-radius: 12px; padding: .6vh .8vw; }
/* .entry div is a grid: the count reads on one line, the bar stays a flex row */
.entry-q .turnout { display: block; font: 600 clamp(.8rem, 1.1vw, 1.3rem) var(--round); color: var(--ink-2); }
.entry-q .turnout .progress { display: flex; }
.entry-q .turnout b { color: var(--ink); font-size: 1.35em; }
.entry-q .turnout .progress { height: 10px; margin-top: .8vh; }
/* the ring loop resizes the canvas bitmap every frame: its intrinsic size must not feed the layout,
or safari widens the column, which grows the bitmap, which widens the column... */
#qr { width: 100%; height: 100%; min-width: 0; min-height: 0; contain: size; image-rendering: pixelated; image-rendering: crisp-edges; object-fit: contain; }
.tick { height: 6px; background: var(--bg); border-radius: 99px; overflow: hidden; margin: 0 1vh; } .tick { height: 6px; background: var(--bg); border-radius: 99px; overflow: hidden; margin: 0 1vh; }
#tick-bar { height: 100%; width: 0; background: var(--mark); border-radius: 99px; } #tick-bar { height: 100%; width: 0; background: var(--mark); border-radius: 99px; }
.s-steps h2 { font-size: clamp(2rem, 4.6vw, 5rem); letter-spacing: -.03em; margin-bottom: .5em; } .s-steps h2 { font-size: clamp(2rem, 4.6vw, 5rem); letter-spacing: -.03em; margin-bottom: .5em; }
@@ -67,24 +30,14 @@ body.entry-q-on.entry-opts-on { --dock-qr: clamp(150px, min(48vh, 30vw), 540px);
font-weight: 700; font-size: .8em; font-weight: 700; font-size: .8em;
} }
/* a question on screen while the ring is up (vote with presence scans, late enrollment). the back rows read /* enrollment + a question at the same time: qr shrinks to the side */
the ring, so it keeps the wider column and as much height as possible */ .s-main.split { grid-template-columns: minmax(0, 1fr) minmax(0, 1.3fr); gap: 5vw; }
.s-main.split { grid-template-columns: minmax(0, 1.25fr) minmax(0, 1fr); gap: 4vw; } .s-main.split .s-enroll { grid-template-columns: 1fr; justify-items: center; gap: 3vh; }
.s-main.split .s-enroll { grid-template-columns: minmax(0, 1fr); justify-items: center; gap: 3vh; } .s-main.split .qr-wrap { max-height: 52vh; }
.s-main.split .s-enroll { grid-template-rows: minmax(0, 1fr) auto; gap: 1.5vh; height: 100%; } .s-main.split .s-steps h2 { font-size: clamp(1.4rem, 2.4vw, 2.6rem); }
.s-main.split .qr-wrap { height: 100%; width: auto; max-width: 100%; max-height: none; }
.s-main.split #qr-steps { display: none; }
.s-main.split .s-steps { text-align: center; }
.s-main.split .s-steps h2 { font-size: clamp(1.2rem, 2.1vw, 2.4rem); margin: 0; }
/* the question side scales with height too, so it still fits above the docked qr on short screens */
.s-main.split .s-focus .q-text { font-size: clamp(1.3rem, min(3.2vw, 6.5vh), 3.6rem); margin-bottom: 2.5vh; }
.s-main.split .s-focus .opts { gap: 1vh; margin-bottom: 2.5vh; }
.s-main.split .s-focus .opts li { font-size: clamp(.95rem, min(1.8vw, 3.6vh), 2rem); padding: 1.1vh 1.5vw; }
.s-main.split .s-focus .turnout { font-size: clamp(.9rem, min(1.5vw, 3vh), 1.7rem); }
.s-main.split .s-focus .results .bar-row { font-size: clamp(.95rem, min(1.8vw, 3.6vh), 2rem); margin: 1.2vh 0; }
.s-main.split .s-steps li { font-size: clamp(1rem, 1.5vw, 1.6rem); } .s-main.split .s-steps li { font-size: clamp(1rem, 1.5vw, 1.6rem); }
.s-focus { align-self: center; align-self: safe center; max-width: 1400px; width: 100%; margin: 0 auto; } .s-focus { align-self: center; max-width: 1400px; width: 100%; margin: 0 auto; }
.s-focus .q-text { font-size: clamp(1.8rem, 3.8vw, 4rem); letter-spacing: -.025em; line-height: 1.1; margin-bottom: 4vh; } .s-focus .q-text { font-size: clamp(1.8rem, 3.8vw, 4rem); letter-spacing: -.025em; line-height: 1.1; margin-bottom: 4vh; }
.s-focus .opts { list-style: none; padding: 0; margin: 0 0 4vh; display: grid; gap: 1.4vh; } .s-focus .opts { list-style: none; padding: 0; margin: 0 0 4vh; display: grid; gap: 1.4vh; }
.s-focus .opts li { font: 600 clamp(1.1rem, 2.2vw, 2.3rem) var(--round); background: var(--surface); border-radius: 20px; padding: 1.6vh 2vw; } .s-focus .opts li { font: 600 clamp(1.1rem, 2.2vw, 2.3rem) var(--round); background: var(--surface); border-radius: 20px; padding: 1.6vh 2vw; }
@@ -110,75 +63,4 @@ body.entry-q-on.entry-opts-on { --dock-qr: clamp(150px, min(48vh, 30vw), 540px);
@media (max-aspect-ratio: 1/1) { @media (max-aspect-ratio: 1/1) {
.s-enroll, .s-main.split { grid-template-columns: 1fr; } .s-enroll, .s-main.split { grid-template-columns: 1fr; }
.qr-wrap { max-height: 50vh; justify-self: center; } .qr-wrap { max-height: 50vh; justify-self: center; }
/* upright screen: the ring takes what the text leaves, the docked entry qr sits right of the steps */
body.screen { --dock-qr: clamp(120px, min(21vh, 34vw), 340px); }
.s-main:not(.split) .s-enroll { grid-template-rows: minmax(0, 1fr) auto; gap: 3vh; height: 100%; }
.s-main:not(.split) .qr-wrap { height: 100%; width: auto; max-width: 100%; max-height: none; }
body.has-entry .s-main:not(.split) .s-steps { padding-bottom: 0; padding-right: calc(var(--dock-qr) + 6vw); }
/* no room beside the ring on an upright screen: the big qr stays a (bigger) corner one */
body.entry-big { --dock-qr: clamp(140px, min(26vh, 40vw), 400px); }
body.entry-big .entry { top: auto; bottom: 1.5vh; right: 1.2vw; translate: none; }
body.entry-big .s-main:not(.split) .s-steps { visibility: visible; }
.entry-q { display: none; }
/* upright + question: ring and title share one row above the question */
.s-main.split .s-enroll { grid-template-columns: minmax(0, 1fr) auto; grid-template-rows: none; height: auto; align-items: center; justify-items: stretch; }
.s-main.split .qr-wrap { height: auto; width: 100%; max-height: 38vh; justify-self: center; }
.s-main.split .s-steps { display: grid; grid-template-columns: auto; justify-items: center; row-gap: 1vh; text-align: center; max-width: 42vw; }
} }
.qr-wrap.ring .tick { display: none; }
/* light motion: blocks rise in, fade out, the question lands piece by piece, result bars grow */
@keyframes s-in { from { opacity: 0; transform: translateY(14px); } to { opacity: 1; transform: none; } }
@keyframes s-out { to { opacity: 0; transform: translateY(-8px); } }
@keyframes s-grow { from { transform: scaleX(0); } }
@keyframes s-bump { 40% { transform: scale(1.18); } }
.s-main:not(.split) > section { grid-area: 1 / 1; }
.s-main > section:not([hidden]), .entry:not([hidden]) { animation: s-in .5s cubic-bezier(.2, .7, .2, 1) both; }
.s-main > section.leaving, .entry.leaving { animation: s-out .22s ease both; }
#focus.enter .q-text { animation: s-in .5s cubic-bezier(.2, .7, .2, 1) both; }
#focus.enter .opts li, #focus.enter .bar-row { animation: s-in .45s cubic-bezier(.2, .7, .2, 1) both; }
#focus.enter :is(.opts li, .bar-row):nth-child(1) { animation-delay: .08s; }
#focus.enter :is(.opts li, .bar-row):nth-child(2) { animation-delay: .14s; }
#focus.enter :is(.opts li, .bar-row):nth-child(3) { animation-delay: .2s; }
#focus.enter :is(.opts li, .bar-row):nth-child(4) { animation-delay: .26s; }
#focus.enter :is(.opts li, .bar-row):nth-child(n+5) { animation-delay: .32s; }
#focus.enter .turnout, #focus.enter .results-foot, #focus.enter .status { animation: s-in .45s .3s cubic-bezier(.2, .7, .2, 1) both; }
#focus.enter .bar-stack { transform-origin: left; animation: s-grow .9s .25s cubic-bezier(.2, .7, .2, 1) both; }
.turnout .progress > div { transition: width .5s cubic-bezier(.2, .7, .2, 1); }
#voters { display: inline-block; }
#voters.bump { animation: s-bump .35s ease; }
@media (prefers-reduced-motion: reduce) {
.s-main > section, .entry, #focus.enter *, #voters.bump { animation: none !important; }
.turnout .progress > div { transition: none; }
}
/* duplicated screen: the admin slides in over the projection, the room sees it while it's open */
.ctl {
position: fixed; top: 0; right: 0; bottom: 0; z-index: 30; width: min(480px, 94vw); display: grid; grid-template-rows: auto 1fr;
background: var(--bg); box-shadow: -12px 0 40px rgba(28, 32, 54, .18); translate: 105% 0; transition: translate .35s cubic-bezier(.2, .7, .2, 1);
}
.ctl.open { translate: 0 0; }
.ctl-head { display: flex; align-items: center; justify-content: space-between; padding: 12px 16px; font: 700 1rem var(--round); }
.ctl iframe { width: 100%; height: 100%; border: 0; background: var(--bg); }
/* the manage button stays reachable in full screen, faint until hovered */
:fullscreen .s-tools .ctl-btn { display: inline-flex; opacity: .3; }
:fullscreen .s-tools .ctl-btn:hover, :fullscreen .s-tools .ctl-btn:focus-visible { opacity: 1; }
@media (prefers-reduced-motion: reduce) { .ctl { transition: none; } }
/* drawer open: the projection keeps the space on its left. --room is that width */
body.screen { --ctl-w: min(480px, 94vw); }
body.ctl-open { --room: calc(100vw - var(--ctl-w)); }
body.ctl-open :is(.s-head, .s-main, .s-foot) { margin-right: var(--ctl-w); }
body.ctl-open .entry { right: calc(var(--ctl-w) + 1.2vw); }
/* big qr: ring and qr share the room, the qr right against the ring */
body.ctl-open.entry-big { --dock-qr: clamp(140px, min(46vh, calc(var(--room) * .34)), 520px); }
body.ctl-open.entry-big .s-main:not(.split) .qr-wrap { max-height: min(74vh, calc(var(--room) * .48)); }
body.ctl-open.entry-big .s-main:not(.split) .s-enroll { gap: 2vw; }
body.ctl-open.entry-big .entry { right: auto; left: calc(4vw + min(74vh, var(--room) * .48) + 2vw); }
body.ctl-open.split-on { --dock-qr: clamp(100px, min(22vh, calc(var(--room) * .2)), 260px); }
body.ctl-open .s-main.split .s-focus .q-text { font-size: clamp(1.1rem, min(calc(var(--room) * .04), 6vh), 3rem); }
body.ctl-open .s-main.split .s-focus .opts li { font-size: clamp(.9rem, min(calc(var(--room) * .024), 3.4vh), 1.8rem); }
/* narrow room: the ring follows its column's width, not the row's height */
body.ctl-open .s-main.split .qr-wrap { width: 100%; height: auto; max-height: 100%; align-self: center; }
/* grid items won't shrink below their content by default: let the ring's column be as narrow as the room */
.s-main > section { min-width: 0; }
-46
View File
@@ -50,49 +50,3 @@ dialog[open] { animation: rise .2s ease-out; }
#confirm-choices { list-style: none; padding: 0; margin: 0 0 8px; } #confirm-choices { list-style: none; padding: 0; margin: 0 0 8px; }
#confirm-choices li { font: 700 1.2rem var(--round); background: var(--mark); border-radius: 12px; padding: 10px 14px; margin: 6px 0; } #confirm-choices li { font: 700 1.2rem var(--round); background: var(--mark); border-radius: 12px; padding: 10px 14px; margin: 6px 0; }
dialog .actions button { flex: 1; } dialog .actions button { flex: 1; }
/* confirmation after enrolling or voting: the projector's mark, its check drawing in */
.celebrate {
position: fixed; inset: 0; z-index: 50; display: grid; place-content: center; justify-items: center; gap: 18px;
background: color-mix(in srgb, var(--bg) 92%, transparent); color: var(--ink);
animation: cel-in .3s ease both;
}
.celebrate svg { width: 132px; height: 132px; animation: cel-pop .5s cubic-bezier(.2, .9, .3, 1.25) both; }
.celebrate .tick { stroke-dasharray: 1; stroke-dashoffset: 1; animation: cel-tick .45s .25s cubic-bezier(.3, .7, .2, 1) forwards; }
.celebrate p { margin: 0; font: 700 1.3rem var(--round); animation: cel-in .4s .35s ease both; }
.celebrate small { margin-top: -10px; font: 600 .95rem var(--round); color: var(--ink-2); animation: cel-in .4s .45s ease both; }
.celebrate.out { animation: cel-out .4s ease forwards; }
@keyframes cel-in { from { opacity: 0; } }
@keyframes cel-out { to { opacity: 0; } }
@keyframes cel-pop { from { transform: scale(.6) rotate(-40deg); opacity: 0; } }
@keyframes cel-tick { to { stroke-dashoffset: 0; } }
.celebrate.verifying svg { animation: cel-spin 1s linear infinite; }
.celebrate.verifying p { animation-delay: 0s; }
@keyframes cel-spin { to { transform: rotate(360deg); } }
@media (prefers-reduced-motion: reduce) {
.celebrate, .celebrate svg, .celebrate p, .celebrate small, .celebrate.verifying svg { animation: none; }
.celebrate .tick { animation: none; stroke-dashoffset: 0; }
}
/* next camera: some phones hand over the selfie lens or the ultra wide */
.cam-switch {
position: absolute; right: 10px; bottom: 10px; width: 44px; height: 44px; padding: 0; border-radius: 50%;
display: grid; place-items: center; border: 0; color: #fff; background: rgba(20, 22, 36, .55);
-webkit-backdrop-filter: blur(6px); backdrop-filter: blur(6px);
}
.cam-switch:hover, .cam-zoom:hover { border: 0; background: rgba(20, 22, 36, .75); }
.cam-zoom {
position: absolute; left: 10px; bottom: 10px; min-width: 44px; height: 44px; padding: 0 12px; border-radius: 22px;
border: 0; color: #fff; background: rgba(20, 22, 36, .55); font: 700 .95rem var(--round);
-webkit-backdrop-filter: blur(6px); backdrop-filter: blur(6px);
}
/* the phone's own camera app reads the projector qr when the browser can't use the camera */
.cam-alt { display: flex; align-items: center; justify-content: center; gap: 8px; margin: 0 0 12px; font-size: .9rem; color: var(--ink-2); text-align: left; }
.cam-alt .icon { flex: none; }
.cam-alt.solo { flex-direction: column; gap: 12px; margin: 4px 0 18px; color: var(--ink); }
.cam-alt.solo .icon { width: 64px; height: 64px; padding: 14px; border-radius: 50%; background: var(--mark); stroke-width: 1.8; }
.cam-alt.solo b { font: 700 1.25rem/1.25 var(--round); text-align: center; }
.cam-alt.solo ol { list-style: none; counter-reset: st; padding: 0; margin: 0; display: grid; gap: 10px; font: 600 1rem/1.35 var(--round); }
.cam-alt.solo li { counter-increment: st; display: grid; grid-template-columns: 28px 1fr; gap: 10px; align-items: start; }
.cam-alt.solo li::before { content: counter(st); display: grid; place-items: center; width: 28px; height: 28px; border-radius: 50%; background: var(--ink); color: var(--surface); font-weight: 700; font-size: .9rem; }
-23
View File
@@ -1,23 +0,0 @@
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>RotatyVote · Essai</title>
<link rel="icon" href="/static/img/mark.svg" type="image/svg+xml">
<link rel="stylesheet" href="/static/css/app.css">
<script type="module" src="/static/js/essai.js"></script>
</head>
<body>
<main class="wrap narrow">
<div class="topbar"><a class="brand" href="/"><img src="/static/img/mark.svg" alt=""><span>rotaty<b>vote</b></span></a></div>
<section class="card">
<h1>Tester l'écran</h1>
<p>Ouvrez cette page sur l'ordinateur relié au projecteur, puis visez l'écran avec votre téléphone depuis le fond de la salle.</p>
<div class="actions"><button id="go" class="primary block" type="button">Lancer l'essai</button></div>
<p class="hint">Scrutin jetable, effacé au bout de 2 h.</p>
</section>
</main>
</body>
</html>
+24 -55
View File
@@ -16,7 +16,24 @@
<h1>Nouveau scrutin</h1> <h1>Nouveau scrutin</h1>
<form id="form"> <form id="form">
<label for="title">Titre</label> <label for="title">Titre</label>
<input id="title" type="text" required maxlength="200" placeholder="Conseil d'administration"> <input id="title" type="text" required maxlength="200" placeholder="Assemblée générale 2026">
<div class="row">
<div>
<label for="interval">Rotation du QR</label>
<select id="interval">
<option value="500">0,5 s</option>
<option value="1000" selected>1 s</option>
<option value="1500">1,5 s</option>
<option value="2000">2 s</option>
</select>
</div>
<div>
<label for="scans">Codes à scanner</label>
<input id="scans" type="number" min="2" max="20" value="5">
</div>
</div>
<p class="hint" id="duration-hint"></p>
<div class="row"> <div class="row">
<div> <div>
@@ -36,37 +53,6 @@
<input id="codes" type="number" min="1" max="5000" value="50"> <input id="codes" type="number" min="1" max="5000" value="50">
</div> </div>
<details class="advanced">
<summary>Réglages du code</summary>
<label for="code-style">Code projeté</label>
<select id="code-style">
<option value="ring" selected>Cercle animé</option>
<option value="qr">QR classique</option>
</select>
<label for="camera">Scan avec l'appareil photo</label>
<select id="camera">
<option value="1" selected>Autorisé</option>
<option value="0">Désactivé</option>
</select>
<div class="row">
<div>
<label for="interval">Rotation du code</label>
<select id="interval">
<option value="500">0,5 s</option>
<option value="700">0,7 s</option>
<option value="800" selected>0,8 s</option>
<option value="1000">1 s</option>
<option value="1500">1,5 s</option>
<option value="2000">2 s</option>
</select>
</div>
<div>
<label for="scans">Codes à scanner</label>
<input id="scans" type="number" min="2" max="20" value="5">
</div>
</div>
</details>
<div id="pw-box" hidden> <div id="pw-box" hidden>
<label for="pw">Mot de passe de création</label> <label for="pw">Mot de passe de création</label>
<input id="pw" type="password" autocomplete="current-password"> <input id="pw" type="password" autocomplete="current-password">
@@ -75,33 +61,16 @@
<div class="actions"><button class="primary block" type="submit">Créer le scrutin</button></div> <div class="actions"><button class="primary block" type="submit">Créer le scrutin</button></div>
</form> </form>
</section> </section>
<p class="hint center" id="try-link"><a href="/essai">Tester l'écran et les téléphones</a></p>
<section id="done" class="card" hidden> <section id="done" class="card" hidden>
<h1>Scrutin créé</h1> <h1>Scrutin créé</h1>
<div class="notice warn">Conservez le lien d'administration : il ne pourra pas être récupéré.</div> <div class="notice warn">Conservez le lien d'administration : il ne pourra pas être récupéré.</div>
<h2 class="mode-title">Écran splitté</h2> <label>Lien d'administration</label>
<p class="hint">L'administration sur votre écran, le projecteur sur l'écran étendu.</p> <div class="linkbox"><input id="admin-link" type="text" readonly><button id="copy-admin" class="small" type="button">Copier</button></div>
<div class="duo stack"> <label>Lien du projecteur</label>
<div class="pane"> <div class="linkbox"><input id="screen-link" type="text" readonly><button id="copy-screen" class="small" type="button">Copier</button></div>
<div class="pane-head"><svg class="icon" viewBox="0 0 24 24" width="26" height="26" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 5h16v11H4z"/><path d="M2 19.5h20"/><path d="M8 9h8"/><path d="M8 12.5h5"/></svg><p><b>Administration</b><span>Sur votre écran</span></p></div> <p class="hint">Pour l'ordinateur du vidéoprojecteur. Ne pas diffuser.</p>
<div class="linkbox"><input id="admin-link" type="text" readonly aria-label="Lien d'administration"><button id="copy-admin" class="small" type="button">Copier</button></div> <div class="actions"><a id="go-admin" class="btn primary block" href="#">Ouvrir l'administration</a></div>
<a id="go-admin" class="btn primary block" href="#" target="_blank" rel="noopener">Ouvrir l'administration</a>
</div>
<div class="pane">
<div class="pane-head"><svg class="icon" viewBox="0 0 24 24" width="26" height="26" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2 4h20"/><path d="M4 4v10h16V4"/><path d="M12 14v3"/><path d="M8.5 21l3.5-4 3.5 4"/></svg><p><b>Projecteur</b><span>Affiché à la salle, à ouvrir sur l'écran projeté</span></p></div>
<div class="linkbox"><input id="screen-link" type="text" readonly aria-label="Lien du projecteur"><button id="copy-screen" class="small" type="button">Copier</button></div>
<a id="go-screen" class="btn block" href="#" target="_blank" rel="noopener">Ouvrir le projecteur</a>
</div>
</div>
<h2 class="mode-title">Écran dupliqué</h2>
<p class="hint">Un seul écran, recopié sur le projecteur. Le bouton « Gérer » ouvre l'administration par-dessus.</p>
<div class="duo stack">
<div class="pane">
<div class="pane-head"><svg class="icon" viewBox="0 0 24 24" width="26" height="26" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2 4h20"/><path d="M4 4v10h16V4"/><path d="M12 14v3"/><path d="M8.5 21l3.5-4 3.5 4"/></svg><p><b>Écran unique</b><span>Projection et gestion au même endroit</span></p></div>
<a id="go-present" class="btn block" href="#" target="_blank" rel="noopener">Ouvrir l'écran dupliqué</a>
</div>
</div>
</section> </section>
</main> </main>
</body> </body>
+6 -164
View File
@@ -1,11 +1,9 @@
import { $, h, api, pollId, takeKey, liveSocket, resultsView, STATE_LABEL, toast, fill, pct, icon } from "./common.js"; import { $, h, api, pollId, takeKey, liveSocket, resultsView, STATE_LABEL, toast, fill, pct, icon } from "./common.js";
import { FORMATS, exportText } from "./export.js";
const pid = pollId(); const pid = pollId();
const key = takeKey(`rv_admin_${pid}`); const key = takeKey(`rv_admin_${pid}`);
const base = `/api/polls/${pid}`; const base = `/api/polls/${pid}`;
const TAB_KEY = "rv_admin_tab"; const TAB_KEY = "rv_admin_tab";
const FMT_KEY = "rv_export_fmt";
let state = null; let state = null;
const TEMPLATES = [ const TEMPLATES = [
@@ -23,7 +21,6 @@ function errMsg(e) {
not_draft: "La question n'est plus en brouillon", not_draft: "La question n'est plus en brouillon",
not_open: "La question n'est pas ouverte", not_open: "La question n'est pas ouverte",
not_closed: "La question n'est pas close", not_closed: "La question n'est pas close",
already_shown: "Résultats déjà publiés, le vote ne peut plus être rouvert",
}; };
return m[e.code] || e.message; return m[e.code] || e.message;
} }
@@ -65,7 +62,6 @@ function render() {
renderSettings(p); renderSettings(p);
renderQuestions(); renderQuestions();
renderShare(p);
} }
function renderSettings(p) { function renderSettings(p) {
@@ -80,12 +76,6 @@ function renderSettings(p) {
if (active !== $("#s-expected")) $("#s-expected").value = p.expected ?? ""; if (active !== $("#s-expected")) $("#s-expected").value = p.expected ?? "";
if (active !== $("#s-max")) $("#s-max").value = p.max_voters ?? ""; if (active !== $("#s-max")) $("#s-max").value = p.max_voters ?? "";
if (active !== $("#s-vote-scans")) $("#s-vote-scans").value = String(p.vote_scans); if (active !== $("#s-vote-scans")) $("#s-vote-scans").value = String(p.vote_scans);
if (active !== $("#s-code-style")) $("#s-code-style").value = p.code_style;
if (active !== $("#s-entry-big")) $("#s-entry-big").value = p.entry_big ? "1" : "0";
$("#s-entry-big").disabled = p.code_style !== "ring";
if (active !== $("#s-camera")) $("#s-camera").value = p.camera_pass ? "1" : "0";
// the classic qr is the camera app code itself
$("#s-camera").disabled = p.code_style !== "ring";
$("#s-code").checked = p.require_code; $("#s-code").checked = p.require_code;
$("#access-row").hidden = !p.require_code && !state.codes.access.total; $("#access-row").hidden = !p.require_code && !state.codes.access.total;
const sum = (c, none) => (c.total ? `${c.used} utilisé${c.used > 1 ? "s" : ""} sur ${c.total}` : none); const sum = (c, none) => (c.total ? `${c.used} utilisé${c.used > 1 ? "s" : ""} sur ${c.total}` : none);
@@ -100,8 +90,8 @@ function renderQuestions() {
box.append(h("p", { class: "empty" }, "Aucune question pour l'instant.")); box.append(h("p", { class: "empty" }, "Aucune question pour l'instant."));
return; return;
} }
// the open vote first, then newest first: a question just created or just closed stays at the top const order = { open: 0, draft: 1, closed: 2 };
const qs = [...state.questions].sort((a, b) => (b.state === "open") - (a.state === "open") || b.id - a.id); const qs = [...state.questions].sort((a, b) => order[a.state] - order[b.state] || a.id - b.id);
for (const q of qs) box.append(questionCard(q)); for (const q of qs) box.append(questionCard(q));
} }
@@ -122,69 +112,32 @@ function questionCard(q) {
actions.push(act("Lancer le vote", "open", "small go")); actions.push(act("Lancer le vote", "open", "small go"));
actions.push(act("Supprimer", "delete", "small danger", "Supprimer ce brouillon ?")); actions.push(act("Supprimer", "delete", "small danger", "Supprimer ce brouillon ?"));
} else if (q.state === "open") { } else if (q.state === "open") {
actions.push(act("Clore le vote", "close", "small primary", `Clore le vote (${q.participants + q.extra_ballots} vote${q.participants + q.extra_ballots > 1 ? "s" : ""}) ?`)); actions.push(act("Clore le vote", "close", "small primary", `Clore le vote (${q.participants} vote${q.participants > 1 ? "s" : ""}) ? Définitif.`));
} else { } else {
actions.push(q.results_public actions.push(q.results_public
? act("Masquer les résultats", "unpublish") ? act("Masquer les résultats", "unpublish")
: act("Publier les résultats", "publish", "small primary", "Publier les résultats ? Le vote ne pourra plus être rouvert.")); : act("Publier les résultats", "publish", "small primary"));
if (!q.shown) actions.push(act("Rouvrir le vote", "reopen"));
} }
if (q.state !== "draft") actions.push(h("button", { class: "small", type: "button", onclick: () => editExtra(q) }, "Votes en plus"));
if (q.state !== "draft" && !focused) actions.push(act([icon("screen", 15), "Afficher à l'écran"], "focus")); if (q.state !== "draft" && !focused) actions.push(act([icon("screen", 15), "Afficher à l'écran"], "focus"));
if (q.state === "closed") {
actions.push(h("button", {
class: "small copy-btn", type: "button", title: "Exporter les résultats", "aria-label": "Exporter les résultats",
onclick: () => openExport(q.id),
}, icon("copy", 16)));
}
const badges = [h("span", { class: `badge ${q.state}` }, STATE_LABEL[q.state])]; const badges = [h("span", { class: `badge ${q.state}` }, STATE_LABEL[q.state])];
if (q.results_public) badges.push(h("span", { class: "badge public" }, "Publiés")); if (q.results_public) badges.push(h("span", { class: "badge public" }, "Publiés"));
if (q.shared && state.poll.share_key) badges.push(h("span", { class: "badge public" }, "Partagés"));
if (focused) badges.push(h("span", { class: "focus-mark" }, icon("screen", 14), "À l'écran")); if (focused) badges.push(h("span", { class: "focus-mark" }, icon("screen", 14), "À l'écran"));
if (q.kind === "multi") badges.push(h("span", { class: "badge" }, `${q.max_choices} choix max`)); if (q.kind === "multi") badges.push(h("span", { class: "badge" }, `${q.max_choices} choix max`));
return h("article", { class: `q ${q.state}` }, return h("article", { class: `q ${q.state}` },
h("div", { class: "q-head" }, h("div", {}, badges), h("div", { class: "q-head" }, h("div", {}, badges),
q.state !== "draft" ? h("span", { class: "q-meta" }, `${q.participants} / ${voters}`, q.state !== "draft" ? h("span", { class: "q-meta" }, `${q.participants} / ${voters}`) : null),
q.extra_ballots ? h("span", { class: "extra-note" }, ` + ${q.extra_ballots}`) : null) : null),
h("div", { class: "q-text" }, q.text), h("div", { class: "q-text" }, q.text),
q.state === "closed" q.state === "closed"
? resultsView(q) ? resultsView(q)
: h("div", { class: "chips" }, q.options.map((o) => h("span", { class: "chip" }, o)), : h("div", { class: "chips" }, q.options.map((o) => h("span", { class: "chip" }, o)),
q.allow_blank ? h("span", { class: "chip ghost" }, "Blanc") : null), q.allow_blank ? h("span", { class: "chip ghost" }, "Blanc") : null),
q.state === "open" ? h("div", { class: "progress" }, fill(pct(q.participants, voters + q.extra_ballots), ""), q.state === "open" ? h("div", { class: "progress" }, fill(pct(q.participants, voters), "")) : null,
q.extra_ballots ? fill(pct(q.extra_ballots, voters + q.extra_ballots), "p-extra") : null) : null,
h("div", { class: "actions" }, actions), h("div", { class: "actions" }, actions),
); );
} }
// votes added by hand, in a dialog: the question list re-renders on every incoming vote
async function editExtra(q) {
const dlg = $("#extra-dlg"), e = q.extra, inputs = [];
const field = (label, value) => {
const inp = h("input", { type: "number", min: 0, max: 100000, value: String(value), inputmode: "numeric" });
inputs.push(inp);
return h("label", { class: "extra-row" }, h("span", {}, label), inp);
};
$("#extra-q").textContent = q.text;
$("#extra-fields").replaceChildren(...[
...q.options.map((o, i) => field(o, e.counts[i] || 0)),
q.allow_blank ? field("Blanc", e.blank) : null,
q.kind === "multi" ? field("Bulletins (choix multiple)", e.ballots) : null,
].filter(Boolean));
dlg.returnValue = "";
dlg.showModal();
await new Promise((res) => dlg.addEventListener("close", res, { once: true }));
if (dlg.returnValue !== "ok") return;
const vals = inputs.map((i) => Math.max(0, Math.floor(+i.value || 0)));
const n = q.options.length;
const payload = { counts: vals.slice(0, n), blank: q.allow_blank ? vals[n] : 0 };
if (q.kind === "multi") payload.ballots = vals[vals.length - 1];
try { await call("POST", `/questions/${q.id}/extra`, payload); toast("Votes ajoutés", "ok"); }
catch (err) { toast(err.code === "bad_extra" ? "Nombre de bulletins incohérent" : errMsg(err), "bad"); }
}
// composer // composer
const composer = $("#composer"); const composer = $("#composer");
@@ -250,9 +203,6 @@ const SETTINGS = {
"#s-max": (el) => ({ max_voters: intOrNull(el.value) }), "#s-max": (el) => ({ max_voters: intOrNull(el.value) }),
"#s-code": (el) => ({ require_code: el.checked }), "#s-code": (el) => ({ require_code: el.checked }),
"#s-vote-scans": (el) => ({ vote_scans: +el.value }), "#s-vote-scans": (el) => ({ vote_scans: +el.value }),
"#s-code-style": (el) => ({ code_style: el.value }),
"#s-entry-big": (el) => ({ entry_big: el.value === "1" }),
"#s-camera": (el) => ({ camera_pass: el.value === "1" }),
}; };
for (const [sel, build] of Object.entries(SETTINGS)) { for (const [sel, build] of Object.entries(SETTINGS)) {
$(sel).addEventListener("change", async (e) => { $(sel).addEventListener("change", async (e) => {
@@ -313,111 +263,6 @@ $("#export").addEventListener("click", async () => {
} catch (e) { toast(errMsg(e), "bad"); } } catch (e) { toast(errMsg(e), "bad"); }
}); });
// read-only results link, the admin ticks which closed questions it shows
const shareUrl = (k) => `${location.origin}/r/${pid}#${k}`;
function renderShare(p) {
const btn = (label, onclick, cls = "small") => h("button", { class: cls, type: "button", onclick }, label);
const rotate = async (msg) => {
if (msg && !confirm(msg)) return;
try { const r = await call("POST", "/share-key"); await copy(shareUrl(r.share_key), "Lien des résultats"); }
catch (e) { toast(errMsg(e), "bad"); }
};
const off = async () => {
if (!confirm("Désactiver le lien des résultats ?")) return;
try { await call("DELETE", "/share-key"); } catch (e) { toast(errMsg(e), "bad"); }
};
const closed = state.questions.filter((q) => q.state === "closed").sort((a, b) => a.id - b.id);
const n = closed.filter((q) => q.shared).length;
$("#share-summary").textContent = p.share_key ? `${n} question${n > 1 ? "s" : ""} visible${n > 1 ? "s" : ""}` : "Lecture seule";
$("#share-actions").replaceChildren(...(p.share_key
? [btn("Copier", () => copy(shareUrl(p.share_key), "Lien des résultats")),
btn("Nouveau lien", () => rotate("Créer un nouveau lien ? L'ancien cessera de fonctionner.")),
btn("Désactiver", off, "small danger")]
: [btn("Créer", () => rotate())]));
if (!p.share_key) return $("#share-qs").replaceChildren();
$("#share-qs").replaceChildren(...(closed.length
? closed.map((q) => h("label", { class: "share-q" },
h("input", {
type: "checkbox", checked: q.shared,
onchange: async (e) => {
const on = e.target.checked;
if (on && !q.shown && !confirm("Partager ces résultats ? Le vote ne pourra plus être rouvert.")) {
e.target.checked = false;
return;
}
try { await call("POST", `/questions/${q.id}/${on ? "share" : "unshare"}`); }
catch (err) { e.target.checked = !on; toast(errMsg(err), "bad"); }
},
}), h("span", {}, q.text)))
: [h("p", { class: "muted share-none" }, "Aucune question close.")]));
}
// text export, built in the browser from the closed tallies the socket already sends
const exDlg = $("#export-dlg");
let fmt = FORMATS[0];
try { fmt = FORMATS.find((f) => f.id === localStorage.getItem(FMT_KEY)) || fmt; } catch { /* private mode */ }
let exText = "";
for (const f of FORMATS) {
$("#ex-formats").append(h("button", {
class: "small", type: "button", role: "radio", dataset: { fmt: f.id },
onclick: () => {
fmt = f;
try { localStorage.setItem(FMT_KEY, f.id); } catch { /* private mode */ }
renderExport();
},
}, f.label));
}
function closedQuestions() {
return state.questions.filter((q) => q.state === "closed").sort((a, b) => a.id - b.id);
}
function renderExport() {
for (const b of $("#ex-formats").children) b.setAttribute("aria-checked", String(b.dataset.fmt === fmt.id));
const scope = $("#ex-scope").value;
const qs = closedQuestions().filter((q) => scope === "all" || String(q.id) === scope);
const now = new Date().toLocaleString("fr-FR", { dateStyle: "long", timeStyle: "short" });
exText = qs.length ? exportText(fmt, state.poll, state.voters, qs, now) : "";
const pre = $("#ex-preview");
pre.classList.toggle("empty", !exText);
pre.textContent = exText || "Aucune question close.";
$("#ex-copy").disabled = $("#ex-download").disabled = !exText;
}
function openExport(qid = "all") {
const qs = closedQuestions();
const sel = $("#ex-scope");
sel.replaceChildren(h("option", { value: "all" }, "Toutes les questions closes"),
...qs.map((q) => h("option", { value: String(q.id) }, q.text)));
sel.value = String(qid);
sel.hidden = qs.length < 2;
renderExport();
exDlg.showModal();
}
$("#ex-scope").addEventListener("change", renderExport);
$("#export-text").addEventListener("click", () => openExport());
$("#ex-copy").addEventListener("click", async () => {
try { await navigator.clipboard.writeText(exText); toast("Copié"); }
catch {
// prompt() would flatten the lines, select the preview so cmd+c works
getSelection().selectAllChildren($("#ex-preview"));
toast("Texte sélectionné");
}
});
$("#ex-download").addEventListener("click", () => {
// bom so excel reads the accents in the csv
const body = fmt.ext === "csv" ? "\ufeff" + exText : exText;
const blob = new Blob([body], { type: `${fmt.mime};charset=utf-8` });
const a = h("a", { href: URL.createObjectURL(blob), download: `rotatyvote-${pid}.${fmt.ext}` });
a.click();
setTimeout(() => URL.revokeObjectURL(a.href), 1000);
});
liveSocket(`/ws/${pid}/admin`, { liveSocket(`/ws/${pid}/admin`, {
auth: key, auth: key,
onMessage(msg) { onMessage(msg) {
@@ -440,6 +285,3 @@ liveSocket(`/ws/${pid}/admin`, {
c.textContent = "Reconnexion…"; c.textContent = "Reconnexion…";
}, },
}); });
// duplicated screen: the projector view with this admin in a drawer, same admin key
$("#open-present").href = `/present/${pid}#${encodeURIComponent(key)}`;
+23 -71
View File
@@ -1,6 +1,3 @@
import { tally, pct } from "./export.js";
export { pct };
export const $ = (sel, root = document) => root.querySelector(sel); export const $ = (sel, root = document) => root.querySelector(sel);
// tiny element builder, children are always text nodes or elements so no html injection // tiny element builder, children are always text nodes or elements so no html injection
@@ -106,6 +103,9 @@ export function drawQR(canvas, modules, px) {
} }
} }
export function pct(n, d) {
return d ? Math.round((n / d) * 1000) / 10 : 0;
}
// CSSOM write, a style="" attribute would be blocked by the CSP // CSSOM write, a style="" attribute would be blocked by the CSP
export function fill(percent, cls = "bar-fill") { export function fill(percent, cls = "bar-fill") {
@@ -115,37 +115,25 @@ export function fill(percent, cls = "bar-fill") {
} }
export function resultsView(q) { export function resultsView(q) {
if (!q.results) return null; const r = q.results;
// votes added by hand ride at the end of each bar, hatched orange, so nobody mistakes them for phone ballots if (!r) return null;
const { phone, extra, tot, ballots, blank, base, exBallots } = tally(q); const base = r.ballots - r.blank;
const max = Math.max(1, ...tot); const max = Math.max(1, ...r.counts);
const rows = q.options.map((label, i) => { const rows = q.options.map((label, i) =>
const stack = h("div", { class: "bar-stack" }, h("div", { class: "bar-row" + (r.counts[i] === max && r.counts[i] > 0 ? " lead" : "") },
seg("bar-fill", phone[i]), extra[i] ? seg("bar-extra", extra[i]) : null);
stack.style.width = `${pct(tot[i], max)}%`;
return h("div", { class: "bar-row" + (tot[i] === max && tot[i] > 0 ? " lead" : "") },
h("div", { class: "bar-label" }, label), h("div", { class: "bar-label" }, label),
h("div", { class: "bar-track" }, stack), h("div", { class: "bar-track" }, fill(pct(r.counts[i], max))),
h("div", { class: "bar-num" }, tot[i], h("small", {}, ` ${pct(tot[i], base).toLocaleString("fr-FR")} %`)), h("div", { class: "bar-num" }, r.counts[i], h("small", {}, ` ${pct(r.counts[i], base).toLocaleString("fr-FR")} %`)),
); ));
});
return h("div", { class: "results" }, return h("div", { class: "results" },
rows, rows,
h("p", { class: "results-foot" }, h("p", { class: "results-foot" },
`${ballots} bulletin${ballots > 1 ? "s" : ""}`, `${r.ballots} bulletin${r.ballots > 1 ? "s" : ""}`,
q.allow_blank ? `, dont ${blank} blanc${blank > 1 ? "s" : ""}` : "", q.allow_blank ? `, dont ${r.blank} blanc${r.blank > 1 ? "s" : ""}` : "",
exBallots ? h("span", { class: "extra-note" }, `, dont ${exBallots} ajouté${exBallots > 1 ? "s" : ""} à la main`) : "",
), ),
); );
} }
// a flex share of a bar (CSSOM write, the CSP blocks style="")
function seg(cls, n) {
const el = h("div", { class: cls });
el.style.flexGrow = String(n);
return el;
}
export const STATE_LABEL = { draft: "Brouillon", open: "Vote ouvert", closed: "Clos" }; export const STATE_LABEL = { draft: "Brouillon", open: "Vote ouvert", closed: "Clos" };
export function toast(msg, kind = "info") { export function toast(msg, kind = "info") {
@@ -161,10 +149,6 @@ const SVGNS = "http://www.w3.org/2000/svg";
const ICONS = { const ICONS = {
screen: ["M3 5h18v11H3z", "M8 20h8", "M12 16v4"], screen: ["M3 5h18v11H3z", "M8 20h8", "M12 16v4"],
check: ["M5 12.5l4.5 4.5L19 7.5"], check: ["M5 12.5l4.5 4.5L19 7.5"],
swap: ["M4 9h13l-3.5-3.5", "M20 15H7l3.5 3.5"],
camera: ["M3 8.5A2.5 2.5 0 0 1 5.5 6h2L9 4h6l1.5 2h2A2.5 2.5 0 0 1 21 8.5v9a2.5 2.5 0 0 1-2.5 2.5h-13A2.5 2.5 0 0 1 3 17.5z",
"M12 9.5a3.5 3.5 0 1 0 0 7a3.5 3.5 0 1 0 0-7"],
copy: ["M9 9h10v10H9z", "M5 15V5h10"],
}; };
export function icon(name, size = 16) { export function icon(name, size = 16) {
@@ -190,52 +174,20 @@ export function ring(n, total, size = 160, label = `${n}/${total}`) {
const r = 40, sw = 10, c = 2 * Math.PI * r; const r = 40, sw = 10, c = 2 * Math.PI * r;
// round caps overhang sw/2 on each side, so shorten each dash by sw // round caps overhang sw/2 on each side, so shorten each dash by sw
const slot = c / total, gap = total > 1 ? 5 : 0, seg = slot - gap - sw; const slot = c / total, gap = total > 1 ? 5 : 0, seg = slot - gap - sw;
const at = (len) => { const a = -Math.PI / 2 + len / r; return `${50 + r * Math.cos(a)} ${50 + r * Math.sin(a)}`; };
const fills = [];
for (let i = 0; i < total; i++) { for (let i = 0; i < total; i++) {
const s0 = i * slot + (gap + sw) / 2; const el = document.createElementNS(SVGNS, "circle");
const d = `M ${at(s0)} A ${r} ${r} 0 ${seg / r > Math.PI ? 1 : 0} 1 ${at(s0 + seg)}`; el.setAttribute("cx", 50); el.setAttribute("cy", 50); el.setAttribute("r", r);
// track underneath, fill on top sweeps clockwise. dash lengths in real units: some android webviews el.setAttribute("stroke-width", sw);
// mishandle pathLength and draw the fill whole or not at all el.setAttribute("stroke-dasharray", `${seg} ${c - seg}`);
for (const cls of ["seg", "fill"]) { // start at 12 o'clock
const el = document.createElementNS(SVGNS, "path"); el.setAttribute("stroke-dashoffset", String(c / 4 - i * slot - (gap + sw) / 2));
el.setAttribute("d", d); el.setAttribute("class", "seg" + (i < n ? " on" : "") + (i === n - 1 && n < total ? " last" : ""));
el.setAttribute("stroke-width", sw); svg.append(el);
el.setAttribute("class", cls);
if (cls === "fill") {
el.style.strokeDasharray = `${seg} ${seg + sw * 2}`;
el.style.strokeDashoffset = String(seg);
fills.push(el);
}
svg.append(el);
}
} }
const t = document.createElementNS(SVGNS, "text"); const t = document.createElementNS(SVGNS, "text");
t.setAttribute("x", 50); t.setAttribute("y", 50); t.setAttribute("x", 50); t.setAttribute("y", 50);
t.setAttribute("text-anchor", "middle"); t.setAttribute("dominant-baseline", "central"); t.setAttribute("text-anchor", "middle"); t.setAttribute("dominant-baseline", "central");
t.textContent = label;
svg.append(t); svg.append(t);
// updates in place so the css transitions run
svg.set = (k, text = `${k}/${total}`) => {
fills.forEach((el, i) => {
el.classList.toggle("on", i < k);
el.classList.toggle("last", i === k - 1 && k < total);
el.style.strokeDashoffset = String(i < k ? 0 : seg);
});
t.textContent = text;
};
svg.total = total;
svg.set(n, label);
return svg; return svg;
} }
// keeps the same svg between counts so each new segment fills instead of popping in
export function paintRing(box, n, total, size) {
let svg = box.querySelector("svg.ring");
if (!svg || svg.total !== total) {
svg = ring(0, total, size);
box.replaceChildren(svg);
// one frame at the old count, so the first fill animates too
svg.getBoundingClientRect();
}
svg.set(n);
}
-12
View File
@@ -1,12 +0,0 @@
import { $, api, toast } from "./common.js";
$("#go").addEventListener("click", async (e) => {
e.target.disabled = true;
try {
const r = await api("POST", "/api/trial");
location.href = `/screen/${r.id}#${r.screen_key}`;
} catch (err) {
toast(err.code === "too_many_trials" ? "Trop d'essais en cours, réessayez plus tard" : `Erreur : ${err.message}`, "bad");
e.target.disabled = false;
}
});
-148
View File
@@ -1,148 +0,0 @@
// plain text results export, pure functions (no dom) so node can run them too
export function tally(q) {
const r = q.results;
const ex = r.extra || { counts: r.counts.map(() => 0), blank: 0, ballots: 0 };
const extra = r.counts.map((_, i) => ex.counts[i] || 0);
const tot = r.counts.map((c, i) => c + extra[i]);
const ballots = r.ballots + ex.ballots, blank = r.blank + ex.blank;
return { phone: r.counts, extra, tot, ballots, blank, base: ballots - blank, exBallots: ex.ballots, exBlank: ex.blank };
}
export function pct(n, d) {
return d ? Math.round((n / d) * 1000) / 10 : 0;
}
// fr-FR toLocaleString puts a narrow nbsp in thousands, which breaks column alignment
const num = (n) => String(n).replace(".", ",");
const pctTxt = (n, d) => `${num(pct(n, d))} %`;
const plural = (n, word) => `${n} ${word}${n > 1 ? "s" : ""}`;
function foot(q, t) {
let s = plural(t.ballots, "bulletin");
if (q.allow_blank) s += `, dont ${plural(t.blank, "blanc")}`;
if (t.exBallots) s += `, dont ${t.exBallots} ajouté${t.exBallots > 1 ? "s" : ""} à la main`;
return s;
}
const nb = (qs, k) => (qs.length > 1 ? `${k + 1}. ` : "");
const kindNote = (q) => (q.kind === "multi" ? `Choix multiple, ${q.max_choices} max` : "");
function header(poll, voters, now) {
return [poll.title, `Résultats du ${now} · ${plural(voters, "inscription")}`];
}
// visible length, emoji and accents count as one column
const width = (s) => [...s].length;
const padEnd = (s, n) => s + " ".repeat(Math.max(0, n - width(s)));
const padStart = (s, n) => " ".repeat(Math.max(0, n - width(s))) + s;
function rows(q, t) {
const out = q.options.map((label, i) => ({ label, n: t.tot[i], p: pctTxt(t.tot[i], t.base) }));
if (q.allow_blank) out.push({ label: "Blanc", n: t.blank, p: "" });
return out;
}
function minutes(poll, voters, qs, now) {
const out = [...header(poll, voters, now)];
qs.forEach((q, k) => {
const t = tally(q), rs = rows(q, t);
const lw = Math.max(...rs.map((r) => width(r.label)));
const nw = Math.max(...rs.map((r) => String(r.n).length));
out.push("", `${nb(qs, k)}${q.text}`);
if (kindNote(q)) out.push(` ${kindNote(q)}`);
for (const r of rs) out.push(` ${padEnd(r.label, lw)} ${padStart(String(r.n), nw)} ${padStart(r.p, 7)}`.trimEnd());
out.push(` ${foot(q, t)}`);
});
return out.join("\n");
}
// no column alignment, survives a paste in an email or a chat
function compact(poll, voters, qs) {
const out = [poll.title];
for (const q of qs) {
const t = tally(q);
const parts = rows(q, t).map((r) => (r.p ? `${r.label} ${r.n} (${r.p})` : `${r.label} ${r.n}`));
out.push("", q.text + (kindNote(q) ? ` (${kindNote(q).toLowerCase()})` : ""),
`${parts.join(" · ")} · ${plural(t.ballots, "bulletin")}`);
}
return out.join("\n");
}
// the long npppav label would eat the whole line
const SHORT = { "ne prend pas part au vote": "NPPPAV" };
function list(poll, voters, qs) {
const out = [poll.title];
for (const q of qs) {
const t = tally(q);
const parts = rows(q, t).map((r) => `${SHORT[r.label.toLowerCase()] || r.label} (${r.n})`);
out.push("", `${q.text} [${plural(t.ballots, "bulletin")}]`, parts.join(" / "));
}
return out.join("\n");
}
function bars(poll, voters, qs) {
const out = [poll.title];
const W = 20;
for (const q of qs) {
const t = tally(q), rs = rows(q, t);
const lw = Math.max(...rs.map((r) => width(r.label)));
out.push("", q.text);
for (const r of rs) {
const full = Math.round((t.base ? r.n / t.base : 0) * W);
const bar = r.p ? "█".repeat(Math.min(W, full)) + "░".repeat(Math.max(0, W - full)) : " ".repeat(W);
out.push(`${padEnd(r.label, lw)} ${bar} ${r.n}${r.p ? ` · ${r.p}` : ""}`);
}
out.push(foot(q, t));
}
return out.join("\n");
}
const mdCell = (s) => String(s).replace(/\|/g, "\\|");
function markdown(poll, voters, qs, now) {
const [title, sub] = header(poll, voters, now);
const out = [`# ${mdCell(title)}`, "", sub];
qs.forEach((q, k) => {
const t = tally(q);
out.push("", `## ${nb(qs, k)}${q.text}`, "");
if (kindNote(q)) out.push(`*${kindNote(q)}*`, "");
out.push("| Réponse | Voix | % |", "| --- | ---: | ---: |");
for (const r of rows(q, t)) out.push(`| ${mdCell(r.label)} | ${r.n} | ${r.p} |`);
out.push("", `${foot(q, t)}.`);
});
return out.join("\n");
}
// semicolons, the decimal comma makes plain commas ambiguous in french spreadsheets
const csvCell = (v) => {
const s = String(v);
return /[;"\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
};
function csv(poll, voters, qs) {
const out = [["n", "question", "réponse", "voix", "dont ajoutées", "% exprimés"]];
qs.forEach((q, k) => {
const t = tally(q);
q.options.forEach((o, i) => out.push([k + 1, q.text, o, t.tot[i], t.extra[i], num(pct(t.tot[i], t.base))]));
if (q.allow_blank) out.push([k + 1, q.text, "Blanc", t.blank, t.exBlank, ""]);
out.push([k + 1, q.text, "Bulletins", t.ballots, t.exBallots, ""]);
});
return out.map((r) => r.map(csvCell).join(";")).join("\n");
}
export const FORMATS = [
{ id: "list", label: "Liste", ext: "txt", mime: "text/plain", build: list },
{ id: "bars", label: "Barres", ext: "txt", mime: "text/plain", build: bars },
{ id: "compact", label: "Compact", ext: "txt", mime: "text/plain", build: compact },
{ id: "pv", label: "Procès-verbal", ext: "txt", mime: "text/plain", build: minutes },
{ id: "md", label: "Markdown", ext: "md", mime: "text/markdown", build: markdown },
{ id: "csv", label: "CSV", ext: "csv", mime: "text/csv", build: csv },
];
// closed questions only (nobody sees open tallies), in the order they were asked
export function exportText(fmt, poll, voters, questions, now) {
const qs = questions.filter((q) => q.state === "closed" && q.results).sort((a, b) => a.id - b.id);
return fmt.build(poll, voters, qs, now);
}
+8 -14
View File
@@ -3,9 +3,15 @@ import { $, api, toast } from "./common.js";
const cfg = await api("GET", "/api/config").catch(() => ({})); const cfg = await api("GET", "/api/config").catch(() => ({}));
$("#pw-box").hidden = !cfg.create_password; $("#pw-box").hidden = !cfg.create_password;
function hint() {
const s = (+$("#interval").value * +$("#scans").value) / 1000;
$("#duration-hint").textContent = `≈ ${s.toLocaleString("fr-FR")} s de scan`;
}
$("#interval").addEventListener("change", hint);
$("#scans").addEventListener("input", hint);
hint();
$("#codes-on").addEventListener("change", (e) => { $("#codes-box").hidden = !e.target.checked; }); $("#codes-on").addEventListener("change", (e) => { $("#codes-box").hidden = !e.target.checked; });
// the classic qr is the camera app code itself
$("#code-style").addEventListener("change", (e) => { $("#camera").disabled = e.target.value !== "ring"; });
$("#form").addEventListener("submit", async (e) => { $("#form").addEventListener("submit", async (e) => {
e.preventDefault(); e.preventDefault();
@@ -16,8 +22,6 @@ $("#form").addEventListener("submit", async (e) => {
title: $("#title").value, title: $("#title").value,
interval_ms: +$("#interval").value, interval_ms: +$("#interval").value,
scans_required: +$("#scans").value, scans_required: +$("#scans").value,
code_style: $("#code-style").value,
camera_pass: $("#camera").value === "1",
expected: $("#expected").value ? +$("#expected").value : null, expected: $("#expected").value ? +$("#expected").value : null,
max_voters: $("#maxv").value ? +$("#maxv").value : null, max_voters: $("#maxv").value ? +$("#maxv").value : null,
require_code: $("#codes-on").checked, require_code: $("#codes-on").checked,
@@ -30,10 +34,7 @@ $("#form").addEventListener("submit", async (e) => {
$("#admin-link").value = admin; $("#admin-link").value = admin;
$("#screen-link").value = screen; $("#screen-link").value = screen;
$("#go-admin").href = admin; $("#go-admin").href = admin;
$("#go-screen").href = screen;
$("#go-present").href = `${location.origin}/present/${res.id}#${res.admin_key}`;
$("#create").hidden = true; $("#create").hidden = true;
$("#try-link").hidden = true;
$("#done").hidden = false; $("#done").hidden = false;
} catch (err) { } catch (err) {
toast(err.code === "bad_password" ? "Mot de passe incorrect" : `Erreur : ${err.message}`, "bad"); toast(err.code === "bad_password" ? "Mot de passe incorrect" : `Erreur : ${err.message}`, "bad");
@@ -48,10 +49,3 @@ for (const [btn, input] of [["#copy-admin", "#admin-link"], ["#copy-screen", "#s
catch { $(input).select(); } catch { $(input).select(); }
}); });
} }
// a real window, not a tab: it can be dragged onto the projected display and put full screen there
$("#go-screen").addEventListener("click", (e) => {
const w = window.open($("#go-screen").href, "_blank", "popup,width=1280,height=720");
// blocked popup: the plain link still opens a tab
if (w) { w.opener = null; e.preventDefault(); }
});
-27
View File
@@ -1,27 +0,0 @@
import { $, h, api, pollId, hashKey, resultsView } from "./common.js";
const pid = pollId();
// the key stays in the address bar so the link can be passed on as is
const key = hashKey();
async function load() {
let data;
try { data = await api("GET", `/api/r/${pid}`, undefined, key); }
catch {
$("#denied").hidden = false;
$("#list").replaceChildren();
return;
}
$("#denied").hidden = true;
$("#title").textContent = data.title;
document.title = `Résultats · ${data.title}`;
const qs = data.questions.sort((a, b) => a.id - b.id);
$("#list").replaceChildren(...(qs.length
? qs.map((q) => h("article", { class: "q" }, h("div", { class: "q-text" }, q.text), resultsView(q)))
: [h("p", { class: "muted" }, "Aucun résultat pour l'instant.")]));
}
load();
// questions get added as the meeting goes on
setInterval(() => { if (!document.hidden) load(); }, 15000);
document.addEventListener("visibilitychange", () => { if (!document.hidden) load(); });
+151 -525
View File
@@ -7,10 +7,10 @@ export const RING_SECTORS = [24, 28, 32, 36];
// code space units, centered on the origin. the solid dark center disc is what the phone looks for // code space units, centered on the origin. the solid dark center disc is what the phone looks for
export const CENTER = 0.62; export const CENTER = 0.62;
export const RADII = [0.9, 1.05, 1.2, 1.35]; export const RADII = [0.9, 1.05, 1.2, 1.35];
export const THICK = 0.12; export const THICK = 0.105;
export const DISC = 1.5; // light background disc export const DISC = 1.5; // light background disc
// animation bounds: dash length and opacity breathe inside these, the data never depends on them // animation bounds: dash length and opacity breathe inside these, the data never depends on them
const LEN = [0.62, 0.88]; // part of the sector covered by the dash const LEN = [0.56, 0.86]; // part of the sector covered by the dash
// wide gap between the two classes so the camera tells them apart easily // wide gap between the two classes so the camera tells them apart easily
const ALPHA_DARK = [0.93, 1], ALPHA_LIGHT = [0.08, 0.19]; const ALPHA_DARK = [0.93, 1], ALPHA_LIGHT = [0.08, 0.19];
const NSYM = 6; const NSYM = 6;
@@ -54,12 +54,11 @@ export function rsEncode(msg) {
} }
// port of the wikiversity "reed-solomon codes for coders" decoder (fcr 0, generator 2) // port of the wikiversity "reed-solomon codes for coders" decoder (fcr 0, generator 2)
// the whole corrected codeword, or null export function rsDecode(cw) {
function rsFix(cw) {
const n = cw.length; const n = cw.length;
const synd = [0]; const synd = [0];
for (let i = 0; i < NSYM; i++) synd.push(polyEval(cw, pow(2, i))); for (let i = 0; i < NSYM; i++) synd.push(polyEval(cw, pow(2, i)));
if (Math.max(...synd) === 0) return cw; if (Math.max(...synd) === 0) return cw.slice(0, n - NSYM);
let errLoc = [1], oldLoc = [1]; let errLoc = [1], oldLoc = [1];
for (let i = 0; i < NSYM; i++) { for (let i = 0; i < NSYM; i++) {
const K = i + 1; const K = i + 1;
@@ -101,12 +100,7 @@ function rsFix(cw) {
}); });
const fixed = cw.map((c, i) => c ^ E[i]); const fixed = cw.map((c, i) => c ^ E[i]);
for (let i = 0; i < NSYM; i++) if (polyEval(fixed, pow(2, i))) return null; for (let i = 0; i < NSYM; i++) if (polyEval(fixed, pow(2, i))) return null;
return fixed; return fixed.slice(0, n - NSYM);
}
export function rsDecode(cw) {
const fixed = rsFix(cw);
return fixed && fixed.slice(0, cw.length - NSYM);
} }
export function whitening(n) { export function whitening(n) {
@@ -154,62 +148,21 @@ const sectorAngle = (theta, j, n) => theta + ((j + 0.5) * 2 * Math.PI) / n;
const INK = "#1c2036"; const INK = "#1c2036";
function logo(ctx, cx, cy, r) { function logo(ctx, cx, cy, r) {
// same geometry as static/img/mark.svg: r 11, stroke 5, 6 dashes of 4.52 every 11.52, first one yellow // the rotaty mark in light tones on the dark disc
const u = (r * 0.62) / 13.5, rr = 11 * u, step = (2 * Math.PI) / 6, dash = 4.52 / 11, start = 3.5 / 11; const n = 6, rr = r * 0.52, step = (2 * Math.PI) / n;
ctx.lineCap = "round"; ctx.lineCap = "round";
ctx.lineWidth = 5 * u; ctx.lineWidth = r * 0.17;
for (let j = 0; j < 6; j++) { for (let j = 0; j < n; j++) {
const a = -Math.PI / 2 + start + j * step; const a = -Math.PI / 2 + j * step;
ctx.strokeStyle = j === 0 ? "#ffcc00" : "#ffffff"; ctx.strokeStyle = j === 0 ? "#ffcc00" : "#ffffff";
ctx.beginPath(); ctx.arc(cx, cy, rr, a, a + dash); ctx.stroke(); ctx.beginPath(); ctx.arc(cx, cy, rr, a + step * 0.2, a + step * 0.8); ctx.stroke();
} }
// check mark inside, same one the phone shows once its scans count
ctx.strokeStyle = "#ffffff";
ctx.lineWidth = 2.4 * u;
ctx.lineJoin = "round";
ctx.beginPath(); ctx.moveTo(cx - 3.2 * u, cy + 0.15 * u); ctx.lineTo(cx - 0.9 * u, cy + 2.45 * u); ctx.lineTo(cx + 3.35 * u, cy - 2.3 * u); ctx.stroke();
} }
const EASE = {
sine: (x) => 0.5 - 0.5 * Math.cos(Math.PI * x),
cubic: (x) => (x < 0.5 ? 4 * x ** 3 : 1 - (-2 * x + 2) ** 3 / 2),
quart: (x) => (x < 0.5 ? 8 * x ** 4 : 1 - (-2 * x + 2) ** 4 / 2),
linear: (x) => x,
};
// deterministic per-dash phase so every dash breathes on its own rhythm // deterministic per-dash phase so every dash breathes on its own rhythm
const phase = (k, j) => ((Math.sin(k * 12.9898 + j * 78.233) * 43758.5453) % 1 + 1) % 1; const phase = (k, j) => ((Math.sin(k * 12.9898 + j * 78.233) * 43758.5453) % 1 + 1) % 1;
// the bean keeps its shape, only its inside changes: a soft gradient slides across it from a random end, // fade: { from: previous bits, k: 0..1 } while the code switches, so changed dashes cross-fade
// fading the new tone in behind and the old one out ahead. conic so it follows the arc exactly
// arc: center, angular extent cap to cap, and how to stroke the dash
function wipeDash(ctx, { cx, cy, lo, hi, dash }, from, to, fade, k, j) {
const dir = phase(k + 7, j + (fade.seed || 0) * 31) < 0.5 ? 1 : -1;
const delay = phase(k + 3, j + (fade.seed || 0) * 17) * 0.15, x = Math.min(1, Math.max(0, (fade.k - delay) / 0.85));
const e = (EASE[fade.ease] || EASE.sine)(x);
if (!ctx.createConicGradient) {
ctx.globalAlpha = from + (to - from) * e;
dash();
return;
}
const soft = (hi - lo) * 0.6, edge = dir > 0 ? lo - soft + (hi - lo + 2 * soft) * e : hi + soft - (hi - lo + 2 * soft) * e;
const start = lo - soft - 0.2, at = (th) => Math.min(1, Math.max(0, (th - start) / (2 * Math.PI)));
const g = ctx.createConicGradient(start, cx, cy);
const [behind, ahead] = dir > 0 ? [to, from] : [from, to];
for (let i = 0; i <= 6; i++) {
const u = i / 6, w = u * u * (3 - 2 * u);
g.addColorStop(at(edge - soft + 2 * soft * u), `rgba(28,32,54,${behind + (ahead - behind) * w})`);
}
g.addColorStop(0, `rgba(28,32,54,${behind})`);
g.addColorStop(1, `rgba(28,32,54,${ahead})`);
ctx.globalAlpha = 1;
ctx.strokeStyle = g;
dash();
ctx.strokeStyle = INK;
}
// fade: { from: previous bits, k: 0..1, seed } while the code switches. a changed dash is wiped:
// one edge crosses it from a random end, the new tone fills behind it while the old one empties ahead
export function render(ctx, cx, cy, unit, theta, bits, t = 0, fade = null) { export function render(ctx, cx, cy, unit, theta, bits, t = 0, fade = null) {
ctx.fillStyle = "#eef0f6"; ctx.fillStyle = "#eef0f6";
ctx.beginPath(); ctx.arc(cx, cy, DISC * unit, 0, 2 * Math.PI); ctx.fill(); ctx.beginPath(); ctx.arc(cx, cy, DISC * unit, 0, 2 * Math.PI); ctx.fill();
@@ -217,9 +170,9 @@ export function render(ctx, cx, cy, unit, theta, bits, t = 0, fade = null) {
ctx.beginPath(); ctx.arc(cx, cy, CENTER * unit, 0, 2 * Math.PI); ctx.fill(); ctx.beginPath(); ctx.arc(cx, cy, CENTER * unit, 0, 2 * Math.PI); ctx.fill();
logo(ctx, cx, cy, CENTER * unit); logo(ctx, cx, cy, CENTER * unit);
const prev = fade && fade.k < 1 ? ringsOf(fade.from) : null; const prev = fade && fade.k < 1 ? ringsOf(fade.from) : null;
const ease = fade ? fade.k * fade.k * (3 - 2 * fade.k) : 1;
ctx.lineCap = "round"; ctx.lineCap = "round";
ctx.lineWidth = THICK * unit; ctx.lineWidth = THICK * unit;
ctx.strokeStyle = INK;
ringsOf(bits).forEach((ring, k) => { ringsOf(bits).forEach((ring, k) => {
const n = ring.length, r = RADII[k] * unit, step = (2 * Math.PI) / n; const n = ring.length, r = RADII[k] * unit, step = (2 * Math.PI) / n;
const cap = (THICK * unit) / 2 / r; const cap = (THICK * unit) / 2 / r;
@@ -227,15 +180,12 @@ export function render(ctx, cx, cy, unit, theta, bits, t = 0, fade = null) {
const ph = phase(k, j) * 2 * Math.PI, w = 0.5 + 0.5 * Math.sin(t * 1.3 + ph), w2 = 0.5 + 0.5 * Math.sin(t * 0.9 + ph * 1.7); const ph = phase(k, j) * 2 * Math.PI, w = 0.5 + 0.5 * Math.sin(t * 1.3 + ph), w2 = 0.5 + 0.5 * Math.sin(t * 0.9 + ph * 1.7);
const len = LEN[0] + (LEN[1] - LEN[0]) * w; const len = LEN[0] + (LEN[1] - LEN[0]) * w;
const alphaOf = (bit) => { const [a0, a1] = bit === "1" ? ALPHA_DARK : ALPHA_LIGHT; return a0 + (a1 - a0) * w2; }; const alphaOf = (bit) => { const [a0, a1] = bit === "1" ? ALPHA_DARK : ALPHA_LIGHT; return a0 + (a1 - a0) * w2; };
const now = alphaOf(ring[j]), before = prev ? alphaOf(prev[k][j]) : now;
const half = Math.max(0.01, (step * len) / 2 - cap); const half = Math.max(0.01, (step * len) / 2 - cap);
const a = sectorAngle(theta, j, n) - Math.PI / 2; const a = sectorAngle(theta, j, n) - Math.PI / 2;
const dash = () => { ctx.beginPath(); ctx.arc(cx, cy, r, a - half, a + half); ctx.stroke(); }; ctx.globalAlpha = before + (now - before) * ease;
if (!prev || prev[k][j] === ring[j]) { ctx.strokeStyle = INK;
ctx.globalAlpha = alphaOf(ring[j]); ctx.beginPath(); ctx.arc(cx, cy, r, a - half, a + half); ctx.stroke();
dash();
continue;
}
wipeDash(ctx, { cx, cy, lo: a - half - cap, hi: a + half + cap, dash }, alphaOf(prev[k][j]), alphaOf(ring[j]), fade, k, j);
} }
}); });
ctx.globalAlpha = 1; ctx.globalAlpha = 1;
@@ -280,23 +230,6 @@ function corr(vals, bits) {
return dv && db ? num / Math.sqrt(dv * db) : 0; return dv && db ? num / Math.sqrt(dv * db) : 0;
} }
// same as corr after removing the first angular harmonic from both sides: a reflection or a lamp lights one side
// of the ring brighter, and that slow swell alone pulls a clean sync ring under the threshold
const flatten = (v) => {
const n = v.length;
let a = 0, b = 0, c = 0;
for (let j = 0; j < n; j++) { const t = (2 * Math.PI * j) / n; a += v[j]; b += v[j] * Math.cos(t); c += v[j] * Math.sin(t); }
a /= n; b *= 2 / n; c *= 2 / n;
return v.map((x, j) => { const t = (2 * Math.PI * j) / n; return x - a - b * Math.cos(t) - c * Math.sin(t); });
};
const SYNC_FLAT = flatten(SYNC_BITS);
function corrFlat(vals) {
const f = flatten(vals);
let num = 0, dv = 0, db = 0;
for (let i = 0; i < f.length; i++) { num += f[i] * -SYNC_FLAT[i]; dv += f[i] * f[i]; db += SYNC_FLAT[i] * SYNC_FLAT[i]; }
return dv && db ? num / Math.sqrt(dv * db) : 0;
}
// otsu split of one ring: threshold + how well it separates (between-class / total variance) // otsu split of one ring: threshold + how well it separates (between-class / total variance)
function split(vals) { function split(vals) {
const s = [...vals].sort((a, b) => a - b), n = s.length; const s = [...vals].sort((a, b) => a - b), n = s.length;
@@ -328,158 +261,80 @@ function solve(A, B) {
return B.map((b, i) => b / A[i][i]); return B.map((b, i) => b / A[i][i]);
} }
// dark = clearly under the brightest thing nearby. a washed projector keeps black/white around 0.6, function otsu(vals) {
// and the disc always has its light surround within reach, whatever the room does around the screen const hist = new Float64Array(256);
function darkMask(g, w, h, ratio) { for (const v of vals) hist[Math.max(0, Math.min(255, v | 0))]++;
const T = 8, tw = Math.ceil(w / T), th = Math.ceil(h / T), tmax = new Float32Array(tw * th); let total = 0, sum = 0;
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { for (let i = 0; i < 256; i++) { total += hist[i]; sum += i * hist[i]; }
const i = ((y / T) | 0) * tw + ((x / T) | 0), v = g[y * w + x]; let wb = 0, sb = 0, best = 0, thr = 128;
if (v > tmax[i]) tmax[i] = v; for (let i = 0; i < 256; i++) {
wb += hist[i];
if (!wb || wb === total) continue;
sb += i * hist[i];
const mb = sb / wb, mf = (sum - sb) / (total - wb), v = wb * (total - wb) * (mb - mf) ** 2;
if (v > best) { best = v; thr = i; }
} }
const dark = new Uint8Array(w * h); return thr;
for (let ty = 0; ty < th; ty++) for (let tx = 0; tx < tw; tx++) {
let m = 0;
for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
const yy = ty + dy, xx = tx + dx;
if (yy >= 0 && xx >= 0 && yy < th && xx < tw && tmax[yy * tw + xx] > m) m = tmax[yy * tw + xx];
}
// nothing bright around: not a screen
if (m < 48) continue;
const thr = m * ratio, y1 = Math.min(h, (ty + 1) * T), x1 = Math.min(w, (tx + 1) * T);
for (let y = ty * T; y < y1; y++) for (let x = tx * T; x < x1; x++) if (g[y * w + x] < thr) dark[y * w + x] = 1;
}
return dark;
} }
// ellipse from the moments of a component filled row by row (so the light logo inside doesn't count as // candidate center discs: solid dark elliptic blobs. returns [{ cx, cy, A }] in image pixels,
// holes), or null when the shape is not a filled ellipse. rows y0..y1 where stamp[y] === id hold lo..hi
function rowEllipse(lo, hi, stamp, id, y0, y1, count, s) {
let m0 = 0, mx = 0, my = 0, mxx = 0, myy = 0, mxy = 0;
for (let y = y0; y <= y1; y++) {
if (stamp[y] !== id) continue;
const a0 = lo[y], a1 = hi[y], n = a1 - a0 + 1, sx = ((a0 + a1) * n) / 2;
const sxx = (a1 * (a1 + 1) * (2 * a1 + 1) - (a0 - 1) * a0 * (2 * a0 - 1)) / 6;
m0 += n; mx += sx; my += y * n; mxx += sxx; myy += y * y * n; mxy += y * sx;
}
const ux = mx / m0, uy = my / m0;
const cxx = mxx / m0 - ux * ux + 1 / 12, cyy = myy / m0 - uy * uy + 1 / 12, cxy = mxy / m0 - ux * uy;
const tr = cxx + cyy, dt = Math.sqrt(Math.max(0, ((cxx - cyy) / 2) ** 2 + cxy * cxy));
const l1 = tr / 2 + dt, l2 = tr / 2 - dt;
if (l2 <= 0) return null;
const a = 2 * Math.sqrt(l1), b = 2 * Math.sqrt(l2);
const fill = m0 / (Math.PI * a * b), solidity = count / m0;
if (fill < 0.84 || fill > 1.16 || solidity < 0.5 || b / a < 0.38 || b < 3.5) return null;
const phi = 0.5 * Math.atan2(2 * cxy, cxx - cyy);
const c = Math.cos(phi), sn = Math.sin(phi);
const k1 = (a * s) / CENTER, k2 = (b * s) / CENTER;
return { cx: (ux + 0.5) * s - 0.5, cy: (uy + 0.5) * s - 0.5, A: [c * k1, -sn * k2, sn * k1, c * k2], area: m0 * s * s, r: Math.sqrt(a * b) * s };
}
// dark blobs of one pyramid level that look like a filled ellipse. s = level px size in image px
function blobs(g, w, h, s, ratio, out) {
const dark = darkMask(g, w, h, ratio);
const stack = new Int32Array(w * h), lo = new Int32Array(h), hi = new Int32Array(h), stamp = new Int32Array(h).fill(-1);
let id = 0;
for (let start = 0; start < w * h; start++) {
if (!dark[start]) continue;
// flood fill one component, keep per-row extents
let sp = 0, count = 0, y0 = h, y1 = -1;
stack[sp++] = start; dark[start] = 0; id++;
while (sp) {
const i = stack[--sp], x = i % w, y = (i / w) | 0;
count++;
if (stamp[y] !== id) { stamp[y] = id; lo[y] = hi[y] = x; if (y < y0) y0 = y; if (y > y1) y1 = y; }
else if (x < lo[y]) lo[y] = x; else if (x > hi[y]) hi[y] = x;
if (x > 0 && dark[i - 1]) { dark[i - 1] = 0; stack[sp++] = i - 1; }
if (x < w - 1 && dark[i + 1]) { dark[i + 1] = 0; stack[sp++] = i + 1; }
if (y > 0 && dark[i - w]) { dark[i - w] = 0; stack[sp++] = i - w; }
if (y < h - 1 && dark[i + w]) { dark[i + w] = 0; stack[sp++] = i + w; }
}
if (count < 30 || y1 - y0 < 5) continue;
const e = rowEllipse(lo, hi, stamp, id, y0, y1, count, s);
if (e) out.push(e);
}
}
const median = (a) => { const s = [...a].sort((x, y) => x - y); return s[s.length >> 1]; };
// does the neighbourhood look like a ring code? dark disc, light gap all around, half-dark textured band.
// cheap (a few dozen samples) and what keeps plain dark blobs away from the decoder
function ringness(img, cand) {
const [a11, a12, a21, a22] = cand.A;
const at = (r, phi) => { const x = r * Math.sin(phi), y = -r * Math.cos(phi); return bilinear(img, cand.cx + a11 * x + a12 * y, cand.cy + a21 * x + a22 * y); };
const n = 24, dk = [], gp = [], rb = [];
for (let i = 0; i < n; i++) {
const phi = (i / n) * 2 * Math.PI;
dk.push(at(0.48, phi)); gp.push(at(0.735, phi));
for (const R of RADII) rb.push(at(R, phi + 0.07), at(R, phi + 0.2));
}
// off-frame samples are NaN: a code cut by the border can't be read anyway
if (dk.some(Number.isNaN) || gp.some(Number.isNaN) || rb.some(Number.isNaN)) return null;
const D = median(dk), G = median(gp), span = G - D;
if (span < 14) return null;
const sg = [...gp].sort((x, y) => x - y), sd = [...dk].sort((x, y) => x - y);
if (sg[4] < D + 0.5 * span || sd[n - 5] > D + 0.4 * span) return null;
const mean = rb.reduce((x, y) => x + y, 0) / rb.length, q = (G - mean) / span;
const dev = Math.sqrt(rb.reduce((x, y) => x + (y - mean) ** 2, 0) / rb.length) / span;
if (q < 0.1 || q > 0.8 || dev < 0.1) return null;
// dashes go all the way round: text or a line next to a dark disc only inks one side
for (let k = 0; k < 4; k++) {
let s = 0, g = 0;
for (let i = k * 48; i < (k + 1) * 48; i++) s += rb[i];
// against the gap of the same side, bands shift whole sides
for (let i = k * 6; i < (k + 1) * 6; i++) g += gp[i];
const qk = (g / 6 - s / 48) / span;
if (qk < 0.08 || qk > 0.85) return null;
}
return { span, black: D, white: G };
}
// candidate center discs: solid dark elliptic blobs with rings around. returns [{ cx, cy, A, span }] in image pixels,
// A maps code space (center disc radius CENTER) onto the ellipse, rotation left free // A maps code space (center disc radius CENTER) onto the ellipse, rotation left free
export function locate(img, opts = {}) { export function locate(img, opts = {}) {
const f = Math.max(1, Math.ceil(Math.max(img.w, img.h) / (opts.maxDim || 640))); const f = Math.max(1, Math.ceil(Math.max(img.w, img.h) / (opts.maxDim || 480)));
let w = Math.floor(img.w / f), h = Math.floor(img.h / f), g = new Float32Array(w * h); const w = Math.floor(img.w / f), h = Math.floor(img.h / f), small = new Float32Array(w * h);
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
let s = 0; let s = 0;
for (let dy = 0; dy < f; dy++) for (let dx = 0; dx < f; dx++) s += img.g[(y * f + dy) * img.w + x * f + dx]; for (let dy = 0; dy < f; dy++) for (let dx = 0; dx < f; dx++) s += img.g[(y * f + dy) * img.w + x * f + dx];
g[y * w + x] = s / (f * f); small[y * w + x] = s / (f * f);
} }
// each level sees discs of ~5..14 px radius, halving covers every size up to the whole frame const thr = otsu(small);
const raw = []; const label = new Int32Array(w * h).fill(-1), cands = [];
for (let s = f; w >= 24 && h >= 24; s *= 2) { const stack = [];
// two cuts: the low one keeps a blurred disc apart from the first ring, the high one still sees it on a very washed screen for (let start = 0; start < w * h; start++) {
for (const ratio of [0.72, 0.8]) blobs(g, w, h, s, ratio, raw); if (label[start] !== -1 || small[start] > thr) continue;
const w2 = w >> 1, h2 = h >> 1, g2 = new Float32Array(w2 * h2); // flood fill one dark component, keep per-row extents
for (let y = 0; y < h2; y++) for (let x = 0; x < w2; x++) { const id = cands.length, rows = new Map();
const i = 2 * y * w + 2 * x; let count = 0;
g2[y * w2 + x] = (g[i] + g[i + 1] + g[i + w] + g[i + w + 1]) / 4; label[start] = id; stack.push(start);
while (stack.length) {
const i = stack.pop(), x = i % w, y = (i / w) | 0;
count++;
const r = rows.get(y);
if (r) { if (x < r[0]) r[0] = x; if (x > r[1]) r[1] = x; } else rows.set(y, [x, x]);
for (const j of [i - 1, i + 1, i - w, i + w]) {
if (j < 0 || j >= w * h || label[j] !== -1 || small[j] > thr) continue;
if ((j === i - 1 && x === 0) || (j === i + 1 && x === w - 1)) continue;
label[j] = id; stack.push(j);
}
} }
g = g2; w = w2; h = h2; cands.push(null);
if (count < 30 || rows.size < 6) continue;
// moments of the row-filled shape, so the light logo inside doesn't count as holes
let m0 = 0, mx = 0, my = 0, mxx = 0, myy = 0, mxy = 0;
for (const [y, [x0, x1]] of rows) {
const n = x1 - x0 + 1, sx = ((x0 + x1) * n) / 2, sxx = (x1 * (x1 + 1) * (2 * x1 + 1) - (x0 - 1) * x0 * (2 * x0 - 1)) / 6;
m0 += n; mx += sx; my += y * n; mxx += sxx; myy += y * y * n; mxy += y * sx;
}
const ux = mx / m0, uy = my / m0;
const cxx = mxx / m0 - ux * ux + 1 / 12, cyy = myy / m0 - uy * uy + 1 / 12, cxy = mxy / m0 - ux * uy;
const tr = cxx + cyy, dt = Math.sqrt(Math.max(0, ((cxx - cyy) / 2) ** 2 + cxy * cxy));
const l1 = tr / 2 + dt, l2 = tr / 2 - dt;
if (l2 <= 0) continue;
const a = 2 * Math.sqrt(l1), b = 2 * Math.sqrt(l2);
const fill = m0 / (Math.PI * a * b), solidity = count / m0;
if (fill < 0.86 || fill > 1.14 || solidity < 0.5 || b / a < 0.38 || b < 5) continue;
const phi = 0.5 * Math.atan2(2 * cxy, cxx - cyy);
const c = Math.cos(phi), s = Math.sin(phi);
const k1 = (a * f) / CENTER, k2 = (b * f) / CENTER;
cands[id] = { cx: (ux + 0.5) * f - 0.5, cy: (uy + 0.5) * f - 0.5, A: [c * k1, -s * k2, s * k1, c * k2], area: m0 };
} }
// same disc seen at two levels or cuts: keep the tightest blob, the others may have swallowed a ring return cands.filter(Boolean).sort((p, q) => q.area - p.area).slice(0, opts.max || 4);
raw.sort((p, q) => q.area - p.area);
const cands = [];
for (const c of raw) {
const twin = cands.findIndex((o) => Math.hypot(o.cx - c.cx, o.cy - c.cy) < 0.5 * Math.max(o.r, c.r) && o.r / c.r < 1.6 && c.r / o.r < 1.6);
if (twin >= 0) { cands[twin] = c; continue; }
cands.push(c);
}
const out = [];
for (const c of cands) {
const fit = discFit(img, c) || c, rn = ringness(img, fit);
if (opts.dbg && Math.hypot(c.cx - opts.dbg.cx, c.cy - opts.dbg.cy) < 0.4 * opts.dbg.r) opts.dbg.stage = rn ? "ok" : fit === c ? "nofit" : "ringness";
if (rn) out.push({ ...fit, ...rn });
if (out.length >= 8) break;
}
// a projected code is the most contrasted thing around: dim look-alikes in the room go last
return out.sort((p, q) => q.span - p.span).slice(0, opts.max || 5);
} }
// the rough ellipse from the center disc is a bit off, and more so as the radius grows. // the rough ellipse from the center disc is a bit off, and more so as the radius grows.
// the rings themselves are the better reference: find their dark bands along rays, // the rings themselves are the better reference: find their dark bands along rays,
// fit one concentric ellipse family, undo center/scale/shear // fit one concentric ellipse family, undo center/scale/shear
function refine(S, span) { function refine(S) {
const rows = []; const rows = [];
const rays = 160, r0 = 0.74, r1 = 1.48, dr = 0.005; const rays = 160, r0 = 0.74, r1 = 1.48, dr = 0.005;
for (let i = 0; i < rays; i++) { for (let i = 0; i < rays; i++) {
@@ -489,7 +344,7 @@ function refine(S, span) {
if (prof.some(Number.isNaN)) continue; if (prof.some(Number.isNaN)) continue;
const sorted = [...prof].sort((a, b) => a - b); const sorted = [...prof].sort((a, b) => a - b);
const bg = sorted[Math.floor(sorted.length * 0.9)], lo = sorted[0]; const bg = sorted[Math.floor(sorted.length * 0.9)], lo = sorted[0];
if (bg - lo < 0.07 * span) continue; if (bg - lo < 15) continue;
RADII.forEach((R) => { RADII.forEach((R) => {
const c = Math.round((R - r0) / dr), wdw = Math.round(0.065 / dr); const c = Math.round((R - r0) / dr), wdw = Math.round(0.065 / dr);
let m = -1; let m = -1;
@@ -592,6 +447,44 @@ function cubicRoots(a, b, c, d) {
return [0, 1, 2].map((k) => r * Math.cos(phi / 3 - (2 * Math.PI * k) / 3) - b / 3); return [0, 1, 2].map((k) => r * Math.cos(phi / 3 - (2 * Math.PI * k) / 3) - b / 3);
} }
// image points on the center disc edge and on each ring, following rays of the rough affine map
function edgePoints(img, cand) {
const [a11, a12, a21, a22] = cand.A;
const map = (x, y) => [cand.cx + a11 * x + a12 * y, cand.cy + a21 * x + a22 * y];
const at = (x, y) => { const [u, v] = map(x, y); return bilinear(img, u, v); };
const disc = [], rings = RADII.map(() => []), rays = 160;
for (let i = 0; i < rays; i++) {
const phi = (i / rays) * 2 * Math.PI, dx = Math.sin(phi), dy = -Math.cos(phi);
// disc edge: strongest dark-to-light step between 0.42 and 0.8
let best = 0, br = 0;
const prof = [];
for (let r = 0.4; r <= 0.82; r += 0.005) prof.push(at(r * dx, r * dy));
if (!prof.some(Number.isNaN)) {
for (let j = 2; j < prof.length - 2; j++) {
const gstep = prof[j + 2] - prof[j - 2];
if (gstep > best) { best = gstep; br = 0.4 + j * 0.005; }
}
if (best > 20) disc.push(map(br * dx, br * dy));
}
// rings: darkest point around each radius, only when it is a clear dip (a dark dash)
RADII.forEach((R, k) => {
const op = [], span = 0.07;
for (let r = R - span; r <= R + span + 1e-9; r += 0.004) op.push(at(r * dx, r * dy));
if (op.some(Number.isNaN)) return;
let m = 0;
for (let j = 1; j < op.length; j++) if (op[j] < op[m]) m = j;
const edge = Math.max(op[0], op[op.length - 1]);
if (m > 1 && m < op.length - 2 && edge - op[m] > 35) {
const a = op[m - 1], b = op[m], c = op[m + 1], den = a - 2 * b + c;
const off = den > 0 ? (0.5 * (a - c)) / den : 0;
const r = R - span + (m + off) * 0.004;
rings[k].push(map(r * dx, r * dy));
}
});
}
return { disc, rings };
}
// center of a conic (3x3 symmetric), in its own coordinates // center of a conic (3x3 symmetric), in its own coordinates
function conicCenter(Q) { function conicCenter(Q) {
const d = Q[0][0] * Q[1][1] - Q[0][1] * Q[1][0]; const d = Q[0][0] * Q[1][1] - Q[0][1] * Q[1][0];
@@ -599,89 +492,25 @@ function conicCenter(Q) {
return [-(Q[1][1] * Q[0][2] - Q[0][1] * Q[1][2]) / d, -(-Q[1][0] * Q[0][2] + Q[0][0] * Q[1][2]) / d]; return [-(Q[1][1] * Q[0][2] - Q[0][1] * Q[1][2]) / d, -(-Q[1][0] * Q[0][2] + Q[0][0] * Q[1][2]) / d];
} }
// image points on the center disc edge, following rays of the rough affine map function nelderMead(f, x0, step, iters) {
function discEdge(img, cand, rays) { let pts = [x0, [x0[0] + step, x0[1]], [x0[0], x0[1] + step]].map((x) => ({ x, v: f(x) }));
const [a11, a12, a21, a22] = cand.A, unit = Math.sqrt(Math.abs(a11 * a22 - a12 * a21)); for (let it = 0; it < iters; it++) {
const map = (x, y) => [cand.cx + a11 * x + a12 * y, cand.cy + a21 * x + a22 * y]; pts.sort((a, b) => a.v - b.v);
// about half a pixel per step, small discs don't need 85 samples per ray const [b, g, w] = pts, c = [(b.x[0] + g.x[0]) / 2, (b.x[1] + g.x[1]) / 2];
const dr = Math.max(0.005, 0.5 / unit), pts = []; const at = (t) => [c[0] + t * (w.x[0] - c[0]), c[1] + t * (w.x[1] - c[1])];
for (let i = 0; i < rays; i++) { const r = { x: at(-1) }; r.v = f(r.x);
const phi = (i / rays) * 2 * Math.PI, dx = Math.sin(phi), dy = -Math.cos(phi); if (r.v < b.v) { const e = { x: at(-2) }; e.v = f(e.x); pts[2] = e.v < r.v ? e : r; }
const prof = []; else if (r.v < g.v) pts[2] = r;
let lo = Infinity, hi = -Infinity, bad = false; else { const k = { x: at(0.5) }; k.v = f(k.x); if (k.v < w.v) pts[2] = k; else pts = [b, ...[g, w].map((p) => { const x = [(p.x[0] + b.x[0]) / 2, (p.x[1] + b.x[1]) / 2]; return { x, v: f(x) }; })]; }
for (let r = 0.4; r <= 0.84; r += dr) {
const [u, v] = map(r * dx, r * dy), p = bilinear(img, u, v);
if (Number.isNaN(p)) { bad = true; break; }
prof.push(p); if (p < lo) lo = p; if (p > hi) hi = p;
}
if (bad || hi - lo < 10) continue;
// strongest dark-to-light step
let best = 0, bj = 0;
for (let j = 2; j < prof.length - 2; j++) { const s = prof[j + 2] - prof[j - 2]; if (s > best) { best = s; bj = j; } }
if (best < 0.2 * (hi - lo) || bj < 4 || bj > prof.length - 5) continue;
const g0 = prof[bj + 1] - prof[bj - 3], g2 = prof[bj + 3] - prof[bj - 1], den = g0 - 2 * best + g2;
const off = den < 0 ? Math.max(-1, Math.min(1, (0.5 * (g0 - g2)) / den)) : 0;
const br = 0.4 + (bj + off) * dr;
pts.push(map(br * dx, br * dy));
} }
return pts; pts.sort((a, b) => a.v - b.v);
return pts[0].x;
} }
// the blob moments are rough on small discs: refit the ellipse on the disc edge at full resolution // projective map code space -> image from the two conics, or null
function discFit(img, cand) {
let cur = cand;
for (let pass = 0; pass < 2; pass++) {
const pts = discEdge(img, cur, 48);
if (pts.length < 30) return pass ? cur : null;
const mx = pts.reduce((s, p) => s + p[0], 0) / pts.length, my = pts.reduce((s, p) => s + p[1], 0) / pts.length;
const sc = Math.sqrt(pts.reduce((s, p) => s + (p[0] - mx) ** 2 + (p[1] - my) ** 2, 0) / pts.length) || 1;
const Q = fitConic(pts.map((p) => [(p[0] - mx) / sc, (p[1] - my) / sc]));
const c0 = Q && conicCenter(Q);
if (!c0) return pass ? cur : null;
const kk = -(Q[2][2] + Q[0][2] * c0[0] + Q[1][2] * c0[1]);
let p = Q[0][0] / kk, q = Q[0][1] / kk, r = Q[1][1] / kk;
const det = p * r - q * q;
if (!(p > 0 && det > 0)) return pass ? cur : null;
// x^T M x = 1: the map from the unit circle is M^-1/2, closed form for 2x2
const n11 = r / det, n12 = -q / det, n22 = p / det, sd = Math.sqrt(n11 * n22 - n12 * n12), t = Math.sqrt(n11 + n22 + 2 * sd);
const k = sc / CENTER / t, A = [(n11 + sd) * k, n12 * k, n12 * k, (n22 + sd) * k];
const size = Math.sqrt(Math.abs(A[0] * A[3] - A[1] * A[2])) * CENTER, cx = mx + c0[0] * sc, cy = my + c0[1] * sc;
if (Math.hypot(cx - cand.cx, cy - cand.cy) > 0.4 * cand.r || size < 0.6 * cand.r || size > 1.6 * cand.r) return pass ? cur : null;
cur = { ...cand, cx, cy, A, r: size };
}
return cur;
}
// image points on each ring: darkest point around each radius, only when it is a clear dip (a dark dash)
function ringDips(img, cand, span) {
const [a11, a12, a21, a22] = cand.A;
const map = (x, y) => [cand.cx + a11 * x + a12 * y, cand.cy + a21 * x + a22 * y];
const at = (x, y) => { const [u, v] = map(x, y); return bilinear(img, u, v); };
const rings = RADII.map(() => []), rays = 160;
for (let i = 0; i < rays; i++) {
const phi = (i / rays) * 2 * Math.PI, dx = Math.sin(phi), dy = -Math.cos(phi);
RADII.forEach((R, k) => {
const op = [], reach = 0.07;
for (let r = R - reach; r <= R + reach + 1e-9; r += 0.004) op.push(at(r * dx, r * dy));
if (op.some(Number.isNaN)) return;
let m = 0;
for (let j = 1; j < op.length; j++) if (op[j] < op[m]) m = j;
const edge = Math.max(op[0], op[op.length - 1]);
if (m > 1 && m < op.length - 2 && edge - op[m] > 0.16 * span) {
const a = op[m - 1], b = op[m], c = op[m + 1], den = a - 2 * b + c;
const off = den > 0 ? (0.5 * (a - c)) / den : 0;
const r = R - reach + (m + off) * 0.004;
rings[k].push(map(r * dx, r * dy));
}
});
}
return rings;
}
// projective map code space -> image coordinates from the two conics, or null
export let lastProjective = null; export let lastProjective = null;
function projective(img, cand) { function projective(img, cand) {
const span = cand.span || 200, disc = discEdge(img, cand, 160), rings = ringDips(img, cand, span); const { disc, rings } = edgePoints(img, cand);
const outer = rings[rings.length - 1]; const outer = rings[rings.length - 1];
lastProjective = { disc: disc.length, rings: rings.map((r) => r.length), stage: 'points' }; lastProjective = { disc: disc.length, rings: rings.map((r) => r.length), stage: 'points' };
if (disc.length < 40 || outer.length < 30) return null; if (disc.length < 40 || outer.length < 30) return null;
@@ -717,14 +546,6 @@ function projective(img, cand) {
if (!l || Math.abs(l[2]) < 1e-9) return null; if (!l || Math.abs(l[2]) < 1e-9) return null;
l = l.map((v) => v / l[2]); l = l.map((v) => v / l[2]);
lastProjective.l = l; lastProjective.stage = 'line'; lastProjective.l = l; lastProjective.stage = 'line';
const map = mapFromLine(Q1, l, mx, my, sc);
lastProjective.stage = map ? 'ok' : 'ellipse';
lastProjective.map = map;
return map;
}
// code space -> image from the disc conic Q1 and a vanishing line l (normalized coordinates), or null
function mapFromLine(Q1, l, mx, my, sc) {
// rectify: P maps the vanishing line to infinity // rectify: P maps the vanishing line to infinity
const P = [[1, 0, 0], [0, 1, 0], l]; const P = [[1, 0, 0], [0, 1, 0], l];
const Pi = inv3(P); const Pi = inv3(P);
@@ -739,184 +560,45 @@ function mapFromLine(Q1, l, mx, my, sc) {
// (x-c0)^T (M/kk) (x-c0) = 1 is the disc: scale so it becomes radius CENTER // (x-c0)^T (M/kk) (x-c0) = 1 is the disc: scale so it becomes radius CENTER
let a = M[0][0] / kk, b = M[0][1] / kk, c = M[1][1] / kk; let a = M[0][0] / kk, b = M[0][1] / kk, c = M[1][1] / kk;
if (a < 0) { a = -a; b = -b; c = -c; } if (a < 0) { a = -a; b = -b; c = -c; }
lastProjective.ellipse = [a, b, c]; lastProjective.stage = 'ellipse';
if (!(a > 0 && a * c - b * b > 0)) return null; if (!(a > 0 && a * c - b * b > 0)) return null;
lastProjective.stage = 'ok';
const p = Math.sqrt(a), q = b / p, s = Math.sqrt(c - q * q); const p = Math.sqrt(a), q = b / p, s = Math.sqrt(c - q * q);
// affine from code space (radius CENTER) into the rectified plane: x = c0 + B t, B = (A^-1) / CENTER // affine from code space (radius CENTER) into the rectified plane: x = c0 + B t, B = (A^-1) / CENTER
const B = [[1 / p / CENTER, -q / (p * s) / CENTER], [0, 1 / s / CENTER]]; const B = [[1 / p / CENTER, -q / (p * s) / CENTER], [0, 1 / s / CENTER]];
return (x, y) => { const map = (x, y) => {
const u = c0[0] + B[0][0] * x + B[0][1] * y, v = c0[1] + B[1][1] * y; const u = c0[0] + B[0][0] * x + B[0][1] * y, v = c0[1] + B[1][1] * y;
const w = Pi[2][0] * u + Pi[2][1] * v + Pi[2][2]; const w = Pi[2][0] * u + Pi[2][1] * v + Pi[2][2];
// points beyond the vanishing line fold back: report them off image
if (w <= 0) return [NaN, NaN];
const X = (Pi[0][0] * u + Pi[0][1] * v + Pi[0][2]) / w, Y = (Pi[1][0] * u + Pi[1][1] * v + Pi[1][2]) / w; const X = (Pi[0][0] * u + Pi[0][1] * v + Pi[0][2]) / w, Y = (Pi[1][0] * u + Pi[1][1] * v + Pi[1][2]) / w;
return [X * sc + mx, Y * sc + my]; return [X * sc + mx, Y * sc + my];
}; };
lastProjective.map = map;
return (x, y) => { const [u, v] = map(x, y); return bilinear(img, u, v); };
} }
// disc conic in normalized coordinates, for the tilt search // reads one candidate. returns { token, theta, score, scale } or { token: null, ... } or null.
function discConic(img, cand) {
const disc = discEdge(img, cand, 160);
if (disc.length < 40) return null;
const mx = disc.reduce((s, p) => s + p[0], 0) / disc.length, my = disc.reduce((s, p) => s + p[1], 0) / disc.length;
const sc = Math.sqrt(disc.reduce((s, p) => s + (p[0] - mx) ** 2 + (p[1] - my) ** 2, 0) / disc.length) || 1;
const Q1 = fitConic(disc.map((p) => [(p[0] - mx) / sc, (p[1] - my) / sc]));
return Q1 && { Q1, mx, my, sc };
}
// unsharp mask on a small crop: undoes part of the camera blur and flattens slow brightness changes
// (rolling shutter bands, vignetting), which a washed-out projection can't afford
function sharpen(img, passes, amt) {
const { g, w, h } = img, b = Float32Array.from(g), tmp = new Float32Array(w * h);
for (let p = 0; p < passes; p++) {
for (let y = 0, i = 0; y < h; y++) for (let x = 0; x < w; x++, i++) tmp[i] = (b[x > 0 ? i - 1 : i] + 2 * b[i] + b[x < w - 1 ? i + 1 : i]) / 4;
for (let y = 0, i = 0; y < h; y++) for (let x = 0; x < w; x++, i++) b[i] = (tmp[y > 0 ? i - w : i] + 2 * tmp[i] + tmp[y < h - 1 ? i + w : i]) / 4;
}
for (let i = 0; i < b.length; i++) b[i] = g[i] + amt * (g[i] - b[i]);
return { g: b, w, h };
}
// sectors close to each other in code space, across rings: the local reference for dark vs light
const NEAR = (() => {
const pts = [];
RING_SECTORS.forEach((n, k) => { for (let j = 0; j < n; j++) { const a = sectorAngle(0, j, n); pts.push([RADII[k] * Math.sin(a), -RADII[k] * Math.cos(a)]); } });
return pts.map((p, i) => pts.map((_, m) => m).filter((m) => m !== i && Math.hypot(pts[m][0] - p[0], pts[m][1] - p[1]) < 0.5));
})();
// vals: brightness of the 120 sectors, sync ring first. two-means split against nearby sectors, seeded by the
// sync ring whose bits are known. returns data bits and soft values (> 0 dark, ~1 = a clean dash)
function classify(vals) {
const n = vals.length, known = SYNC_BITS.length;
let D = 0, L = 0, nd = 0;
for (let j = 0; j < known; j++) if (SYNC_BITS[j]) { D += vals[j]; nd++; } else L += vals[j];
D /= nd; L /= known - nd;
const swing = L - D;
if (!(swing > 0)) return null;
const bit = new Uint8Array(n), thr = new Float32Array(n).fill((D + L) / 2), half = new Float32Array(n).fill(swing / 2);
for (let i = 0; i < n; i++) bit[i] = i < known ? SYNC_BITS[i] : +(vals[i] < thr[i]);
for (let it = 0; it < 3; it++) {
for (let i = 0; i < n; i++) {
let sd = 0, cd = 0, sl = 0, cl = 0;
for (const m of NEAR[i]) if (bit[m]) { sd += vals[m]; cd++; } else { sl += vals[m]; cl++; }
if (cd < 2 || cl < 2) continue;
const d = sd / cd, l = sl / cl;
if (l - d > 0.35 * swing) { thr[i] = (d + l) / 2; half[i] = (l - d) / 2; }
}
for (let i = known; i < n; i++) bit[i] = +(vals[i] < thr[i]);
}
const soft = new Float32Array(n - known);
for (let i = known; i < n; i++) soft[i - known] = Math.max(-2, Math.min(2, (thr[i] - vals[i]) / half[i]));
return { bits: Array.from(bit.subarray(known)), soft };
}
// bits -> token, or null. soft tells how sure each bit was
function tokenOf(bits, soft, strict = true) {
const cw = bytesFromBits(bits), fixed = rsFix(cw);
if (!fixed) return null;
let bad = 0, flips = 0, shaky = 0, all = 0;
for (let i = 0; i < cw.length; i++) {
if (cw[i] === fixed[i]) continue;
bad++;
for (let k = 0; k < 8; k++) if (((cw[i] ^ fixed[i]) >> (7 - k)) & 1) { flips++; shaky += Math.abs(soft[i * 8 + k]); }
}
for (let i = 0; i < soft.length; i++) all += Math.abs(soft[i]);
// rs "repairs" 1 random word in 80000 at 3 byte errors. noise gets its confident bits flipped as often as
// the shaky ones, a real read only loses shaky ones
if (strict && bad >= 3 && shaky / flips > 0.7 * (all / soft.length)) return null;
return { token: tokenFromPayload(fixed.slice(0, fixed.length - NSYM)), fixes: bad };
}
// looks like a code but the geometry is off: a screen seen at 30-45 deg bends the outer rings more than the
// conic fit can follow. search the vanishing line directly, scored on the sync ring and the outer ring.
// tone(u, v) reads brightness at image coordinates
function searchTilt(img, cand, tone, best, opts) {
const D = discConic(img, cand);
if (!D) return null;
const at = (map) => (x, y) => { const [u, v] = map(x, y); return tone(u, v); };
const n0 = RING_SECTORS[0], s0 = (2 * Math.PI) / n0, nk = RING_SECTORS[3], sk = (2 * Math.PI) / nk;
const quick = (S) => {
let top = null;
for (let dt = -12; dt <= 12; dt += 2) {
const th = best.theta + (dt * Math.PI) / 180, vals = [];
for (let j = 0; j < n0; j++) vals.push(sector(S, RADII[0], sectorAngle(th, j, n0), s0));
if (vals.some(Number.isNaN)) return null;
const sc = Math.max(corr(vals, SYNC_BITS), corrFlat(vals));
if (!top || sc > top.sc) top = { sc, th };
}
const outer = [];
for (let j = 0; j < nk; j++) outer.push(sector(S, RADII[3], sectorAngle(top.th, j, nk), sk));
if (outer.some(Number.isNaN)) return null;
return top.sc + split(outer).quality;
};
const tryLine = (lx, ly) => {
const map = mapFromLine(D.Q1, [lx, ly, 1], D.mx, D.my, D.sc);
if (!map) return null;
const S = at(map), q = quick(S);
return q == null ? null : { q, S, l: [lx, ly] };
};
const tries = [];
for (const m of [0.015, 0.03, 0.045, 0.06, 0.08, 0.1]) for (let i = 0; i < 16; i++) {
const t = tryLine(m * Math.cos((i / 16) * 2 * Math.PI), m * Math.sin((i / 16) * 2 * Math.PI));
if (t) tries.push(t);
}
tries.sort((p, q) => q.q - p.q);
let out = null;
for (const t of tries.slice(0, 3)) {
// polish around the pick on a finer grid before the full read
let pick = t;
for (const dx of [-0.008, 0, 0.008]) for (const dy of [-0.008, 0, 0.008]) {
if (!dx && !dy) continue;
const c = tryLine(t.l[0] + dx, t.l[1] + dy);
if (c && c.q > pick.q) pick = c;
}
const r = readRings(pick.S, opts);
if (r && r.token) return { ...r, tilt: pick.l };
if (r && (!out || r.score > out.score)) out = r;
}
return out;
}
// reads one candidate. returns { token, theta, score, scale, soft } or { token: null, ... } or null.
// tries the projective geometry (better under tilt) and the plain affine one (safer on soft frames) // tries the projective geometry (better under tilt) and the plain affine one (safer on soft frames)
export function decodeAt(img, cand, opts = {}) { export function decodeAt(img, cand, opts = {}) {
const span = cand.span || 200, unit = Math.sqrt(Math.abs(cand.A[0] * cand.A[3] - cand.A[1] * cand.A[2]));
let tone = img, x0 = 0, y0 = 0;
if (opts.sharpen !== false && unit < 70) {
// small code (under ~210 px across): read tones from a sharpened crop
const half = Math.ceil(unit * (DISC + 0.25)) + 4;
x0 = Math.max(0, Math.round(cand.cx) - half); y0 = Math.max(0, Math.round(cand.cy) - half);
const x1 = Math.min(img.w, Math.round(cand.cx) + half + 1), y1 = Math.min(img.h, Math.round(cand.cy) + half + 1);
const w = x1 - x0, h = y1 - y0, g = new Float32Array(w * h);
for (let y = 0; y < h; y++) g.set(img.g.subarray((y0 + y) * img.w + x0, (y0 + y) * img.w + x1), y * w);
tone = sharpen({ g, w, h }, 6, 2);
}
const [a11, a12, a21, a22] = cand.A; const [a11, a12, a21, a22] = cand.A;
// geometry comes from the plain image, tones from the sharpened one const affine = (x, y) => bilinear(img, cand.cx + a11 * x + a12 * y, cand.cy + a21 * x + a22 * y);
const proj = opts.projective !== false && projective(img, cand); const maps = [opts.projective !== false && projective(img, cand), affine].filter(Boolean);
const maps = [proj && ((x, y) => { const [u, v] = proj(x, y); return bilinear(tone, u - x0, v - y0); }),
(x, y) => bilinear(tone, cand.cx - x0 + a11 * x + a12 * y, cand.cy - y0 + a21 * x + a22 * y)].filter(Boolean);
let best = null; let best = null;
for (const S0 of maps) { for (const S0 of maps) {
const S = (opts.refine !== false && refine(S0, span * (tone === img ? 1 : 2))) || S0; const S = (opts.refine !== false && refine(S0)) || S0;
const r = readRings(S, { ...opts, span }); const r = readRings(S, opts);
if (r && r.token) return r; if (r && r.token) return r;
if (r && (!best || r.score > best.score)) best = r; if (r && (!best || r.score > best.score)) best = r;
} }
if (opts.tilt !== false && best && best.score > 0.55 && best.theta != null) {
const r = searchTilt(img, cand, (x, y) => bilinear(tone, x - x0, y - y0), best, { ...opts, span });
if (r && r.token) return r;
if (r && r.score > best.score) best = r;
}
return best; return best;
} }
// rotation and scale of the sync ring: { best } to go on, or { done } when the read stops here function readRings(S, opts) {
function findSync(S, opts) {
const minScore = opts.minScore ?? 0.8; const minScore = opts.minScore ?? 0.8;
const n0 = RING_SECTORS[0], step0 = (2 * Math.PI) / n0; const n0 = RING_SECTORS[0], step0 = (2 * Math.PI) / n0;
const syncAt = (theta, scale) => { const syncAt = (theta, scale) => {
const vals = []; const vals = [];
for (let j = 0; j < n0; j++) vals.push(sector(S, RADII[0] * scale, sectorAngle(theta, j, n0), step0)); for (let j = 0; j < n0; j++) vals.push(sector(S, RADII[0] * scale, sectorAngle(theta, j, n0), step0));
return vals.some(Number.isNaN) ? null : { score: Math.max(corr(vals, SYNC_BITS), corrFlat(vals)), theta, scale, vals }; return vals.some(Number.isNaN) ? null : { score: corr(vals, SYNC_BITS), theta, scale, vals };
}; };
// coarse pass over the full turn (no rotational symmetry), then a fine pass around the best hits. // coarse pass over the full turn (no rotational symmetry), then a fine pass around the best hits.
// ~5x fewer samples than a dense search, which matters on low-end phones // ~5x fewer samples than a dense search, which matters on low-end phones
@@ -924,13 +606,11 @@ function findSync(S, opts) {
for (const scale of opts.scales || [0.96, 1.0, 1.04]) { for (const scale of opts.scales || [0.96, 1.0, 1.04]) {
for (let t = 0; t < 72; t++) { for (let t = 0; t < 72; t++) {
const r = syncAt((t / 72) * 2 * Math.PI, scale); const r = syncAt((t / 72) * 2 * Math.PI, scale);
if (!r) return { done: null }; if (!r) return null;
coarse.push(r); coarse.push(r);
} }
} }
coarse.sort((p, q) => q.score - p.score); coarse.sort((p, q) => q.score - p.score);
// nothing like the sync pattern at any angle: not a code, skip the fine search
if (coarse[0].score < 0.5) return { done: { token: null, ...coarse[0], vals: undefined } };
let best = null; let best = null;
for (const c of coarse.slice(0, 3)) { for (const c of coarse.slice(0, 3)) {
for (const ds of [-0.02, 0, 0.02]) for (let dt = -10; dt <= 10; dt++) { for (const ds of [-0.02, 0, 0.02]) for (let dt = -10; dt <= 10; dt++) {
@@ -939,19 +619,12 @@ function findSync(S, opts) {
} }
} }
// weak sync means we're not looking at a ring code (or a bad frame): don't let rs "fix" noise // weak sync means we're not looking at a ring code (or a bad frame): don't let rs "fix" noise
if (!best || best.score < minScore) return { done: best ? { token: null, ...best, vals: undefined } : null }; if (!best || best.score < minScore) return best ? { token: null, ...best } : null;
return { best };
}
function readRings(S, opts) {
const { best, done } = findSync(S, opts);
if (!best) return done;
const dark = [], light = []; const dark = [], light = [];
best.vals.forEach((v, j) => (SYNC_BITS[j] ? dark : light).push(v)); best.vals.forEach((v, j) => (SYNC_BITS[j] ? dark : light).push(v));
const md = dark.reduce((x, y) => x + y) / dark.length, ml = light.reduce((x, y) => x + y) / light.length; const md = dark.reduce((x, y) => x + y) / dark.length, ml = light.reduce((x, y) => x + y) / light.length;
const out = { ...best, vals: undefined, token: null }; if (ml - md < 12) return { token: null, ...best };
if (ml - md < Math.max(5, 0.055 * (opts.span || 200))) return out; const bits = [];
const all = [...best.vals], otsu = [];
for (let k = 1; k < RING_SECTORS.length; k++) { for (let k = 1; k < RING_SECTORS.length; k++) {
// nudge scale and rotation per ring (perspective is only approximated) and keep the cleanest split // nudge scale and rotation per ring (perspective is only approximated) and keep the cleanest split
const n = RING_SECTORS[k], step = (2 * Math.PI) / n; const n = RING_SECTORS[k], step = (2 * Math.PI) / n;
@@ -963,68 +636,21 @@ function readRings(S, opts) {
const sp = split(vals); const sp = split(vals);
if (!pick || sp.quality > pick.quality) pick = { ...sp, vals }; if (!pick || sp.quality > pick.quality) pick = { ...sp, vals };
} }
if (!pick) return out; if (!pick) return { token: null, ...best };
all.push(...pick.vals); for (const v of pick.vals) bits.push(v < pick.thr ? 1 : 0);
for (const v of pick.vals) otsu.push(+(v < pick.thr));
} }
const c = classify(all); const msg = rsDecode(bytesFromBits(bits));
if (!c) return out; return { ...best, vals: undefined, bits: bits.join(""), token: msg ? tokenFromPayload(msg) : null };
// local split first (bands, vignetting), plain per-ring split as a second opinion (strong tilt)
const strict = best.score < 0.92, t = tokenOf(c.bits, c.soft, strict) || tokenOf(otsu, c.soft, strict);
return { ...out, bits: c.bits.join(""), soft: c.soft, token: t ? t.token : null, fixes: t ? t.fixes : null };
} }
// whole frame: find center discs, read the first one that yields a valid token // whole frame: find center discs, read the first one that yields a valid token
export function decodeFrame(img, opts = {}) { export function decodeFrame(img, opts = {}) {
// seed: where the disc was a moment ago, or on a smaller copy of the frame. refit there before searching again const cands = locate(img, opts);
let cands = [];
if (opts.seed) {
const s = opts.seed, k = s.r / CENTER, fit = discFit(img, { cx: s.cx, cy: s.cy, A: s.A || [k, 0, 0, k], r: s.r }), rn = fit && ringness(img, fit);
if (rn) cands = [{ ...fit, ...rn }];
}
if (!cands.length) cands = locate(img, opts);
let last = null; let last = null;
for (const c of cands) { for (const c of cands) {
const r = decodeAt(img, c, opts); const r = decodeAt(img, c, opts);
if (r && r.token) return { ...r, cand: c, found: cands.length }; if (r && r.token) return { ...r, cand: c, found: cands.length };
if (r && (!last || r.score > last.score)) last = { ...r, cand: c }; last = r || last;
} }
return { token: null, found: cands.length, score: last?.score ?? null, soft: last?.soft, cand: last?.cand || cands[0] }; return { token: null, found: cands.length, score: last?.score ?? null };
} }
// frame after frame: adds up the soft bits of frames showing the same code, so a code too noisy
// for one frame still gets through, and keeps tokens in line with the previous ones
export function makeReader(opts = {}) {
let acc = null, frames = 0, anchor = null, pending = null;
const similar = (a, b) => { let s = 0, na = 0, nb = 0; for (let i = 0; i < a.length; i++) { s += a[i] * b[i]; na += a[i] * a[i]; nb += b[i] * b[i]; } return s / Math.sqrt(na * nb || 1); };
// slots only move forward, about 2 per second: a token far from the last one is noise or a replay
// a first token that needed the full rs correction waits for a second one to agree
const gate = (token, now, sure) => {
const slot = +token.slice(1).split(".")[0];
const near = (ref) => { const d = ((slot - ref.slot + 98304) % 65536) - 32768; return d >= -8 && d <= 8 + (now - ref.at) / 100; };
if (anchor ? near(anchor) : sure) { anchor = { slot, at: now }; pending = null; return true; }
if (pending && near(pending)) { anchor = { slot, at: now }; pending = null; return true; }
pending = { slot, at: now };
return false;
};
return {
read(img, now = Date.now(), seed = null) {
const d = decodeFrame(img, { ...opts, seed });
let token = d.token, via = "frame";
if (!token && d.soft && opts.accumulate !== false) {
if (acc && similar(acc, d.soft) > 0.3) { for (let i = 0; i < acc.length; i++) acc[i] += d.soft[i]; frames++; }
else { acc = Float32Array.from(d.soft); frames = 1; }
if (frames > 1) {
const t = tokenOf(Array.from(acc, (v) => +(v > 0)), acc);
// summed frames only get the safe corrections
if (t && t.fixes <= 2) { token = t.token; via = "sum"; }
}
} else if (token) { acc = Float32Array.from(d.soft, (v) => (v > 0 ? 1.5 : -1.5)); frames = 1; }
if (token && opts.gate !== false && !gate(token, now, via === "sum" || d.fixes <= 2)) token = null;
return { ...d, token, via };
},
};
}
// internals for the lab bench
export const _lab = { readRings, sector, bilinear, split, corr, sectorAngle, classify, tokenOf, discConic, mapFromLine, refine };
-70
View File
@@ -1,70 +0,0 @@
// camera side of the ring code: finds the code on a small copy of the frame, then reads it from a crop
// at full sensor resolution. far codes keep every pixel the camera has, and the cost per frame stays flat
import { makeReader, locate, grayOf, CENTER, DISC } from "./ringcode.js";
const WIDE = 960, CROP = 360;
export function makeRingScanner(opts = {}) {
const reader = makeReader(opts);
// no willReadFrequently: it moves the canvas to the cpu, and drawing a video frame into it then copies and
// scales the whole frame in software (2 s per frame for a 4k stream on a mid-range android). on the gpu the
// scaling is free and only these small canvases are read back
const wide = document.createElement("canvas"), wctx = wide.getContext("2d");
const crop = document.createElement("canvas"), cctx = crop.getContext("2d");
let track = null;
// source px of the square around a code of the given unit
function readAt(src, sw, sh, t, now) {
const half = t.unit * (DISC + 0.9);
const x0 = Math.max(0, Math.round(t.cx - half)), y0 = Math.max(0, Math.round(t.cy - half));
const w = Math.min(sw, Math.round(t.cx + half)) - x0, h = Math.min(sh, Math.round(t.cy + half)) - y0;
if (w < 24 || h < 24) return null;
const k = Math.min(1, (opts.crop || CROP) / Math.max(w, h));
crop.width = Math.round(w * k); crop.height = Math.round(h * k);
cctx.imageSmoothingQuality = "high";
cctx.drawImage(src, x0, y0, w, h, 0, 0, crop.width, crop.height);
const seed = { cx: (t.cx - x0) * k - 0.5, cy: (t.cy - y0) * k - 0.5, r: t.unit * CENTER * k, A: t.A && t.A.map((v) => v * k) };
const d = reader.read(grayOf(cctx.getImageData(0, 0, crop.width, crop.height)), now, seed);
if (!d.cand) return null;
// where the code sits in the frame and how big, as fractions: lets the camera zoom in on a small one
const ux = x0 + (d.cand.cx + 0.5) / k, uy = y0 + (d.cand.cy + 0.5) / k, unit = d.cand.r / CENTER / k;
d.where = { x: ux / sw, y: uy / sh, d: (2 * DISC * unit) / Math.min(sw, sh) };
// only a blob with a sync ring keeps the crop alive, anything else goes back to the whole frame
if (!d.token && !d.soft) { track = null; return d; }
track = { cx: ux, cy: uy, unit, A: d.cand.A.map((v) => v / k), at: now };
return d;
}
return {
// src: video or canvas of sw x sh. returns { token, ... } with token null when nothing was read
scan(src, sw, sh, now = performance.now()) {
if (track && now - track.at < 700) {
const d = readAt(src, sw, sh, track, now);
if (d) return d;
}
track = null;
const r = search(src, sw, sh, now, 0, 0, sw, sh);
if (r.token || r.found) return r;
// nothing in the whole view: the back rows see a ring too small to find on the reduced copy. look at the
// middle, where people aim, at twice the detail. same as zooming in, without moving the preview
return search(src, sw, sh, now, sw / 4, sh / 4, sw / 2, sh / 2);
},
};
// finds discs in the region x0 y0 w h of the frame (on a copy of at most WIDE px), reads them at full resolution
function search(src, sw, sh, now, x0, y0, w, h) {
const k = Math.min(1, WIDE / Math.max(w, h));
wide.width = Math.round(w * k); wide.height = Math.round(h * k);
// plain bilinear at 3x reduction skips pixels and keeps the noise
wctx.imageSmoothingQuality = "high";
wctx.drawImage(src, x0, y0, w, h, 0, 0, wide.width, wide.height);
const cands = locate(grayOf(wctx.getImageData(0, 0, wide.width, wide.height)), { max: 5 });
let last = null;
for (const c of cands) {
const d = readAt(src, sw, sh, { cx: x0 + (c.cx + 0.5) / k, cy: y0 + (c.cy + 0.5) / k, unit: c.r / CENTER / k, A: c.A.map((v) => v / k) }, now);
if (d && d.token) return d;
last = d || last;
}
return last || { token: null, found: cands.length };
}
}
+25 -184
View File
@@ -1,184 +1,61 @@
import { $, h, pollId, takeKey, liveSocket, drawQR, resultsView, pct } from "./common.js"; import { $, h, pollId, takeKey, liveSocket, drawQR, resultsView, fill, pct } from "./common.js";
import { render as drawRing, DISC } from "./ringcode.js";
const pid = pollId(); const pid = pollId();
// /present/: duplicated screen, the laptop shows what the projector shows. admin key, admin in a drawer const key = takeKey(`rv_screen_${pid}`);
const present = location.pathname.startsWith("/present/");
const key = takeKey(present ? `rv_present_${pid}` : `rv_screen_${pid}`);
let st = null; let st = null;
let qr = null; // current code message, qr or ring let qr = null;
let raf = 0; let raf = 0;
let entry = null;
let prevBits = null, switchedAt = 0;
let focusView = "";
// shows at once (css plays the entrance), hides after a short exit so blocks don't just vanish
function reveal(el, on) {
if (on) {
clearTimeout(el._leave);
el.classList.remove("leaving");
el.hidden = false;
return;
}
if (el.hidden || el.classList.contains("leaving")) return;
el.classList.add("leaving");
el._leave = setTimeout(() => { el.hidden = true; el.classList.remove("leaving"); }, 220);
}
// restarts a css animation class on an element that stays in the dom
function replay(el, cls) {
el.classList.remove(cls);
void el.offsetWidth;
el.classList.add(cls);
}
// the entry qr jumps between the corner and the big spot: slide and grow it from where it was (flip)
function flip(el, before) {
if (!before || el.hidden || matchMedia("(prefers-reduced-motion: reduce)").matches) return;
const after = el.getBoundingClientRect();
if (!after.width || !after.height) return;
const dx = before.left - after.left, dy = before.top - after.top, sx = before.width / after.width, sy = before.height / after.height;
if (Math.abs(dx) < 2 && Math.abs(dy) < 2 && Math.abs(sx - 1) < 0.02 && Math.abs(sy - 1) < 0.02) return;
el.animate([
{ transformOrigin: "0 0", transform: `translate(${dx}px, ${dy}px) scale(${sx}, ${sy})` },
{ transformOrigin: "0 0", transform: "none" },
], { duration: 600, easing: "cubic-bezier(.2, .7, .2, 1)" });
}
function layout() { function layout() {
if (!st) return; if (!st) return;
const entryEl = $("#entry");
const before = !entryEl.hidden && !entryEl.classList.contains("leaving") ? entryEl.getBoundingClientRect() : null;
// qr stays up while enrolling, and during a vote that needs a presence scan // qr stays up while enrolling, and during a vote that needs a presence scan
const qrOn = st.enrollment_open || st.presence; const qrOn = st.enrollment_open || st.presence;
const ring = st.code_style === "ring"; const focus = st.focus;
// the camera app code: enrolls, and proves presence for a vote, so it stays up whenever the ring does $("#enroll").hidden = !qrOn;
const cam = st.camera_pass !== false; $("#focus").hidden = !focus;
const entryOn = !!(ring && entry && (st.enrollment_open || (cam && st.presence))); $("#idle").hidden = qrOn || !!focus;
// with the big qr on, a vote waiting for scans (or closed with nothing to show) moves above it
const f = st.focus, idleVote = f && f.state === "closed" && !f.results;
// an upright screen has no room for the question above the qr (.entry-q hidden): it keeps its own block
const openVote = cam && f && f.state === "open" && st.presence && !matchMedia("(max-aspect-ratio: 1/1)").matches;
const big = entryOn && st.entry_big && (!f || idleVote || openVote);
const focus = big ? null : f;
reveal($("#enroll"), qrOn);
reveal($("#focus"), !!focus);
reveal($("#idle"), !qrOn && !focus);
$(".s-main").classList.toggle("split", qrOn && !!focus); $(".s-main").classList.toggle("split", qrOn && !!focus);
document.body.classList.toggle("split-on", qrOn && !!focus); $("#qr-title").textContent = st.enrollment_open ? "Inscription" : "Scannez pour voter";
// a vote waiting for presence scans takes the title, even while late arrivals can still enroll
$("#qr-title").textContent = st.presence || !st.enrollment_open ? (ring ? "Visez le cercle pour voter" : "Scannez pour voter") : "Inscription";
$("#qr-steps").hidden = !st.enrollment_open; $("#qr-steps").hidden = !st.enrollment_open;
$("#step1").textContent = ring ? (cam ? "Scannez le QR avec l'appareil photo" : "Ouvrez la page de vote") : "Scannez avec l'appareil photo";
$("#step2").hidden = !ring;
reveal($("#entry"), entryOn);
document.body.classList.toggle("has-entry", entryOn);
document.body.classList.toggle("entry-big", big);
const showQ = big && !!f;
document.body.classList.toggle("entry-q-on", showQ);
$("#entry-q").hidden = !showQ;
// an open vote keeps its options and turnout bar on screen, just above the qr
const opts = showQ && !!openVote;
document.body.classList.toggle("entry-opts-on", opts);
$("#entry-q-opts").hidden = !opts;
$("#entry-q-turnout").hidden = !opts;
$("#entry-q-count").hidden = opts;
if (showQ) {
$("#entry-q-text").textContent = f.text;
if (opts) {
const ul = $("#entry-q-opts"), key = JSON.stringify(f.options);
if (ul.dataset.key !== key) { ul.dataset.key = key; ul.replaceChildren(...f.options.map((o) => h("li", {}, o))); }
paintTurnout($("#entry-q-turnout"), f);
} else {
$("#entry-q-count").textContent = `Vote clos, ${f.participants} bulletin${f.participants > 1 ? "s" : ""}`;
}
}
$("#entry-hint").textContent = cam ? "Scannez avec l'appareil photo" : big ? "Scannez ici, puis visez le cercle" : "Pas encore sur la page ?";
$(".qr-wrap").classList.toggle("ring", ring);
flip(entryEl, before);
} }
function render() { function render() {
$("#s-title").textContent = st.title; $("#s-title").textContent = st.title;
$("#idle-title").textContent = st.title; $("#idle-title").textContent = st.title;
document.title = st.title; document.title = st.title;
if ($("#voters").textContent !== String(st.voters)) { $("#voters").textContent = st.voters;
$("#voters").textContent = st.voters;
replay($("#voters"), "bump");
}
$("#voters-label").textContent = $("#voters-label").textContent =
`inscription${st.voters > 1 ? "s" : ""}` + (st.expected ? ` sur ${st.expected}` : ""); `inscription${st.voters > 1 ? "s" : ""}` + (st.expected ? ` sur ${st.expected}` : "");
$("#secs").textContent = Math.ceil((st.scans_required * st.interval_ms) / 1000); $("#secs").textContent = Math.ceil((st.scans_required * st.interval_ms) / 1000);
const f = st.focus; const f = st.focus;
const box = $("#focus"); const box = $("#focus");
const view = f ? `${f.id}|${f.state}|${f.results ? JSON.stringify(f.results) : 0}|${f.text}` : ""; box.replaceChildren();
if (f && view === focusView && f.state === "open") { if (f) {
// same question still open: only the turnout moves, in place so the bar slides box.append(h("div", { class: "q-text" }, f.text));
paintTurnout(box.querySelector(".turnout"), f); if (f.state === "open") {
} else if (view !== focusView) { box.append(
focusView = view; h("ul", { class: "opts" }, f.options.map((o) => h("li", {}, o))),
if (f) { h("div", { class: "turnout" },
// the old question fades with the section when there is no new one h("b", {}, f.participants), ` vote${f.participants > 1 ? "s" : ""} sur ${st.voters}`,
box.replaceChildren(h("div", { class: "q-text" }, f.text)); h("div", { class: "progress" }, fill(pct(f.participants, st.voters), ""))),
if (f.state === "open") { );
box.append( } else if (f.results) {
h("ul", { class: "opts" }, f.options.map((o) => h("li", {}, o))), box.append(resultsView(f));
paintTurnout(h("div", { class: "turnout" }, } else {
h("b", {}), h("span", { class: "t-of" }), box.append(h("p", { class: "status" }, `Vote clos, ${f.participants} vote${f.participants > 1 ? "s" : ""}`));
h("div", { class: "progress" }, h("div", {}), h("div", { class: "p-extra" }))), f),
);
} else if (f.results) {
box.append(resultsView(f));
} else {
box.append(h("p", { class: "status" }, `Vote clos, ${f.participants} vote${f.participants > 1 ? "s" : ""}`));
}
replay(box, "enter");
} }
} }
layout(); layout();
} }
// "9 votes sur 10, dont 3 ajoutés": hand-added votes count in, and show hatched at the end of the bar
function paintTurnout(t, f) {
const extra = f.extra_ballots || 0, all = f.participants + extra, of = st.voters + extra;
t.querySelector("b").textContent = all;
t.querySelector(".t-of").textContent = ` vote${all > 1 ? "s" : ""} sur ${of}` +
(extra ? `, dont ${extra} ajouté${extra > 1 ? "s" : ""}` : "");
const [phone, added] = t.querySelectorAll(".progress > div");
phone.style.width = `${pct(f.participants, of)}%`;
added.style.width = `${pct(extra, of)}%`;
return t;
}
function paintQR() { function paintQR() {
if (!qr || qr.type !== "qr") return; if (!qr) return;
const c = $("#qr"); const c = $("#qr");
const px = Math.min(c.clientWidth || 600, c.clientHeight || 600) * (window.devicePixelRatio || 1); const px = Math.min(c.clientWidth || 600, c.clientHeight || 600) * (window.devicePixelRatio || 1);
drawQR(c, qr.modules, px); drawQR(c, qr.modules, px);
} }
function paintEntry() {
if (!entry) return;
drawQR($("#entry-qr"), entry.modules, 220 * (window.devicePixelRatio || 1));
$("#entry-url").textContent = entry.url.replace(/^https?:\/\//, "");
}
// rings rotate continuously (one turn every 45 s); changed dashes cross-fade when the code switches
function ringLoop(t) {
if (!qr || qr.type !== "ring") return;
const c = $("#qr"), dpr = window.devicePixelRatio || 1;
const size = Math.round(Math.min(c.clientWidth || 600, c.clientHeight || 600) * dpr);
if (c.width !== size) { c.width = c.height = size; }
const ctx = c.getContext("2d");
ctx.clearRect(0, 0, size, size);
const fadeMs = Math.min(700, qr.interval_ms * 0.7);
const k = prevBits ? Math.min(1, (t - switchedAt) / fadeMs) : 1;
drawRing(ctx, size / 2, size / 2, (size / 2) / DISC * 0.98, (t / 1000) * (2 * Math.PI / 45), qr.bits, t / 1000,
prevBits ? { from: prevBits, k, seed: qr.slot } : null);
requestAnimationFrame(ringLoop);
}
function animateTick() { function animateTick() {
cancelAnimationFrame(raf); cancelAnimationFrame(raf);
const bar = $("#tick-bar"); const bar = $("#tick-bar");
@@ -192,7 +69,7 @@ function animateTick() {
} }
let skew = 0; let skew = 0;
window.addEventListener("resize", () => { paintQR(); layout(); }); window.addEventListener("resize", paintQR);
$("#fs").addEventListener("click", () => document.documentElement.requestFullscreen?.()); $("#fs").addEventListener("click", () => document.documentElement.requestFullscreen?.());
@@ -203,18 +80,6 @@ liveSocket(`/ws/${pid}/screen`, {
st = msg; st = msg;
if (!st.enrollment_open && !st.presence) qr = null; if (!st.enrollment_open && !st.presence) qr = null;
render(); render();
} else if (msg.type === "entry") {
entry = msg;
paintEntry();
if (st) layout();
} else if (msg.type === "ring") {
skew = Date.now() - msg.slot * msg.interval_ms;
const wasRing = qr && qr.type === "ring";
prevBits = wasRing ? qr.bits : null;
switchedAt = performance.now();
qr = msg;
if (!wasRing) requestAnimationFrame(ringLoop);
animateTick();
} else if (msg.type === "qr") { } else if (msg.type === "qr") {
// server clock drives validity, estimate offset so the countdown bar is right // server clock drives validity, estimate offset so the countdown bar is right
skew = Date.now() - msg.slot * msg.interval_ms; skew = Date.now() - msg.slot * msg.interval_ms;
@@ -240,27 +105,3 @@ liveSocket(`/ws/${pid}/screen`, {
if (s !== "online") { qr = null; const cv = $("#qr"); cv.getContext("2d").clearRect(0, 0, cv.width, cv.height); } if (s !== "online") { qr = null; const cv = $("#qr"); cv.getContext("2d").clearRect(0, 0, cv.width, cv.height); }
}, },
}); });
if (present) {
const btn = h("button", { class: "small ctl-btn", type: "button", "aria-expanded": "false" }, "Gérer");
const close = h("button", { class: "small", type: "button" }, "Fermer");
const drawer = h("aside", { class: "ctl", "aria-label": "Gestion du scrutin" },
h("div", { class: "ctl-head" }, h("b", {}, "Gestion"), close));
document.body.append(drawer);
$(".s-tools").prepend(btn);
const toggle = (open) => {
// the admin page loads on first open only, and keeps its state when the drawer closes
if (open && !drawer.querySelector("iframe")) {
drawer.append(h("iframe", { src: `/admin/${pid}#${encodeURIComponent(key)}`, title: "Administration" }));
}
// the projection folds into the room the drawer leaves, the entry qr slides along
const entryEl = $("#entry"), before = entryEl.hidden ? null : entryEl.getBoundingClientRect();
drawer.classList.toggle("open", open);
document.body.classList.toggle("ctl-open", open);
btn.setAttribute("aria-expanded", String(open));
flip(entryEl, before);
};
btn.addEventListener("click", () => toggle(!drawer.classList.contains("open")));
close.addEventListener("click", () => toggle(false));
document.addEventListener("keydown", (e) => { if (e.key === "Escape") toggle(false); });
}
+44 -379
View File
@@ -1,22 +1,12 @@
import { $, h, api, pollId, liveSocket, resultsView, toast, paintRing, icon } from "./common.js"; import { $, h, api, pollId, liveSocket, resultsView, toast, ring, icon } from "./common.js";
import { makeRingScanner } from "./ringscan.js";
const pid = pollId(); const pid = pollId();
const DONE_KEY = `rv_done_${pid}`; const DONE_KEY = `rv_done_${pid}`;
const apiBase = `/api/v/${pid}`; const apiBase = `/api/v/${pid}`;
const PENDING_KEY = `rv_pending_${pid}`; // token from the QR that opened this page, then drop it from the url bar so it isn't shared
const ARRIVED_KEY = `rv_arrived_${pid}`; const firstToken = decodeURIComponent(location.hash.slice(1));
const VIA_QR = "Avec la caméra native via le QR";
// the camera app redirect leaves a one-time claim (or why there is none) in the hash. off the url bar at once
const hash = new URLSearchParams(location.hash.slice(1));
const claim = hash.get("c"), camExpired = hash.get("cam") === "expired";
if (location.hash) history.replaceState(null, "", location.pathname); if (location.hash) history.replaceState(null, "", location.pathname);
// a camera app scan covers votes for a few seconds (server PASS_HOLD_MS, minus the round trip)
let passUntil = 0;
let presenceFor = null;
let camPass = true; // organizers can turn the camera app way off
let scanner = null; let scanner = null;
let required = 5; let required = 5;
@@ -25,8 +15,6 @@ const sent = new Set();
const selections = new Map(); const selections = new Map();
let queue = Promise.resolve(); let queue = Promise.resolve();
let lastState = null; let lastState = null;
let codeStyle = "qr"; // what the projector shows: rotating qr or ring code
let qrEngine = null;
let lastJson = ""; let lastJson = "";
function show(id) { function show(id) {
@@ -43,13 +31,9 @@ function lsGet(k) { try { return localStorage.getItem(k); } catch { return null;
function lsSet(k, v) { try { localStorage.setItem(k, v); } catch { /* private mode */ } } function lsSet(k, v) { try { localStorage.setItem(k, v); } catch { /* private mode */ } }
// the segment fill in app.css takes .5 s, plus a beat to see the ring complete
const FILL_MS = 650;
let landing = false;
function renderDots(n) { function renderDots(n) {
const box = $("#dots"); const box = $("#dots");
paintRing(box, n, required, 150); box.replaceChildren(ring(n, required, 150));
box.setAttribute("aria-label", `${n} codes lus sur ${required}`); box.setAttribute("aria-label", `${n} codes lus sur ${required}`);
} }
@@ -59,25 +43,6 @@ function scanMsg(text, kind = "") {
m.className = `scan-msg ${kind || "muted"}`; m.className = `scan-msg ${kind || "muted"}`;
} }
// the camera app way: a quiet line under a working scanner, step by step without one.
// people are already on the page, so it has to say why they leave it and what happens after
function camAlt(el, solo, vote = false) {
el.hidden = !camPass;
el.classList.toggle("solo", solo);
if (!solo) {
el.replaceChildren(icon("camera", 18), h("span", {}, "Ça ne marche pas ? Rouvrez votre scanneur de code QR et scannez le grand QR."));
return;
}
// "re-open": the same scanner that brought them here, not something new to find
// the vote dialog has the heading in its own title
el.replaceChildren(icon("camera", 36), vote ? "" : h("b", {}, "Confirmez avec votre scanneur de code QR"),
h("ol", {},
h("li", {}, "Rouvrez votre scanneur de code QR, celui qui vous a amené·e ici."),
h("li", {}, "Scannez le grand QR de l'écran."),
// joining only takes a code that left the screen less than 4 s ago
h("li", {}, vote ? "Touchez le lien qui s'affiche. Votre vote part tout seul." : "Touchez tout de suite le lien qui s'affiche. Vous êtes inscrit·e.")));
}
async function startScanner() { async function startScanner() {
if (scanner) return; if (scanner) return;
if (!window.isSecureContext) { if (!window.isSecureContext) {
@@ -85,12 +50,10 @@ async function startScanner() {
return; return;
} }
$("#cam-box").hidden = false; $("#cam-box").hidden = false;
scanner = makeScanner($("#video"), onScan, () => scanMsg("QR d'un autre scrutin.", "bad")); scanner = makeScanner($("#video"), onScan);
try { try {
await scanner.start(); await scanner.start();
$("#start-cam").hidden = true; $("#start-cam").hidden = true;
$("#dots").hidden = false;
camAlt($("#enroll-alt"), false);
scanMsg(""); scanMsg("");
navigator.wakeLock?.request("screen").catch(() => {}); navigator.wakeLock?.request("screen").catch(() => {});
} catch (e) { } catch (e) {
@@ -98,183 +61,32 @@ async function startScanner() {
scanner.destroy(); scanner.destroy();
scanner = null; scanner = null;
$("#cam-box").hidden = true; $("#cam-box").hidden = true;
// the camera app is the way now: the ring and a big retry button would only compete with it
$("#dots").hidden = true;
$("#start-cam").hidden = false; $("#start-cam").hidden = false;
$("#start-cam").className = "link"; scanMsg("Autorisez la caméra puis réessayez.", "bad");
$("#start-cam").textContent = "Réessayer la caméra";
scanMsg(camError(e), "bad");
camAlt($("#enroll-alt"), true);
} }
} }
// what blocked the camera. no settings walkthrough: the camera app path below works without them function makeScanner(video, onData) {
function camError(e) { return new window.QrScanner(video, (r) => onData(r.data), {
switch (e && e.name) { returnDetailedScanResult: true,
case "NotAllowedError": preferredCamera: "environment",
case "SecurityError": maxScansPerSecond: 15,
return "Ce navigateur n'a pas accès à la caméra."; // whole frame, the projected code is often small and off-center
case "NotReadableError": calculateScanRegion: (v) => {
case "AbortError": const w = Math.min(960, v.videoWidth);
return "Caméra occupée ou bloquée par le téléphone."; return { x: 0, y: 0, width: v.videoWidth, height: v.videoHeight,
case "NotFoundError": downScaledWidth: w, downScaledHeight: Math.round((w * v.videoHeight) / v.videoWidth) };
case "OverconstrainedError":
return "Aucune caméra trouvée.";
default:
return "Caméra indisponible.";
}
}
// own camera loop: decodes the ring code, or the classic qr through qr-scanner's engine.
// calls onToken(token) for every code of this poll it reads
function makeScanner(video, onToken, onOther) {
let stream = null, running = false;
const canvas = document.createElement("canvas"), ctx = canvas.getContext("2d");
const rings = makeRingScanner();
async function loop() {
if (!running) return;
const t0 = performance.now();
if (video.readyState >= 2 && video.videoWidth) {
try {
if (codeStyle === "ring") {
// reads a crop at sensor resolution: a far code keeps all its pixels
const ts = performance.now(), d = rings.scan(video, video.videoWidth, video.videoHeight);
if (d.token) onToken(d.token);
steer(d);
pace(performance.now() - ts);
} else {
// 960 px is plenty for a qr and keeps low-end phones near 7 fps
const k = Math.min(1, 960 / video.videoWidth);
canvas.width = Math.round(video.videoWidth * k);
canvas.height = Math.round(video.videoHeight * k);
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
qrEngine ||= await window.QrScanner.createQrEngine();
const r = await window.QrScanner.scanImage(canvas, { qrEngine, returnDetailedScanResult: true }).catch(() => null);
if (r) { const tok = tokenOf(r.data); if (tok) onToken(tok); else onOther?.(); }
}
} catch (e) { console.warn(e); }
}
// ~15 fps cap, saves battery on fast phones
setTimeout(loop, Math.max(0, 66 - (performance.now() - t0)));
}
const swap = h("button", { class: "cam-switch", type: "button", "aria-label": "Changer de caméra", hidden: true }, icon("swap", 20));
// sensor zoom, by hand only: an automatic one made the preview jump and shook too much on cheap phones.
// the far ring gets its pixels from the full sensor resolution instead (openCamera, ringscan)
const zoom = h("button", { class: "cam-zoom", type: "button", "aria-label": "Zoom", hidden: true }, "1×");
video.parentElement.append(swap, zoom);
let zs = null;
function setZoom(z) {
const track = stream?.getVideoTracks()[0];
if (!track || !zs) return;
zs.now = z;
zoom.textContent = `${(Math.round(z * 10) / 10).toLocaleString("fr-FR")}×`;
track.applyConstraints({ advanced: [{ zoom: z }] }).catch(() => { zs = null; zoom.hidden = true; });
}
// a slow phone reads few frames and misses codes: past ~300 ms a frame, drop the stream to 720p once
let slow = 0, frames = 0, dropped = false;
function pace(ms) {
slow = frames++ ? slow * 0.8 + ms * 0.2 : ms;
if (dropped || frames < 6 || slow < 300 || video.videoWidth * video.videoHeight <= 1280 * 720) return;
dropped = true;
stream?.getVideoTracks()[0]?.applyConstraints({ width: { ideal: 1280 }, height: { ideal: 720 } }).catch(() => {});
}
function steer(d) {
// people keep their seat between votes: a zoom that read the ring is where the next scan starts
if (zs && d.token) lsSet(ZOOM_KEY, String(zs.now));
}
async function attach(s) {
stream = s;
const track = s.getVideoTracks()[0];
// not every browser knows focusMode, those ignore it
track?.applyConstraints({ advanced: [{ focusMode: "continuous" }] }).catch(() => {});
const cap = track?.getCapabilities?.().zoom;
zs = cap && cap.max >= 1.5 ? { base: Math.max(1, cap.min), max: Math.min(cap.max, 3), now: Math.max(1, cap.min) } : null;
zoom.hidden = !zs;
zoom.textContent = "1×";
video.srcObject = s;
await video.play();
const saved = +lsGet(ZOOM_KEY);
if (zs && saved > zs.base) setZoom(Math.min(zs.max, saved));
}
zoom.onclick = () => {
if (!zs) return;
const steps = [zs.base, 2, 3].filter((z) => z >= zs.base && z <= zs.max);
setZoom(steps.find((z) => z > zs.now + 0.05) ?? zs.base);
};
swap.onclick = async () => {
const cams = rankCameras(await videoInputs());
if (cams.length < 2) return;
const cur = stream?.getVideoTracks()[0]?.getSettings().deviceId;
const next = cams[(cams.findIndex((d) => d.deviceId === cur) + 1) % cams.length];
stream?.getTracks().forEach((t) => t.stop());
try { await attach(await openCamera(next.deviceId)); lsSet(CAM_KEY, next.deviceId); }
catch { await attach(await openCamera(null)); }
};
return {
async start() {
const saved = lsGet(CAM_KEY);
let s = null;
if (saved) s = await openCamera(saved).catch(() => null);
s ||= await openCamera(null);
// some browsers ignore facingMode or hand over the ultra wide: switch to the main back lens when labels say so
const track = s.getVideoTracks()[0], cams = await videoInputs();
if (!saved && cams.length > 1 && (track.getSettings().facingMode === "user" || !isMainBack(track.label))) {
const best = rankCameras(cams)[0];
if (best && best.deviceId !== track.getSettings().deviceId) {
s.getTracks().forEach((t) => t.stop());
s = await openCamera(best.deviceId).catch(() => null) || await openCamera(null);
}
}
swap.hidden = cams.length < 2;
await attach(s);
running = true;
loop();
}, },
stop() {
running = false;
stream?.getTracks().forEach((t) => t.stop());
video.srcObject = null;
},
destroy() { swap.remove(); zoom.remove(); },
};
}
const CAM_KEY = "rv_cam";
const ZOOM_KEY = `rv_zoom_${pid}`;
const FRONT = /front|user|avant|facetime|selfie/i, ODD = /ultra|wide|grand.angle|macro|tele|télé|depth|infra|dual|triple|double/i, BACK = /back|rear|arri[eè]re|environment/i;
function openCamera(deviceId) {
// rings from the back of a room are a few dozen pixels wide at 720p. 4k was tried: a mid-range android took
// it and fell to one frame every 2 s, so 1080p, and 720p on phones too slow for that (pace)
const [w, h] = codeStyle === "ring" ? [1920, 1080] : [1280, 720];
const base = { width: { ideal: w }, height: { ideal: h } };
return navigator.mediaDevices.getUserMedia({
audio: false, video: deviceId ? { ...base, deviceId: { exact: deviceId } } : { ...base, facingMode: { ideal: "environment" } },
}); });
} }
async function videoInputs() {
try { return (await navigator.mediaDevices.enumerateDevices()).filter((d) => d.kind === "videoinput"); }
catch { return []; }
}
// without a label we can't tell, so trust what facingMode gave
const isMainBack = (label) => !label || (!FRONT.test(label) && !ODD.test(label));
// main back lens first, other back lenses next, front last. android lists its main back camera first
function rankCameras(cams) {
const score = (d) => (FRONT.test(d.label) ? -4 : 0) + (ODD.test(d.label) ? -2 : 0) + (BACK.test(d.label) ? 1 : 0);
return cams.map((d, i) => ({ d, i, s: score(d) })).sort((a, b) => b.s - a.s || a.i - b.i).map((x) => x.d);
}
// token of a code shown for this poll, null for anything else // token of a code shown for this poll, null for anything else
// the classic qr is the camera app code: /V/<poll>/<code>, upper case
function tokenOf(data) { function tokenOf(data) {
let u; let u;
try { u = new URL(data); } catch { return null; } try { u = new URL(data); } catch { return null; }
const [v, id, tok] = u.pathname.split("/").filter(Boolean); const parts = u.pathname.split("/").filter(Boolean);
if (v?.toLowerCase() !== "v" || id?.toLowerCase() !== pid || !tok) return null; if (parts[0] !== "v" || parts[1] !== pid) return null;
return tok; return decodeURIComponent(u.hash.slice(1)) || null;
} }
function stopScanner() { function stopScanner() {
@@ -285,56 +97,15 @@ function stopScanner() {
$("#cam-box").hidden = true; $("#cam-box").hidden = true;
} }
function onScan(token) { function onScan(data) {
if (landing || sent.has(token)) return; const token = tokenOf(data);
sent.add(token); if (!token) {
if (codeStyle === "qr") redeem({ token }).then(afterPass); scanMsg("QR d'un autre scrutin.", "bad");
else submitToken(token); return;
}
async function redeem(body) {
try { return await api("POST", `${apiBase}/pass`, body); }
catch { return { status: "network" }; }
}
function pendingVote() {
let p;
try { p = JSON.parse(lsGet(PENDING_KEY)); } catch { return null; }
return p && Date.now() - p.at < 5 * 60e3 ? p : null;
}
// what one camera app scan gave: enrolled, votes covered for a moment, or why not
async function afterPass(r) {
switch (r.status) {
case "enrolled":
passUntil = Date.now() + 8000;
enrolled(true);
break;
case "pass": {
passUntil = Date.now() + (r.hold_ms || 10000) - 1500;
// the choice made before going to the camera app goes through on its own
const p = pendingVote();
const q = p && lastState?.questions.find((x) => x.id === p.qid && x.state === "open" && !x.voted);
if (q) castVote(q, p.choices);
break;
}
case "need_code":
stopScanner();
show("#v-code");
break;
case "closed":
if (!lastState) block("Inscriptions closes. Inscrit·e dans un autre navigateur ? Revenez-y pour voter.");
break;
case "full":
block("Nombre maximal d'inscriptions atteint.");
break;
case "expired":
toast("QR expiré, scannez-le à nouveau.", "bad");
break;
case "late":
toast("Lien ouvert trop tard. Rescannez et touchez le lien tout de suite.", "bad");
break;
} }
if (sent.has(token)) return;
sent.add(token);
submitToken(token);
} }
function submitToken(token) { function submitToken(token) {
@@ -361,11 +132,7 @@ function handleScan(r) {
$("#code").focus(); $("#code").focus();
break; break;
case "enrolled": case "enrolled":
// the 5th code answers "enrolled" straight away: fill the last segment and let it land first enrolled();
if (landing) break;
landing = true;
renderDots(required);
setTimeout(() => { landing = false; enrolled(); }, FILL_MS);
break; break;
case "closed": case "closed":
block("Inscriptions closes."); block("Inscriptions closes.");
@@ -376,45 +143,13 @@ function handleScan(r) {
} }
} }
function enrolled(viaCam = false) { function enrolled() {
stopScanner(); stopScanner();
lsSet(DONE_KEY, "1"); lsSet(DONE_KEY, "1");
navigator.vibrate?.([40, 60, 40]); navigator.vibrate?.([40, 60, 40]);
celebrate("Inscription validée", viaCam ? VIA_QR : "");
boot(); boot();
} }
// the projector's center mark with its check, drawn in, held a moment, then gone
const MARK_NS = "http://www.w3.org/2000/svg";
function mark(withTick) {
const svg = document.createElementNS(MARK_NS, "svg");
svg.setAttribute("viewBox", "0 0 32 32");
svg.setAttribute("aria-hidden", "true");
const g = document.createElementNS(MARK_NS, "g");
g.setAttribute("transform", "rotate(-90 16 16)");
for (const [stroke, dash] of [["currentColor", "4.52 7"], ["#ffcc00", "4.52 64.6"]]) {
const c = document.createElementNS(MARK_NS, "circle");
for (const [k, v] of Object.entries({ cx: 16, cy: 16, r: 11, fill: "none", stroke, "stroke-width": 5,
"stroke-linecap": "round", "stroke-dasharray": dash, "stroke-dashoffset": -3.5 })) c.setAttribute(k, v);
g.append(c);
}
const tick = document.createElementNS(MARK_NS, "path");
for (const [k, v] of Object.entries({ d: "M12.8 16.15l2.3 2.3 4.25-4.75", fill: "none", stroke: "currentColor", "stroke-width": 2.4,
"stroke-linecap": "round", "stroke-linejoin": "round", pathLength: 1, class: "tick" })) tick.setAttribute(k, v);
svg.append(g);
if (withTick) svg.append(tick);
return svg;
}
function celebrate(text, sub = "") {
const el = h("div", { class: "celebrate", role: "status" }, mark(true), h("p", {}, text), sub ? h("small", {}, sub) : "");
document.body.append(el);
// a second line takes longer to read
const hold = sub ? 2000 : 1300;
setTimeout(() => el.classList.add("out"), hold);
setTimeout(() => el.remove(), hold + 400);
}
$("#start-cam").addEventListener("click", startScanner); $("#start-cam").addEventListener("click", startScanner);
$("#no-cam").addEventListener("click", () => { stopScanner(); show("#v-rescue"); $("#rescue-code").focus(); }); $("#no-cam").addEventListener("click", () => { stopScanner(); show("#v-rescue"); $("#rescue-code").focus(); });
@@ -467,9 +202,6 @@ function sel(qid) {
function renderVote(st) { function renderVote(st) {
lastState = st; lastState = st;
// voted from the tab the camera app opened: nothing left to scan here
if (presenceFor && st.questions.some((q) => q.id === presenceFor && q.voted)) $("#presence").close();
if (st.code_style) codeStyle = st.code_style;
const box = $("#questions"); const box = $("#questions");
box.replaceChildren(); box.replaceChildren();
let pending = 0; let pending = 0;
@@ -535,34 +267,17 @@ async function confirmVote(q) {
dlg.showModal(); dlg.showModal();
await new Promise((res) => dlg.addEventListener("close", res, { once: true })); await new Promise((res) => dlg.addEventListener("close", res, { once: true }));
if (dlg.returnValue !== "ok") return; if (dlg.returnValue !== "ok") return;
castVote(q, s.blank ? [] : choices);
}
async function castVote(q, choices, retried = false) {
let presence; let presence;
if (lastState.vote_scans > 0 && Date.now() > passUntil) { if (lastState.vote_scans > 0) {
// kept for the tab the camera app opens, which sends it on its own presence = await collectPresence(lastState.vote_scans);
if (camPass) lsSet(PENDING_KEY, JSON.stringify({ qid: q.id, choices, at: Date.now() })); if (!presence) return;
presence = await collectPresence(lastState.vote_scans, q.id);
// cancelled (or voted from the other tab): a later scan must not cast a choice left behind
if (!presence) {
try { localStorage.removeItem(PENDING_KEY); } catch { /* private mode */ }
return;
}
} }
try { try {
await api("POST", `${apiBase}/vote`, { question_id: q.id, choices, presence }); await api("POST", `${apiBase}/vote`, { question_id: q.id, choices: s.blank ? [] : choices, presence });
try { localStorage.removeItem(PENDING_KEY); } catch { /* private mode */ }
selections.delete(q.id); selections.delete(q.id);
// no codes sent while some were due: the camera app scan covered it toast("Vote enregistré", "ok");
celebrate("Vote enregistré", !presence && lastState.vote_scans > 0 ? VIA_QR : "");
navigator.vibrate?.(60); navigator.vibrate?.(60);
} catch (e) { } catch (e) {
// the camera app scan ran out on the server side: scan again
if (e.code === "presence_required" && !presence && !retried) {
passUntil = 0;
return castVote(q, choices, true);
}
const m = { already_voted: "Déjà voté.", not_open: "Vote clos.", not_enrolled: "Appareil non inscrit.", const m = { already_voted: "Déjà voté.", not_open: "Vote clos.", not_enrolled: "Appareil non inscrit.",
presence_required: "Scan expiré, revotez en visant l'écran." }; presence_required: "Scan expiré, revotez en visant l'écran." };
toast(m[e.code] || `Erreur : ${e.message}`, "bad"); toast(m[e.code] || `Erreur : ${e.message}`, "bad");
@@ -571,62 +286,33 @@ async function castVote(q, choices, retried = false) {
// proof of presence at vote time: read n distinct codes off the projector, resolve with them // proof of presence at vote time: read n distinct codes off the projector, resolve with them
// (or null if cancelled). the server checks freshness // (or null if cancelled). the server checks freshness
function collectPresence(n, qid) { function collectPresence(n) {
const dlg = $("#presence"); const dlg = $("#presence");
const got = []; const got = [];
// the classic qr is the camera app code: one read is enough, the server then covers the vote const paint = () => $("#p-ring").replaceChildren(ring(got.length, n, 120));
if (codeStyle === "qr") n = 1;
const paint = () => paintRing($("#p-ring"), got.length, n, 120);
paint(); paint();
$("#p-title").textContent = codeStyle === "ring" ? "Visez le cercle" : "Scannez le QR";
$("#p-scan").hidden = false;
$("#p-msg").textContent = ""; $("#p-msg").textContent = "";
camAlt($("#p-alt"), false);
presenceFor = qid;
dlg.showModal(); dlg.showModal();
const seenAt = new Map(), tried = new Set(); const sc = makeScanner($("#p-video"), (data) => {
const sc = makeScanner($("#p-video"), async (t) => { const t = tokenOf(data);
if (got.length >= n || got.includes(t)) return; if (!t || got.includes(t)) return;
if (codeStyle === "qr") {
if (tried.has(t)) return;
tried.add(t);
const r = await redeem({ token: t });
if (r.status === "pass" && !got.length) { got.push(t); paint(); setTimeout(() => finish([]), FILL_MS); }
return;
}
// the server takes codes spread over ~8 s + n intervals: on a slow phone the oldest ones lapse, drop them
const now = performance.now();
while (got.length && now - seenAt.get(got[0]) > 9000) got.shift();
got.push(t); got.push(t);
seenAt.set(t, now);
paint(); paint();
navigator.vibrate?.(15); navigator.vibrate?.(15);
if (got.length >= n) setTimeout(() => finish(got), FILL_MS); if (got.length >= n) finish(got);
}); });
let done, finished = false; let done, finished = false;
const result = new Promise((res) => { done = res; }); const result = new Promise((res) => { done = res; });
function finish(value) { function finish(value) {
if (finished) return; if (finished) return;
finished = true; finished = true;
presenceFor = null;
sc.stop(); sc.stop();
sc.destroy(); sc.destroy();
if (dlg.open) dlg.close(); if (dlg.open) dlg.close();
done(value); done(value);
} }
dlg.addEventListener("close", () => finish(null), { once: true }); dlg.addEventListener("close", () => finish(null), { once: true });
// no camera here: the camera app opens a new tab that sends the kept choice sc.start().catch(() => { $("#p-msg").textContent = "Autorisez la caméra puis réessayez."; });
sc.start().catch((e) => {
$("#p-scan").hidden = true;
if (!camPass) {
// no camera and no camera app way: the desk can still count this vote by hand (votes en plus)
$("#p-msg").textContent = `${camError(e)} Sinon, signalez-vous à la tribune.`;
return;
}
$("#p-title").textContent = "Validez avec votre scanneur de code QR";
$("#p-msg").textContent = camError(e);
camAlt($("#p-alt"), true, true);
});
return result; return result;
} }
@@ -643,7 +329,6 @@ function connect() {
lastJson = j; lastJson = j;
show("#v-vote"); show("#v-vote");
$("#title").textContent = msg.title; $("#title").textContent = msg.title;
camPass = msg.camera_pass !== false;
renderVote(msg); renderVote(msg);
} }
else if (msg.type === "not_enrolled") { socket?.close(); socket = null; boot(); } else if (msg.type === "not_enrolled") { socket?.close(); socket = null; boot(); }
@@ -668,8 +353,6 @@ async function boot() {
} }
$("#title").textContent = me.title; $("#title").textContent = me.title;
document.title = me.title; document.title = me.title;
camPass = me.camera_pass !== false;
camAlt($("#enroll-alt"), $("#enroll-alt").classList.contains("solo"));
if (me.enrolled) { if (me.enrolled) {
lsSet(DONE_KEY, "1"); lsSet(DONE_KEY, "1");
show("#v-vote"); show("#v-vote");
@@ -682,31 +365,13 @@ async function boot() {
return block("Appareil déjà inscrit à ce scrutin (accès perdu). Adressez-vous à l'équipe organisatrice."); return block("Appareil déjà inscrit à ce scrutin (accès perdu). Adressez-vous à l'équipe organisatrice.");
} }
if (!me.enrollment_open) return block("Inscriptions closes."); if (!me.enrollment_open) return block("Inscriptions closes.");
codeStyle = me.code_style || "qr"; required = me.scans_required;
// the classic qr is read once (camera app code), the ring several times
required = codeStyle === "qr" ? 1 : me.scans_required;
if (me.need_code) { show("#v-code"); return; } if (me.need_code) { show("#v-code"); return; }
startEnroll(me.count); startEnroll(me.count);
if (firstToken && !sent.has(firstToken)) { sent.add(firstToken); submitToken(firstToken); }
} }
async function start() { boot();
await boot();
// the scan that brings someone here only opens the page: joining takes the ring, or a second scan
const arrived = +lsGet(ARRIVED_KEY) > Date.now() - 3 * 3600e3;
if (claim && (lastState || arrived)) {
// the check takes a few ms: held a second so people see their scan was taken and checked
const wait = h("div", { class: "celebrate verifying", role: "status" }, mark(false), h("p", {}, "Vérification"));
document.body.append(wait);
const [r] = await Promise.all([redeem({ claim }), new Promise((res) => setTimeout(res, 1000))]);
wait.remove();
afterPass(r);
}
else if (camExpired) afterPass({ status: "expired" });
if (!lastState) lsSet(ARRIVED_KEY, String(Date.now()));
}
camAlt($("#enroll-alt"), false);
start();
// a socket can look open after sleep while being dead, so refetch on wake // a socket can look open after sleep while being dead, so refetch on wake
document.addEventListener("visibilitychange", () => { document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "visible" && lastState) boot(); if (document.visibilityState === "visible" && lastState) boot();
-21
View File
@@ -1,21 +0,0 @@
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>RotatyVote · Résultats</title>
<link rel="icon" href="/static/img/mark.svg" type="image/svg+xml">
<link rel="stylesheet" href="/static/css/app.css">
<script type="module" src="/static/js/results.js"></script>
</head>
<body>
<main class="wrap narrow results-page">
<div class="topbar">
<span class="brand"><img src="/static/img/mark.svg" alt=""><span>rotaty<b>vote</b></span></span>
</div>
<h1 id="title">Résultats</h1>
<p id="denied" class="notice bad" hidden>Lien invalide ou désactivé.</p>
<div id="list"></div>
</main>
</body>
</html>
+2 -4
View File
@@ -5,8 +5,6 @@
<script type="module"> <script type="module">
import { render, decodeFrame, grayOf, locate, decodeAt, DISC } from "/static/js/ringcode.js"; import { render, decodeFrame, grayOf, locate, decodeAt, DISC } from "/static/js/ringcode.js";
import * as RC from "/static/js/ringcode.js"; import * as RC from "/static/js/ringcode.js";
import "/static/ringlab/far.js";
import * as V1 from "/static/ringlab/ringcode_v1.js";
// warps canvas `src` onto a new w x h canvas so that src's unit square maps to quad `dst` (perspective) // warps canvas `src` onto a new w x h canvas so that src's unit square maps to quad `dst` (perspective)
function warp(src, dst, w, h, bg) { function warp(src, dst, w, h, bg) {
@@ -88,7 +86,7 @@ window.runBench = async (cfg) => {
clutter(sctx, 960, 720, rnd); clutter(sctx, 960, 720, rnd);
if (!trial.nocode) { if (!trial.nocode) {
actx.clearRect(0, 0, A.width, A.height); actx.clearRect(0, 0, A.width, A.height);
(cfg.v1 ? V1.render : render)(actx, A.width / 2, A.height / 2, A.width / (2 * DISC), trial.theta, trial.bits, trial.anim); render(actx, A.width / 2, A.height / 2, A.width / (2 * DISC), trial.theta, trial.bits, trial.anim);
const q = quad(480 + trial.dx, 360 + trial.dy, trial.d, trial.tilt, trial.axis, trial.dist || 3.5); const q = quad(480 + trial.dx, 360 + trial.dy, trial.d, trial.tilt, trial.axis, trial.dist || 3.5);
sctx.drawImage(warp(A, q, 960, 720), 0, 0); sctx.drawImage(warp(A, q, 960, 720), 0, 0);
} }
@@ -101,7 +99,7 @@ window.runBench = async (cfg) => {
cctx.putImageData(id, 0, 0); cctx.putImageData(id, 0, 0);
} }
const t0 = performance.now(); const t0 = performance.now();
const d = (cfg.v1 ? V1.decodeFrame : decodeFrame)(grayOf(cctx.getImageData(0, 0, 960, 720))); const d = decodeFrame(grayOf(cctx.getImageData(0, 0, 960, 720)));
const out = { found: d.found, token: d.token, score: d.score == null ? null : +d.score.toFixed(3), ms: Math.round(performance.now() - t0) }; const out = { found: d.found, token: d.token, score: d.score == null ? null : +d.score.toFixed(3), ms: Math.round(performance.now() - t0) };
out.ok = trial.nocode ? !d.token : d.token === trial.token; out.ok = trial.nocode ? !d.token : d.token === trial.token;
if (d.bits && !trial.nocode) { if (d.bits && !trial.nocode) {
-193
View File
@@ -1,193 +0,0 @@
// far / low contrast bench: stills with per-stage diagnosis, and timed sequences
import * as RC from "/static/js/ringcode.js";
import { lcg, makeRoom, frame, jpeg, design } from "/static/ringlab/synth.js";
import * as V1 from "/static/ringlab/ringcode_v1.js";
import { makeRingScanner } from "/static/js/ringscan.js";
window.makeRingScanner = makeRingScanner;
const { decodeFrame, grayOf, locate, decodeAt, RADII, CENTER, _lab } = RC;
function grab(canvas, maxW) {
const k = Math.min(1, maxW / canvas.width);
if (k === 1) return { img: grayOf(canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height)), k };
const c = document.createElement("canvas"); c.width = Math.round(canvas.width * k); c.height = Math.round(canvas.height * k);
const ctx = c.getContext("2d", { willReadFrequently: true });
ctx.drawImage(canvas, 0, 0, c.width, c.height);
return { img: grayOf(ctx.getImageData(0, 0, c.width, c.height)), k };
}
// pipelines under test: canvas -> { token, ... }
const scanners = {};
const pipes = {
legacy: (canvas) => V1.decodeFrame(grab(canvas, 960).img), // what vote.js shipped with
cap960: (canvas, t) => decodeFrame(grab(canvas, 960).img, t.opts || {}),
native: (canvas, t) => decodeFrame(grab(canvas, 1e9).img, t.opts || {}),
noacc: (canvas, t, key) => {
const s = (scanners[key] ||= window.makeRingScanner({ accumulate: false }));
return s.scan(canvas, canvas.width, canvas.height, t.now ?? undefined);
},
crop: (canvas, t, key) => {
const s = (scanners[key] ||= window.makeRingScanner({ gate: t.now != null, crop: +key.slice(4) }));
return s.scan(canvas, canvas.width, canvas.height, t.now ?? undefined);
},
scan: (canvas, t, key) => {
// a lone still has no previous token to agree with
const s = (scanners[key] ||= window.makeRingScanner(t.now == null ? { gate: false } : {}));
return s.scan(canvas, canvas.width, canvas.height, t.now ?? undefined);
},
};
// where does a failed frame break? substitutes the truth stage by stage
function diagnose(img, k, truth, t) {
const T = (x, y) => { const [u, v] = truth(x, y); return [(u + 0.5) * k - 0.5, (v + 0.5) * k - 0.5]; };
const [cx, cy] = T(0, 0), [ex, ey] = T(CENTER, 0), rpx = Math.hypot(ex - cx, ey - cy);
const out = { rpx: +rpx.toFixed(1) };
const dbg = { cx, cy, r: rpx, stage: "noblob" };
const cands = locate(img, { max: 60, dbg });
out.loc = dbg.stage;
out.rank = cands.findIndex((c) => Math.hypot(c.cx - cx, c.cy - cy) < 0.3 * rpx);
out.ncand = cands.length;
if (out.rank >= 0) { const r = decodeAt(img, cands[out.rank], {}); out.candOk = !!(r && r.token === t.token); out.candScore = r ? +(+r.score).toFixed(2) : null; }
const S = (x, y) => { const [u, v] = T(x, y); return _lab.bilinear(img, u, v); };
const r = _lab.readRings(S, {});
out.oracleGeo = !!(r && r.token === t.token);
out.oracleScore = r && r.score != null ? +r.score.toFixed(2) : null;
// true geometry and rotation: is the tone of each dash still separable?
const rings = RC.ringsOf(t.bits);
let bitErr = 0, idealErr = 0; const dp = [], byteBits = [];
rings.forEach((ring, ri) => {
const n = ring.length, step = (2 * Math.PI) / n, vals = [];
for (let j = 0; j < n; j++) vals.push(_lab.sector(S, RADII[ri], _lab.sectorAngle(t.theta, j, n), step));
const dark = vals.filter((_, j) => ring[j] === "1"), light = vals.filter((_, j) => ring[j] === "0");
const m = (a) => a.reduce((x, y) => x + y, 0) / a.length, sd = (a) => Math.sqrt(m(a.map((v) => (v - m(a)) ** 2)));
dp.push(+((m(light) - m(dark)) / (Math.hypot(sd(light), sd(dark)) / Math.SQRT2 || 1)).toFixed(1));
if (ri === 0) { out.span = +(m(light) - m(dark)).toFixed(0); return; }
const sp = _lab.split(vals);
let best = n;
for (const thr of vals) { let e = 0; vals.forEach((v, j) => { e += (v <= thr ? "1" : "0") !== ring[j]; }); best = Math.min(best, e); }
idealErr += best;
vals.forEach((v, j) => { const e = (v < sp.thr ? "1" : "0") !== ring[j]; bitErr += e; byteBits.push(e); });
});
let byteErr = 0;
for (let i = 0; i < 96; i += 8) byteErr += byteBits.slice(i, i + 8).some(Boolean);
Object.assign(out, { dprime: dp, bitErr, idealErr, byteErr, lab: toneLab(img, T, t) });
out.stage = out.rank < 0 || out.rank >= 4 ? "locate" : out.oracleGeo ? "geometry" : byteErr <= 3 ? "sync/thr" : "tone";
return out;
}
// lab only: which bit decision would survive, given the true geometry? and how much do neighbours bleed in?
function sharpen(img, passes, amt) {
const { g, w, h } = img, b = Float32Array.from(g), tmp = new Float32Array(w * h);
for (let p = 0; p < passes; p++) {
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { const i = y * w + x; tmp[i] = (b[i - (x > 0)] + 2 * b[i] + b[i + (x < w - 1)]) / 4; }
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { const i = y * w + x; b[i] = (tmp[i - (y > 0 ? w : 0)] + 2 * tmp[i] + tmp[i + (y < h - 1 ? w : 0)]) / 4; }
}
for (let i = 0; i < b.length; i++) b[i] = g[i] + amt * (g[i] - b[i]);
return { g: b, w, h };
}
function toneLab(img, T, t) {
const rings = RC.ringsOf(t.bits), out = {};
const read = (im) => {
const S = (x, y) => { const [u, v] = T(x, y); return _lab.bilinear(im, u, v); };
return rings.map((ring, ri) => { const n = ring.length, step = (2 * Math.PI) / n; return ring.split("").map((_, j) => _lab.sector(S, RADII[ri], _lab.sectorAngle(t.theta, j, n), step)); });
};
const errs = (vals, thrOf) => { let e = 0; for (let ri = 1; ri < 4; ri++) { const thr = thrOf(ri); vals[ri].forEach((v, j) => { e += (v < thr ? "1" : "0") !== rings[ri][j]; }); } return e; };
const m = (a) => a.reduce((x, y) => x + y, 0) / a.length;
const variants = { raw: img, sh1: sharpen(img, 3, 1), sh2: sharpen(img, 6, 2) };
for (const [name, im] of Object.entries(variants)) {
const vals = read(im);
if (vals.flat().some(Number.isNaN)) continue;
const D = m(vals[0].filter((_, j) => rings[0][j] === "1")), L = m(vals[0].filter((_, j) => rings[0][j] === "0"));
out[name + "Otsu"] = errs(vals, (ri) => _lab.split(vals[ri]).thr);
out[name + "Sync"] = errs(vals, () => (D + L) / 2);
const all = _lab.split(vals.slice(1).flat()).thr;
out[name + "All"] = errs(vals, () => all);
// local: compare each dash with the mean of its ring neighbourhood
let e = 0;
for (let ri = 1; ri < 4; ri++) { const v = vals[ri], n = v.length; v.forEach((x, j) => { let lo = Infinity, hi = -Infinity; for (let d = -3; d <= 3; d++) { const y = v[(j + d + n) % n]; if (y < lo) lo = y; if (y > hi) hi = y; } const thr = hi - lo > 0.5 * (L - D) ? (lo + hi) / 2 : (D + L) / 2; e += (x < thr ? "1" : "0") !== rings[ri][j]; }); }
out[name + "Local"] = e;
if (name !== "raw") continue;
// y = c0 + own*b + ang*mean(ring neighbours) + rad*mean(adjacent rings), in units of the sync ring swing
const rows = [];
rings.forEach((ring, ri) => {
const n = ring.length;
for (let j = 0; j < n; j++) {
const frac = (j + 0.5) / n, nb = (k) => (k < 0 || k > 3 ? 0 : +rings[k][Math.floor(frac * rings[k].length)]);
rows.push([1, +ring[j], (+ring[(j + 1) % n] + +ring[(j + n - 1) % n]) / 2, (nb(ri - 1) + nb(ri + 1)) / 2, (L - vals[ri][j]) / (L - D)]);
}
});
const N = Array.from({ length: 4 }, () => new Array(4).fill(0)), V = new Array(4).fill(0);
for (const r of rows) for (let i = 0; i < 4; i++) { V[i] += r[i] * r[4]; for (let j = 0; j < 4; j++) N[i][j] += r[i] * r[j]; }
for (let i = 0; i < 4; i++) { let p = i; for (let r = i + 1; r < 4; r++) if (Math.abs(N[r][i]) > Math.abs(N[p][i])) p = r; [N[i], N[p]] = [N[p], N[i]]; [V[i], V[p]] = [V[p], V[i]]; for (let r = 0; r < 4; r++) if (r !== i) { const f = N[r][i] / N[i][i]; for (let k = i; k < 4; k++) N[r][k] -= f * N[i][k]; V[r] -= f * V[i]; } }
const co = V.map((v, i) => v / N[i][i]);
let res = 0;
for (const r of rows) res += (r[4] - co[0] - co[1] * r[1] - co[2] * r[2] - co[3] * r[3]) ** 2;
out.isi = [...co, Math.sqrt(res / rows.length)].map((v) => +v.toFixed(3));
}
return out;
}
window.runFar = async (cfg) => {
const rnd = lcg(cfg.seed || 4242), results = [];
design.v1 = !!cfg.v1;
for (const t of cfg.trials) {
const room = makeRoom(t.W, t.H, t.room, rnd);
let f = frame(room, t, rnd);
if (t.jpeg) f = { ...f, canvas: await jpeg(f.canvas, t.jpeg) };
const res = { ...t, bits: undefined };
for (const name of cfg.pipes) {
for (const key of Object.keys(scanners)) delete scanners[key];
const t0 = performance.now();
const d = (pipes[name] || pipes[name.slice(0, 4)])(f.canvas, t, name);
const ms = performance.now() - t0;
res[name] = { ok: t.nocode ? !d.token : d.token === t.token, token: d.token || null, ms: +ms.toFixed(1), found: d.found, score: d.score == null ? null : +(+d.score).toFixed(2) };
}
if (cfg.diag && !t.nocode) {
const { img, k } = grab(f.canvas, cfg.diag === "legacy" ? 960 : 1e9);
res.diag = diagnose(img, k, f.truth, t);
}
if (cfg.keep && results.length < cfg.keep) res.png = f.canvas.toDataURL("image/jpeg", 0.9);
results.push(res);
}
return results;
};
// a phone held for a few seconds: rotation, token switches with cross-fade, shake, per-frame noise.
// seq: frame params + { fps, secs, interval, tokens: [{ bits, token }], shake }
window.runSeq = async (cfg) => {
const rnd = lcg(cfg.seed || 777), results = [];
design.v1 = !!cfg.v1;
for (const s of cfg.seqs) {
const room = makeRoom(s.W, s.H, s.room, rnd);
const res = { ...s, tokens: undefined };
for (const name of cfg.pipes) res[name] = { got: [], false: 0, frames: 0, ms: 0, first5: null };
for (const key of Object.keys(scanners)) delete scanners[key];
let px = 0, py = 0;
const fadeMs = Math.min(700, s.interval * (s.fadeK || 0.7)), t00 = s.t0 || 0;
for (let i = 0; i < s.fps * s.secs; i++) {
const ms = t00 + (i * 1000) / s.fps + rnd() * 20, slot = Math.floor(ms / s.interval), idx = slot - Math.floor(t00 / s.interval);
const cur = s.tokens[idx], prev = idx > 0 ? s.tokens[idx - 1] : null, since = ms - slot * s.interval;
// hand shake: drifting offset plus a random smear for this exposure
px = px * 0.8 + (rnd() - 0.5) * 2 * s.shake * 3; py = py * 0.8 + (rnd() - 0.5) * 2 * s.shake * 3;
const t = { ...s, bits: cur.bits, token: cur.token, theta: (ms / 1000) * (2 * Math.PI / 45), anim: ms / 1000,
fade: prev && since < fadeMs ? { from: prev.bits, k: since / fadeMs, seed: slot } : null,
dx: (s.dx || 0) + px * (s.W / 1280), dy: (s.dy || 0) + py * (s.W / 1280),
motion: [(rnd() - 0.5) * 2 * s.shake, (rnd() - 0.5) * 2 * s.shake], now: ms };
const f = frame(room, t, rnd);
for (const name of cfg.pipes) {
const r = res[name], t0 = performance.now();
const d = pipes[name](f.canvas, t, name + results.length);
r.ms += performance.now() - t0; r.frames++;
if (!d.token) continue;
// late reads of an older token are fine (accumulation), anything never shown is a false token
if (!s.tokens.slice(0, idx + 1).some((k) => k.token === d.token)) r.false++;
else if (!r.got.includes(d.token)) { r.got.push(d.token); if (r.got.length === 5) r.first5 = +((ms - t00) / 1000).toFixed(2); }
}
}
for (const name of cfg.pipes) { const r = res[name]; r.ms = +(r.ms / r.frames).toFixed(1); r.got = r.got.length; }
results.push(res);
}
return results;
};
-1
View File
@@ -12,4 +12,3 @@ html, body { margin: 0; height: 100%; background: #f5f6fa; color: #1c2036; font:
button { font: 600 16px system-ui; padding: 12px 18px; border-radius: 99px; border: 0; background: #ffcc00; color: #1c2036; width: 100%; margin-top: 8px; } button { font: 600 16px system-ui; padding: 12px 18px; border-radius: 99px; border: 0; background: #ffcc00; color: #1c2036; width: 100%; margin-top: 8px; }
button.ghost { background: #fff; } button.ghost { background: #fff; }
.hist { font-size: 14px; color: #4a4f66; } .hist { font-size: 14px; color: #4a4f66; }
#shot { width: 100%; border-radius: 12px; margin-top: 12px; }
-4
View File
@@ -13,12 +13,8 @@
<div>Images lues<b id="ring">0 %</b></div> <div>Images lues<b id="ring">0 %</b></div>
<div>Codes distincts<b id="count">0 / 5</b></div> <div>Codes distincts<b id="count">0 / 5</b></div>
<div>Mode vu<b id="mode">aucun</b></div> <div>Mode vu<b id="mode">aucun</b></div>
<div>Flux caméra<b id="res">-</b></div>
<div>Temps de calcul<b id="ms">-</b></div>
</div> </div>
<button id="go">Démarrer la caméra</button> <button id="go">Démarrer la caméra</button>
<button id="snap" class="ghost">Enregistrer l'image vidéo</button>
<button id="again" class="ghost">Nouvel essai</button> <button id="again" class="ghost">Nouvel essai</button>
<p class="hist" id="hist"></p> <p class="hist" id="hist"></p>
<img id="shot" alt="Image vidéo enregistrée" hidden>
</main></body></html> </main></body></html>
+7 -32
View File
@@ -1,11 +1,9 @@
import { makeRingScanner } from "/static/js/ringscan.js"; import { decodeFrame, grayOf } from "/static/js/ringcode.js";
const rings = makeRingScanner();
const $ = (id) => document.getElementById(id); const $ = (id) => document.getElementById(id);
const video = $("v"), canvas = document.createElement("canvas"), ctx = canvas.getContext("2d"); const video = $("v"), canvas = document.createElement("canvas"), ctx = canvas.getContext("2d", { willReadFrequently: true });
let engine, running = false, frames = 0, qr = 0, ring = 0, t0 = 0, fpsT = performance.now(), fpsN = 0; let engine, running = false, frames = 0, qr = 0, ring = 0, t0 = 0, fpsT = performance.now(), fpsN = 0;
let tokens = new Set(), mode = "aucun", msAvg = 0; let tokens = new Set(), mode = "aucun";
const history = []; const history = [];
function reset() { function reset() {
@@ -15,12 +13,9 @@ function reset() {
async function start() { async function start() {
engine = await QrScanner.createQrEngine(); engine = await QrScanner.createQrEngine();
// same request as the vote page, so what this page measures is what voters get
const stream = await navigator.mediaDevices.getUserMedia({ const stream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: { ideal: "environment" }, width: { ideal: 1920 }, height: { ideal: 1080 } }, video: { facingMode: { ideal: "environment" }, width: { ideal: 1920 }, height: { ideal: 1080 } },
}); });
const set = stream.getVideoTracks()[0].getSettings();
$("res").textContent = `${set.width}×${set.height} ${set.frameRate ? Math.round(set.frameRate) + " i/s" : ""}`;
video.srcObject = stream; video.srcObject = stream;
await video.play(); await video.play();
running = true; running = true;
@@ -31,16 +26,15 @@ async function start() {
async function loop() { async function loop() {
if (!running) return; if (!running) return;
if (video.readyState >= 2) { if (video.readyState >= 2) {
// the qr reference reads a 960 px copy, the rings read their own crop of the full frame // 960 px is plenty for the locator and keeps capture cheap on low-end phones
const k = Math.min(1, 960 / video.videoWidth); const k = Math.min(1, 960 / video.videoWidth);
canvas.width = Math.round(video.videoWidth * k); canvas.width = Math.round(video.videoWidth * k);
canvas.height = Math.round(video.videoHeight * k); canvas.height = Math.round(video.videoHeight * k);
ctx.drawImage(video, 0, 0, canvas.width, canvas.height); ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
frames++; fpsN++; frames++; fpsN++;
const ts = performance.now(), d = rings.scan(video, video.videoWidth, video.videoHeight); const img = grayOf(ctx.getImageData(0, 0, canvas.width, canvas.height));
msAvg = msAvg ? msAvg * 0.9 + (performance.now() - ts) * 0.1 : performance.now() - ts; const d = decodeFrame(img);
$("ms").textContent = `${Math.round(msAvg)} ms`; if (d.found) qr++;
if (d.cand) qr++;
if (d.token) { ring++; mode = "anneaux"; tokens.add(d.token); } if (d.token) { ring++; mode = "anneaux"; tokens.add(d.token); }
else if (mode !== "anneaux") { else if (mode !== "anneaux") {
// reference mode: the classic rotating qr // reference mode: the classic rotating qr
@@ -68,22 +62,3 @@ async function loop() {
$("go").addEventListener("click", () => start().catch((e) => { $("state").textContent = `Caméra : ${e.message}`; })); $("go").addEventListener("click", () => start().catch((e) => { $("state").textContent = `Caméra : ${e.message}`; }));
$("again").addEventListener("click", reset); $("again").addEventListener("click", reset);
// one raw frame of the stream as the decoder sees it, to send back when a phone can't read the ring.
// built and clicked in the same tap: android drops a download started after an async step (toBlob)
$("snap").addEventListener("click", () => {
if (!video.videoWidth) return;
const c = document.createElement("canvas");
c.width = video.videoWidth; c.height = video.videoHeight;
c.getContext("2d").drawImage(video, 0, 0);
const url = c.toDataURL("image/jpeg", 0.95);
const a = document.createElement("a");
a.href = url;
a.download = `rotatyvote-frame-${video.videoWidth}x${video.videoHeight}-${Date.now()}.jpg`;
document.body.append(a);
a.click();
a.remove();
// fallback: long press the picture to save it
$("shot").src = url;
$("shot").hidden = false;
});
-656
View File
@@ -1,656 +0,0 @@
// ring code: dark logo disc in the middle + rotating rings of dashes carrying the time token.
// layout, bit order and reed-solomon params must match rotatyvote/ringcode.py
// pure functions, no dom: runs in the browser and under node for the cross tests
export const SYNC = "010001100101001000111111";
export const RING_SECTORS = [24, 28, 32, 36];
// code space units, centered on the origin. the solid dark center disc is what the phone looks for
export const CENTER = 0.62;
export const RADII = [0.9, 1.05, 1.2, 1.35];
export const THICK = 0.105;
export const DISC = 1.5; // light background disc
// animation bounds: dash length and opacity breathe inside these, the data never depends on them
const LEN = [0.56, 0.86]; // part of the sector covered by the dash
// wide gap between the two classes so the camera tells them apart easily
const ALPHA_DARK = [0.93, 1], ALPHA_LIGHT = [0.08, 0.19];
const NSYM = 6;
// gf(256), poly 0x11d, generator 2
const EXP = new Uint8Array(512), LOG = new Uint8Array(256);
{
let x = 1;
for (let i = 0; i < 255; i++) { EXP[i] = x; LOG[x] = i; x <<= 1; if (x & 0x100) x ^= 0x11d; }
for (let i = 255; i < 512; i++) EXP[i] = EXP[i - 255];
}
const mul = (a, b) => (a && b ? EXP[LOG[a] + LOG[b]] : 0);
const div = (a, b) => (a ? EXP[(LOG[a] + 255 - LOG[b]) % 255] : 0);
const pow = (x, p) => EXP[(((LOG[x] * p) % 255) + 255) % 255];
const inv = (x) => EXP[255 - LOG[x]];
const polyScale = (p, x) => p.map((c) => mul(c, x));
const polyAdd = (p, q) => {
const r = new Array(Math.max(p.length, q.length)).fill(0);
for (let i = 0; i < p.length; i++) r[i + r.length - p.length] = p[i];
for (let i = 0; i < q.length; i++) r[i + r.length - q.length] ^= q[i];
return r;
};
const polyMul = (p, q) => {
const r = new Array(p.length + q.length - 1).fill(0);
for (let j = 0; j < q.length; j++) for (let i = 0; i < p.length; i++) r[i + j] ^= mul(p[i], q[j]);
return r;
};
const polyEval = (p, x) => { let y = p[0]; for (let i = 1; i < p.length; i++) y = mul(y, x) ^ p[i]; return y; };
let GEN = [1];
for (let i = 0; i < NSYM; i++) GEN = polyMul(GEN, [1, pow(2, i)]);
export function rsEncode(msg) {
const rem = new Array(NSYM).fill(0);
for (const byte of msg) {
const f = byte ^ rem[0];
rem.shift(); rem.push(0);
if (f) for (let j = 0; j < NSYM; j++) rem[j] ^= mul(GEN[j + 1], f);
}
return [...msg, ...rem];
}
// port of the wikiversity "reed-solomon codes for coders" decoder (fcr 0, generator 2)
export function rsDecode(cw) {
const n = cw.length;
const synd = [0];
for (let i = 0; i < NSYM; i++) synd.push(polyEval(cw, pow(2, i)));
if (Math.max(...synd) === 0) return cw.slice(0, n - NSYM);
let errLoc = [1], oldLoc = [1];
for (let i = 0; i < NSYM; i++) {
const K = i + 1;
let delta = synd[K];
for (let j = 1; j < errLoc.length; j++) delta ^= mul(errLoc[errLoc.length - 1 - j], synd[K - j]);
oldLoc = [...oldLoc, 0];
if (delta) {
if (oldLoc.length > errLoc.length) {
const newLoc = polyScale(oldLoc, delta);
oldLoc = polyScale(errLoc, inv(delta));
errLoc = newLoc;
}
errLoc = polyAdd(errLoc, polyScale(oldLoc, delta));
}
}
while (errLoc.length && errLoc[0] === 0) errLoc.shift();
const errs = errLoc.length - 1;
if (errs * 2 > NSYM) return null;
const rev = [...errLoc].reverse();
const errPos = [];
for (let i = 0; i < n; i++) if (polyEval(rev, pow(2, i)) === 0) errPos.push(n - 1 - i);
if (errPos.length !== errs) return null;
const coefPos = errPos.map((p) => n - 1 - p);
let eLoc = [1];
for (const i of coefPos) eLoc = polyMul(eLoc, polyAdd([1], [pow(2, i), 0]));
// error evaluator: (synd reversed * eLoc) mod x^(len)
const prod = polyMul([...synd].reverse(), eLoc);
const evalLen = eLoc.length;
const errEval = prod.slice(prod.length - evalLen).reverse();
const X = coefPos.map((c) => pow(2, -(255 - c)));
const E = new Array(n).fill(0);
X.forEach((Xi, i) => {
const XiInv = inv(Xi);
let prime = 1;
X.forEach((Xj, j) => { if (j !== i) prime = mul(prime, 1 ^ mul(XiInv, Xj)); });
if (!prime) return;
const y = mul(Xi, polyEval([...errEval].reverse(), XiInv));
E[errPos[i]] = div(y, prime);
});
const fixed = cw.map((c, i) => c ^ E[i]);
for (let i = 0; i < NSYM; i++) if (polyEval(fixed, pow(2, i))) return null;
return fixed.slice(0, n - NSYM);
}
export function whitening(n) {
let lfsr = 0xace1;
const out = [];
for (let i = 0; i < n; i++) { const bit = lfsr & 1; lfsr >>= 1; if (bit) lfsr ^= 0xb400; out.push(bit); }
return out;
}
export function dataBits(codeword) {
const bits = [];
for (const b of codeword) for (let k = 7; k >= 0; k--) bits.push((b >> k) & 1);
const w = whitening(bits.length);
return bits.map((b, i) => b ^ w[i]).join("");
}
export function bytesFromBits(bits) {
const w = whitening(bits.length);
const out = [];
for (let i = 0; i < bits.length; i += 8) {
let v = 0;
for (let k = 0; k < 8; k++) v = (v << 1) | (bits[i + k] ^ w[i + k]);
out.push(v);
}
return out;
}
export function tokenFromPayload(p) {
const slot = (p[0] << 8) | p[1];
return `r${slot}.${p.slice(2).map((b) => b.toString(16).padStart(2, "0")).join("")}`;
}
// splits the 120 render bits into rings
export function ringsOf(bits) {
const rings = [];
let k = 0;
for (const n of RING_SECTORS) { rings.push(bits.slice(k, k + n)); k += n; }
return rings;
}
const sectorAngle = (theta, j, n) => theta + ((j + 0.5) * 2 * Math.PI) / n;
// ---- drawing (projector + bench) ----
const INK = "#1c2036";
function logo(ctx, cx, cy, r) {
// the rotaty mark in light tones on the dark disc
const n = 6, rr = r * 0.52, step = (2 * Math.PI) / n;
ctx.lineCap = "round";
ctx.lineWidth = r * 0.17;
for (let j = 0; j < n; j++) {
const a = -Math.PI / 2 + j * step;
ctx.strokeStyle = j === 0 ? "#ffcc00" : "#ffffff";
ctx.beginPath(); ctx.arc(cx, cy, rr, a + step * 0.2, a + step * 0.8); ctx.stroke();
}
}
// deterministic per-dash phase so every dash breathes on its own rhythm
const phase = (k, j) => ((Math.sin(k * 12.9898 + j * 78.233) * 43758.5453) % 1 + 1) % 1;
// fade: { from: previous bits, k: 0..1 } while the code switches, so changed dashes cross-fade
export function render(ctx, cx, cy, unit, theta, bits, t = 0, fade = null) {
ctx.fillStyle = "#eef0f6";
ctx.beginPath(); ctx.arc(cx, cy, DISC * unit, 0, 2 * Math.PI); ctx.fill();
ctx.fillStyle = INK;
ctx.beginPath(); ctx.arc(cx, cy, CENTER * unit, 0, 2 * Math.PI); ctx.fill();
logo(ctx, cx, cy, CENTER * unit);
const prev = fade && fade.k < 1 ? ringsOf(fade.from) : null;
const ease = fade ? fade.k * fade.k * (3 - 2 * fade.k) : 1;
ctx.lineCap = "round";
ctx.lineWidth = THICK * unit;
ringsOf(bits).forEach((ring, k) => {
const n = ring.length, r = RADII[k] * unit, step = (2 * Math.PI) / n;
const cap = (THICK * unit) / 2 / r;
for (let j = 0; j < n; j++) {
const ph = phase(k, j) * 2 * Math.PI, w = 0.5 + 0.5 * Math.sin(t * 1.3 + ph), w2 = 0.5 + 0.5 * Math.sin(t * 0.9 + ph * 1.7);
const len = LEN[0] + (LEN[1] - LEN[0]) * w;
const alphaOf = (bit) => { const [a0, a1] = bit === "1" ? ALPHA_DARK : ALPHA_LIGHT; return a0 + (a1 - a0) * w2; };
const now = alphaOf(ring[j]), before = prev ? alphaOf(prev[k][j]) : now;
const half = Math.max(0.01, (step * len) / 2 - cap);
const a = sectorAngle(theta, j, n) - Math.PI / 2;
ctx.globalAlpha = before + (now - before) * ease;
ctx.strokeStyle = INK;
ctx.beginPath(); ctx.arc(cx, cy, r, a - half, a + half); ctx.stroke();
}
});
ctx.globalAlpha = 1;
}
// ---- decoding (phone) ----
export function grayOf(imageData) {
const { data, width, height } = imageData, g = new Float32Array(width * height);
for (let i = 0, j = 0; i < g.length; i++, j += 4) g[i] = 0.299 * data[j] + 0.587 * data[j + 1] + 0.114 * data[j + 2];
return { g, w: width, h: height };
}
function bilinear(img, u, v) {
const { g, w, h } = img;
if (!(u >= 0 && v >= 0 && u < w - 1 && v < h - 1)) return NaN;
const x0 = u | 0, y0 = v | 0, fx = u - x0, fy = v - y0, i = y0 * w + x0;
return (g[i] * (1 - fx) + g[i + 1] * fx) * (1 - fy) + (g[i + w] * (1 - fx) + g[i + w + 1] * fx) * fy;
}
// mean brightness of one dash: a few points across its middle
function sector(S, r, a, step) {
let sum = 0, n = 0;
for (const dr of [-0.028, 0, 0.028]) for (const da of [-0.18, 0, 0.18]) {
const ang = a + da * step, rr = r + dr;
const v = S(rr * Math.sin(ang), -rr * Math.cos(ang));
if (!Number.isNaN(v)) { sum += v; n++; }
}
return n >= 6 ? sum / n : NaN;
}
const SYNC_BITS = [...SYNC].map(Number);
function corr(vals, bits) {
// dark (1) should be low: correlate values with -bit
const n = vals.length;
let mv = 0, mb = 0;
for (let i = 0; i < n; i++) { mv += vals[i]; mb += bits[i]; }
mv /= n; mb /= n;
let num = 0, dv = 0, db = 0;
for (let i = 0; i < n; i++) { const a = vals[i] - mv, b = -(bits[i] - mb); num += a * b; dv += a * a; db += b * b; }
return dv && db ? num / Math.sqrt(dv * db) : 0;
}
// otsu split of one ring: threshold + how well it separates (between-class / total variance)
function split(vals) {
const s = [...vals].sort((a, b) => a - b), n = s.length;
const total = s.reduce((a, b) => a + b, 0), mean = total / n;
const tv = s.reduce((a, v) => a + (v - mean) ** 2, 0) || 1;
let best = { quality: -1, thr: mean }, left = 0;
for (let i = 1; i < n; i++) {
left += s[i - 1];
const m0 = left / i, m1 = (total - left) / (n - i);
const q = (i * (n - i) * (m0 - m1) ** 2) / n / tv;
if (q > best.quality) best = { quality: q, thr: (s[i - 1] + s[i]) / 2 };
}
return best;
}
function solve(A, B) {
const n = B.length;
for (let i = 0; i < n; i++) {
let p = i;
for (let r = i + 1; r < n; r++) if (Math.abs(A[r][i]) > Math.abs(A[p][i])) p = r;
[A[i], A[p]] = [A[p], A[i]]; [B[i], B[p]] = [B[p], B[i]];
if (Math.abs(A[i][i]) < 1e-12) return null;
for (let r = 0; r < n; r++) if (r !== i) {
const f = A[r][i] / A[i][i];
for (let k = i; k < n; k++) A[r][k] -= f * A[i][k];
B[r] -= f * B[i];
}
}
return B.map((b, i) => b / A[i][i]);
}
function otsu(vals) {
const hist = new Float64Array(256);
for (const v of vals) hist[Math.max(0, Math.min(255, v | 0))]++;
let total = 0, sum = 0;
for (let i = 0; i < 256; i++) { total += hist[i]; sum += i * hist[i]; }
let wb = 0, sb = 0, best = 0, thr = 128;
for (let i = 0; i < 256; i++) {
wb += hist[i];
if (!wb || wb === total) continue;
sb += i * hist[i];
const mb = sb / wb, mf = (sum - sb) / (total - wb), v = wb * (total - wb) * (mb - mf) ** 2;
if (v > best) { best = v; thr = i; }
}
return thr;
}
// candidate center discs: solid dark elliptic blobs. returns [{ cx, cy, A }] in image pixels,
// A maps code space (center disc radius CENTER) onto the ellipse, rotation left free
export function locate(img, opts = {}) {
const f = Math.max(1, Math.ceil(Math.max(img.w, img.h) / (opts.maxDim || 480)));
const w = Math.floor(img.w / f), h = Math.floor(img.h / f), small = new Float32Array(w * h);
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
let s = 0;
for (let dy = 0; dy < f; dy++) for (let dx = 0; dx < f; dx++) s += img.g[(y * f + dy) * img.w + x * f + dx];
small[y * w + x] = s / (f * f);
}
const thr = otsu(small);
const label = new Int32Array(w * h).fill(-1), cands = [];
const stack = [];
for (let start = 0; start < w * h; start++) {
if (label[start] !== -1 || small[start] > thr) continue;
// flood fill one dark component, keep per-row extents
const id = cands.length, rows = new Map();
let count = 0;
label[start] = id; stack.push(start);
while (stack.length) {
const i = stack.pop(), x = i % w, y = (i / w) | 0;
count++;
const r = rows.get(y);
if (r) { if (x < r[0]) r[0] = x; if (x > r[1]) r[1] = x; } else rows.set(y, [x, x]);
for (const j of [i - 1, i + 1, i - w, i + w]) {
if (j < 0 || j >= w * h || label[j] !== -1 || small[j] > thr) continue;
if ((j === i - 1 && x === 0) || (j === i + 1 && x === w - 1)) continue;
label[j] = id; stack.push(j);
}
}
cands.push(null);
if (count < 30 || rows.size < 6) continue;
// moments of the row-filled shape, so the light logo inside doesn't count as holes
let m0 = 0, mx = 0, my = 0, mxx = 0, myy = 0, mxy = 0;
for (const [y, [x0, x1]] of rows) {
const n = x1 - x0 + 1, sx = ((x0 + x1) * n) / 2, sxx = (x1 * (x1 + 1) * (2 * x1 + 1) - (x0 - 1) * x0 * (2 * x0 - 1)) / 6;
m0 += n; mx += sx; my += y * n; mxx += sxx; myy += y * y * n; mxy += y * sx;
}
const ux = mx / m0, uy = my / m0;
const cxx = mxx / m0 - ux * ux + 1 / 12, cyy = myy / m0 - uy * uy + 1 / 12, cxy = mxy / m0 - ux * uy;
const tr = cxx + cyy, dt = Math.sqrt(Math.max(0, ((cxx - cyy) / 2) ** 2 + cxy * cxy));
const l1 = tr / 2 + dt, l2 = tr / 2 - dt;
if (l2 <= 0) continue;
const a = 2 * Math.sqrt(l1), b = 2 * Math.sqrt(l2);
const fill = m0 / (Math.PI * a * b), solidity = count / m0;
if (fill < 0.86 || fill > 1.14 || solidity < 0.5 || b / a < 0.38 || b < 5) continue;
const phi = 0.5 * Math.atan2(2 * cxy, cxx - cyy);
const c = Math.cos(phi), s = Math.sin(phi);
const k1 = (a * f) / CENTER, k2 = (b * f) / CENTER;
cands[id] = { cx: (ux + 0.5) * f - 0.5, cy: (uy + 0.5) * f - 0.5, A: [c * k1, -s * k2, s * k1, c * k2], area: m0 };
}
return cands.filter(Boolean).sort((p, q) => q.area - p.area).slice(0, opts.max || 4);
}
// the rough ellipse from the center disc is a bit off, and more so as the radius grows.
// the rings themselves are the better reference: find their dark bands along rays,
// fit one concentric ellipse family, undo center/scale/shear
function refine(S) {
const rows = [];
const rays = 160, r0 = 0.74, r1 = 1.48, dr = 0.005;
for (let i = 0; i < rays; i++) {
const phi = (i / rays) * 2 * Math.PI, dx = Math.sin(phi), dy = -Math.cos(phi);
const prof = [];
for (let r = r0; r <= r1 + 1e-9; r += dr) prof.push(S(r * dx, r * dy));
if (prof.some(Number.isNaN)) continue;
const sorted = [...prof].sort((a, b) => a - b);
const bg = sorted[Math.floor(sorted.length * 0.9)], lo = sorted[0];
if (bg - lo < 15) continue;
RADII.forEach((R) => {
const c = Math.round((R - r0) / dr), wdw = Math.round(0.065 / dr);
let m = -1;
for (let j = Math.max(1, c - wdw); j <= Math.min(prof.length - 2, c + wdw); j++) if (m < 0 || prof[j] < prof[m]) m = j;
if (m <= 0 || m >= prof.length - 1) return;
// a ray through a gap or a pale dash has no real dip, skip it
if (bg - prof[m] < 0.4 * (bg - lo)) return;
const a = prof[m - 1], b = prof[m], cc = prof[m + 1], den = a - 2 * b + cc;
const off = den > 0 ? (0.5 * (a - cc)) / den : 0;
const r = r0 + (m + Math.max(-1, Math.min(1, off))) * dr;
const x = r * dx, y = r * dy;
rows.push([x * x, x * y, y * y, x, y, 1, R * R]);
});
}
if (rows.length < 80) return null;
const N = Array.from({ length: 6 }, () => new Array(6).fill(0)), V = new Array(6).fill(0);
for (const row of rows) for (let i = 0; i < 6; i++) { V[i] += row[i] * row[6]; for (let j = 0; j < 6; j++) N[i][j] += row[i] * row[j]; }
const sol = solve(N, V);
if (!sol) return null;
const [a, b, c, d, e] = sol;
if (!(a > 0 && a * c - (b * b) / 4 > 0)) return null;
const x0 = (-d * 2 * c + e * b) / (4 * a * c - b * b), y0 = (-e * 2 * a + d * b) / (4 * a * c - b * b);
const p = Math.sqrt(a), q = b / 2 / p, s = Math.sqrt(c - q * q);
if (!(s > 0) || Math.hypot(x0, y0) > 0.2 || Math.abs(Math.log(p * s)) > 0.35) return null;
const i11 = 1 / p, i12 = -q / (p * s), i22 = 1 / s;
return (x, y) => S(x0 + i11 * x + i12 * y, y0 + i22 * y);
}
// ---- perspective from two concentric circles ----
// images of concentric circles C1, C2 are conics Q1, Q2. the pencil Q1 - l*Q2 holds a rank-1 member,
// the doubled vanishing line. knowing that line undoes the projective part, the rest is affine.
function jacobi(M) {
// eigen decomposition of a small symmetric matrix
const n = M.length, A = M.map((r) => [...r]), V = Array.from({ length: n }, (_, i) => Array.from({ length: n }, (_, j) => +(i === j)));
for (let sweep = 0; sweep < 60; sweep++) {
let off = 0;
for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) off += A[i][j] * A[i][j];
if (off < 1e-22) break;
for (let p = 0; p < n; p++) for (let q = p + 1; q < n; q++) {
if (Math.abs(A[p][q]) < 1e-30) continue;
const th = (A[q][q] - A[p][p]) / (2 * A[p][q]);
const t = Math.sign(th || 1) / (Math.abs(th) + Math.sqrt(th * th + 1)), c = 1 / Math.sqrt(t * t + 1), s = t * c;
for (let k = 0; k < n; k++) {
const akp = A[k][p], akq = A[k][q];
A[k][p] = c * akp - s * akq; A[k][q] = s * akp + c * akq;
}
for (let k = 0; k < n; k++) {
const apk = A[p][k], aqk = A[q][k];
A[p][k] = c * apk - s * aqk; A[q][k] = s * apk + c * aqk;
}
for (let k = 0; k < n; k++) {
const vkp = V[k][p], vkq = V[k][q];
V[k][p] = c * vkp - s * vkq; V[k][q] = s * vkp + c * vkq;
}
}
}
return { values: A.map((r, i) => r[i]), vectors: V };
}
function fitConic(pts) {
// algebraic fit, smallest eigenvector of the scatter matrix (points already normalized)
if (pts.length < 12) return null;
const S = Array.from({ length: 6 }, () => new Array(6).fill(0));
for (const [x, y] of pts) {
const r = [x * x, x * y, y * y, x, y, 1];
for (let i = 0; i < 6; i++) for (let j = 0; j < 6; j++) S[i][j] += r[i] * r[j];
}
const { values, vectors } = jacobi(S);
let k = 0;
for (let i = 1; i < 6; i++) if (values[i] < values[k]) k = i;
const [a, b, c, d, e, f] = vectors.map((row) => row[k]);
return [[a, b / 2, d / 2], [b / 2, c, e / 2], [d / 2, e / 2, f]];
}
const det3 = (m) => m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]);
const sub3 = (A, B, l) => A.map((r, i) => r.map((v, j) => v - l * B[i][j]));
function inv3(m) {
const d = det3(m);
if (Math.abs(d) < 1e-30) return null;
const c = (i, j) => {
const r = [0, 1, 2].filter((k) => k !== i), q = [0, 1, 2].filter((k) => k !== j);
return ((i + j) % 2 ? -1 : 1) * (m[r[0]][q[0]] * m[r[1]][q[1]] - m[r[0]][q[1]] * m[r[1]][q[0]]);
};
return [0, 1, 2].map((i) => [0, 1, 2].map((j) => c(j, i) / d));
}
const mul3 = (A, B) => A.map((r) => [0, 1, 2].map((j) => r[0] * B[0][j] + r[1] * B[1][j] + r[2] * B[2][j]));
const tr3 = (A) => [0, 1, 2].map((i) => [0, 1, 2].map((j) => A[j][i]));
function cubicRoots(a, b, c, d) {
// real roots of a x^3 + b x^2 + c x + d
b /= a; c /= a; d /= a;
const p = c - (b * b) / 3, q = (2 * b * b * b) / 27 - (b * c) / 3 + d, disc = (q * q) / 4 + (p * p * p) / 27;
if (disc > 0) {
const u = Math.cbrt(-q / 2 + Math.sqrt(disc)), v = Math.cbrt(-q / 2 - Math.sqrt(disc));
// near a double root the pair turns complex with noise: report its real part twice
return [u + v - b / 3, -(u + v) / 2 - b / 3, -(u + v) / 2 - b / 3];
}
const r = 2 * Math.sqrt(-p / 3), phi = Math.acos(Math.max(-1, Math.min(1, (3 * q) / (p * r))));
return [0, 1, 2].map((k) => r * Math.cos(phi / 3 - (2 * Math.PI * k) / 3) - b / 3);
}
// image points on the center disc edge and on each ring, following rays of the rough affine map
function edgePoints(img, cand) {
const [a11, a12, a21, a22] = cand.A;
const map = (x, y) => [cand.cx + a11 * x + a12 * y, cand.cy + a21 * x + a22 * y];
const at = (x, y) => { const [u, v] = map(x, y); return bilinear(img, u, v); };
const disc = [], rings = RADII.map(() => []), rays = 160;
for (let i = 0; i < rays; i++) {
const phi = (i / rays) * 2 * Math.PI, dx = Math.sin(phi), dy = -Math.cos(phi);
// disc edge: strongest dark-to-light step between 0.42 and 0.8
let best = 0, br = 0;
const prof = [];
for (let r = 0.4; r <= 0.82; r += 0.005) prof.push(at(r * dx, r * dy));
if (!prof.some(Number.isNaN)) {
for (let j = 2; j < prof.length - 2; j++) {
const gstep = prof[j + 2] - prof[j - 2];
if (gstep > best) { best = gstep; br = 0.4 + j * 0.005; }
}
if (best > 20) disc.push(map(br * dx, br * dy));
}
// rings: darkest point around each radius, only when it is a clear dip (a dark dash)
RADII.forEach((R, k) => {
const op = [], span = 0.07;
for (let r = R - span; r <= R + span + 1e-9; r += 0.004) op.push(at(r * dx, r * dy));
if (op.some(Number.isNaN)) return;
let m = 0;
for (let j = 1; j < op.length; j++) if (op[j] < op[m]) m = j;
const edge = Math.max(op[0], op[op.length - 1]);
if (m > 1 && m < op.length - 2 && edge - op[m] > 35) {
const a = op[m - 1], b = op[m], c = op[m + 1], den = a - 2 * b + c;
const off = den > 0 ? (0.5 * (a - c)) / den : 0;
const r = R - span + (m + off) * 0.004;
rings[k].push(map(r * dx, r * dy));
}
});
}
return { disc, rings };
}
// center of a conic (3x3 symmetric), in its own coordinates
function conicCenter(Q) {
const d = Q[0][0] * Q[1][1] - Q[0][1] * Q[1][0];
if (Math.abs(d) < 1e-18) return null;
return [-(Q[1][1] * Q[0][2] - Q[0][1] * Q[1][2]) / d, -(-Q[1][0] * Q[0][2] + Q[0][0] * Q[1][2]) / d];
}
function nelderMead(f, x0, step, iters) {
let pts = [x0, [x0[0] + step, x0[1]], [x0[0], x0[1] + step]].map((x) => ({ x, v: f(x) }));
for (let it = 0; it < iters; it++) {
pts.sort((a, b) => a.v - b.v);
const [b, g, w] = pts, c = [(b.x[0] + g.x[0]) / 2, (b.x[1] + g.x[1]) / 2];
const at = (t) => [c[0] + t * (w.x[0] - c[0]), c[1] + t * (w.x[1] - c[1])];
const r = { x: at(-1) }; r.v = f(r.x);
if (r.v < b.v) { const e = { x: at(-2) }; e.v = f(e.x); pts[2] = e.v < r.v ? e : r; }
else if (r.v < g.v) pts[2] = r;
else { const k = { x: at(0.5) }; k.v = f(k.x); if (k.v < w.v) pts[2] = k; else pts = [b, ...[g, w].map((p) => { const x = [(p.x[0] + b.x[0]) / 2, (p.x[1] + b.x[1]) / 2]; return { x, v: f(x) }; })]; }
}
pts.sort((a, b) => a.v - b.v);
return pts[0].x;
}
// projective map code space -> image from the two conics, or null
export let lastProjective = null;
function projective(img, cand) {
const { disc, rings } = edgePoints(img, cand);
const outer = rings[rings.length - 1];
lastProjective = { disc: disc.length, rings: rings.map((r) => r.length), stage: 'points' };
if (disc.length < 40 || outer.length < 30) return null;
// normalize coordinates for a well conditioned fit
const all = [disc, ...rings].flat();
const mx = all.reduce((s, p) => s + p[0], 0) / all.length, my = all.reduce((s, p) => s + p[1], 0) / all.length;
const sc = Math.sqrt(all.reduce((s, p) => s + (p[0] - mx) ** 2 + (p[1] - my) ** 2, 0) / all.length) || 1;
const nrm = (p) => [(p[0] - mx) / sc, (p[1] - my) / sc];
const Q1 = fitConic(disc.map(nrm)), Q2 = fitConic(outer.map(nrm));
if (!Q1 || !Q2) return null;
// for concentric circles C1 C2^-1 = diag(1, 1, r1^2/r2^2): its simple eigenvalue belongs to the
// line at infinity. in the image that eigenvector of Q1 Q2^-1 is the vanishing line (stable, unlike the double one)
const Q2i = inv3(Q2);
if (!Q2i) return null;
const N = mul3(Q1, Q2i);
const tr = N[0][0] + N[1][1] + N[2][2];
const minors = N[0][0] * N[1][1] - N[0][1] * N[1][0] + N[0][0] * N[2][2] - N[0][2] * N[2][0] + N[1][1] * N[2][2] - N[1][2] * N[2][1];
const roots = cubicRoots(1, -tr, minors, -det3(N));
let mu = roots[0], gap = -1;
for (let i = 0; i < 3; i++) {
const g = Math.min(...roots.filter((_, j) => j !== i).map((r) => Math.abs(r - roots[i])));
if (g > gap) { gap = g; mu = roots[i]; }
}
lastProjective.roots = roots; lastProjective.stage = 'roots';
// left eigenvector: l^T (N - mu I) = 0, so l is orthogonal to the columns of (N - mu I)
const Mt = tr3(sub3(N, [[1, 0, 0], [0, 1, 0], [0, 0, 1]], mu));
const cross = (u, v) => [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
let l = null, ln = 0;
for (const [i, j] of [[0, 1], [0, 2], [1, 2]]) {
const c = cross(Mt[i], Mt[j]), n = Math.hypot(...c);
if (n > ln) { ln = n; l = c; }
}
if (!l || Math.abs(l[2]) < 1e-9) return null;
l = l.map((v) => v / l[2]);
lastProjective.l = l; lastProjective.stage = 'line';
// rectify: P maps the vanishing line to infinity
const P = [[1, 0, 0], [0, 1, 0], l];
const Pi = inv3(P);
if (!Pi) return null;
const Q1r = mul3(tr3(Pi), mul3(Q1, Pi));
// Q1r is now an ellipse: x^T M x + 2 g.x + f = 0
const M = [[Q1r[0][0], Q1r[0][1]], [Q1r[1][0], Q1r[1][1]]], g = [Q1r[0][2], Q1r[1][2]], f = Q1r[2][2];
const dm = M[0][0] * M[1][1] - M[0][1] * M[1][0];
if (Math.abs(dm) < 1e-18) return null;
const c0 = [-(M[1][1] * g[0] - M[0][1] * g[1]) / dm, -(-M[1][0] * g[0] + M[0][0] * g[1]) / dm];
const kk = -(f + g[0] * c0[0] + g[1] * c0[1]);
// (x-c0)^T (M/kk) (x-c0) = 1 is the disc: scale so it becomes radius CENTER
let a = M[0][0] / kk, b = M[0][1] / kk, c = M[1][1] / kk;
if (a < 0) { a = -a; b = -b; c = -c; }
lastProjective.ellipse = [a, b, c]; lastProjective.stage = 'ellipse';
if (!(a > 0 && a * c - b * b > 0)) return null;
lastProjective.stage = 'ok';
const p = Math.sqrt(a), q = b / p, s = Math.sqrt(c - q * q);
// affine from code space (radius CENTER) into the rectified plane: x = c0 + B t, B = (A^-1) / CENTER
const B = [[1 / p / CENTER, -q / (p * s) / CENTER], [0, 1 / s / CENTER]];
const map = (x, y) => {
const u = c0[0] + B[0][0] * x + B[0][1] * y, v = c0[1] + B[1][1] * y;
const w = Pi[2][0] * u + Pi[2][1] * v + Pi[2][2];
const X = (Pi[0][0] * u + Pi[0][1] * v + Pi[0][2]) / w, Y = (Pi[1][0] * u + Pi[1][1] * v + Pi[1][2]) / w;
return [X * sc + mx, Y * sc + my];
};
lastProjective.map = map;
return (x, y) => { const [u, v] = map(x, y); return bilinear(img, u, v); };
}
// reads one candidate. returns { token, theta, score, scale } or { token: null, ... } or null.
// tries the projective geometry (better under tilt) and the plain affine one (safer on soft frames)
export function decodeAt(img, cand, opts = {}) {
const [a11, a12, a21, a22] = cand.A;
const affine = (x, y) => bilinear(img, cand.cx + a11 * x + a12 * y, cand.cy + a21 * x + a22 * y);
const maps = [opts.projective !== false && projective(img, cand), affine].filter(Boolean);
let best = null;
for (const S0 of maps) {
const S = (opts.refine !== false && refine(S0)) || S0;
const r = readRings(S, opts);
if (r && r.token) return r;
if (r && (!best || r.score > best.score)) best = r;
}
return best;
}
function readRings(S, opts) {
const minScore = opts.minScore ?? 0.8;
const n0 = RING_SECTORS[0], step0 = (2 * Math.PI) / n0;
const syncAt = (theta, scale) => {
const vals = [];
for (let j = 0; j < n0; j++) vals.push(sector(S, RADII[0] * scale, sectorAngle(theta, j, n0), step0));
return vals.some(Number.isNaN) ? null : { score: corr(vals, SYNC_BITS), theta, scale, vals };
};
// coarse pass over the full turn (no rotational symmetry), then a fine pass around the best hits.
// ~5x fewer samples than a dense search, which matters on low-end phones
const coarse = [];
for (const scale of opts.scales || [0.96, 1.0, 1.04]) {
for (let t = 0; t < 72; t++) {
const r = syncAt((t / 72) * 2 * Math.PI, scale);
if (!r) return null;
coarse.push(r);
}
}
coarse.sort((p, q) => q.score - p.score);
let best = null;
for (const c of coarse.slice(0, 3)) {
for (const ds of [-0.02, 0, 0.02]) for (let dt = -10; dt <= 10; dt++) {
const r = syncAt(c.theta + (dt * 0.5 * Math.PI) / 180, c.scale + ds);
if (r && (!best || r.score > best.score)) best = r;
}
}
// weak sync means we're not looking at a ring code (or a bad frame): don't let rs "fix" noise
if (!best || best.score < minScore) return best ? { token: null, ...best } : null;
const dark = [], light = [];
best.vals.forEach((v, j) => (SYNC_BITS[j] ? dark : light).push(v));
const md = dark.reduce((x, y) => x + y) / dark.length, ml = light.reduce((x, y) => x + y) / light.length;
if (ml - md < 12) return { token: null, ...best };
const bits = [];
for (let k = 1; k < RING_SECTORS.length; k++) {
// nudge scale and rotation per ring (perspective is only approximated) and keep the cleanest split
const n = RING_SECTORS[k], step = (2 * Math.PI) / n;
let pick = null;
for (const ds of [-0.03, -0.015, 0, 0.015, 0.03]) for (const dt of [-0.22, 0, 0.22]) {
const r = RADII[k] * best.scale * (1 + ds), vals = [];
for (let j = 0; j < n; j++) vals.push(sector(S, r, sectorAngle(best.theta + dt * step, j, n), step));
if (vals.some(Number.isNaN)) continue;
const sp = split(vals);
if (!pick || sp.quality > pick.quality) pick = { ...sp, vals };
}
if (!pick) return { token: null, ...best };
for (const v of pick.vals) bits.push(v < pick.thr ? 1 : 0);
}
const msg = rsDecode(bytesFromBits(bits));
return { ...best, vals: undefined, bits: bits.join(""), token: msg ? tokenFromPayload(msg) : null };
}
// whole frame: find center discs, read the first one that yields a valid token
export function decodeFrame(img, opts = {}) {
const cands = locate(img, opts);
let last = null;
for (const c of cands) {
const r = decodeAt(img, c, opts);
if (r && r.token) return { ...r, cand: c, found: cands.length };
last = r || last;
}
return { token: null, found: cands.length, score: last?.score ?? null };
}
+3 -5
View File
@@ -12,10 +12,8 @@ for (const ms of [1000, 500]) {
} }
let slot = 0, bits = "", prevBits = "", switchedAt = 0, idx = 0; let slot = 0, bits = "", prevBits = "", switchedAt = 0, idx = 0;
// changed dashes wipe over a short time, a few frames are then unreadable, which is fine // changed dashes cross-fade over a short time, a few frames are then unreadable, which is fine
// ?fade=0.5 tries a longer wipe, as a share of the interval const FADE = Math.min(220, MS * 0.25);
const FADE = params.get("fade") ? MS * +params.get("fade") : Math.min(700, MS * 0.7);
const EASE = params.get("ease") || "sine";
function tick() { function tick() {
prevBits = bits || null; prevBits = bits || null;
switchedAt = performance.now(); switchedAt = performance.now();
@@ -36,7 +34,7 @@ function frame(t) {
if (MODE === "ring") { if (MODE === "ring") {
// one full turn every 45 s // one full turn every 45 s
const k = prevBits ? Math.min(1, (t - switchedAt) / FADE) : 1; const k = prevBits ? Math.min(1, (t - switchedAt) / FADE) : 1;
render(ctx, w / 2, h / 2, size / (2 * DISC), (t / 1000) * (2 * Math.PI / 45), bits, t / 1000, prevBits ? { from: prevBits, k, seed: slot, ease: EASE } : null); render(ctx, w / 2, h / 2, size / (2 * DISC), (t / 1000) * (2 * Math.PI / 45), bits, t / 1000, prevBits ? { from: prevBits, k } : null);
} else { } else {
const m = lab.classic[idx].modules, n = m.length, s = Math.floor(size / (n + 8)); const m = lab.classic[idx].modules, n = m.length, s = Math.floor(size / (n + 8));
const x0 = (w - n * s) / 2, y0 = (h - n * s) / 2; const x0 = (w - n * s) / 2, y0 = (h - n * s) / 2;
-170
View File
@@ -1,170 +0,0 @@
// synthetic camera frames of a projected ring code: a washed-out screen in a room, seen by a phone sensor
import { render, DISC } from "/static/js/ringcode.js";
import { render as renderV1 } from "/static/ringlab/ringcode_v1.js";
// v1: draw the code as it was before the far-reading work, for baselines
export const design = { v1: false };
export function lcg(seed) {
let s = (seed >>> 0) || 1;
return () => ((s = (Math.imul(s, 1103515245) + 12345) & 0x7fffffff) / 0x7fffffff);
}
// 8 coefs of the homography sending src[i] to dst[i]
function homography(src, dst) {
const A = [], B = [];
for (let i = 0; i < 4; i++) {
const [x, y] = src[i], [u, v] = dst[i];
A.push([x, y, 1, 0, 0, 0, -u * x, -u * y]); B.push(u);
A.push([0, 0, 0, x, y, 1, -v * x, -v * y]); B.push(v);
}
for (let i = 0; i < 8; i++) {
let p = i;
for (let r = i + 1; r < 8; r++) if (Math.abs(A[r][i]) > Math.abs(A[p][i])) p = r;
[A[i], A[p]] = [A[p], A[i]]; [B[i], B[p]] = [B[p], B[i]];
for (let r = 0; r < 8; r++) if (r !== i) { const f = A[r][i] / A[i][i]; for (let k = i; k < 8; k++) A[r][k] -= f * A[i][k]; B[r] -= f * B[i]; }
}
return B.map((b, i) => b / A[i][i]);
}
const applyH = (h, x, y) => { const w = h[6] * x + h[7] * y + 1; return [(h[0] * x + h[1] * y + h[2]) / w, (h[3] * x + h[4] * y + h[5]) / w]; };
export function makeRoom(W, H, kind, rnd) {
const c = document.createElement("canvas"); c.width = W; c.height = H;
const ctx = c.getContext("2d");
// dark room: lights off for the projector. bright: daylight, full range clutter around the screen
const lmax = kind === "dark" ? 28 : 95, lmin = kind === "dark" ? 2 : 15;
const L = () => lmin + rnd() * (lmax - lmin);
const g = ctx.createLinearGradient(0, 0, W, H);
g.addColorStop(0, `hsl(${rnd() * 360}, 15%, ${L()}%)`); g.addColorStop(1, `hsl(${rnd() * 360}, 20%, ${L()}%)`);
ctx.fillStyle = g; ctx.fillRect(0, 0, W, H);
const k = W / 960;
for (let i = 0; i < 22; i++) {
ctx.fillStyle = `hsl(${rnd() * 360}, ${rnd() * 40}%, ${L()}%)`;
const t = rnd();
if (t < 0.4) ctx.fillRect(rnd() * W, rnd() * H, (20 + rnd() * 200) * k, (10 + rnd() * 120) * k);
else if (t < 0.65) { ctx.beginPath(); ctx.arc(rnd() * W, rnd() * H, (6 + rnd() * 60) * k, 0, 7); ctx.fill(); } // decoy discs (heads, lamps)
else if (t < 0.8) { ctx.font = `${(14 + rnd() * 40) * k}px system-ui`; ctx.fillText("Assemblée générale 2026", rnd() * W, rnd() * H); }
else { ctx.lineWidth = (2 + rnd() * 10) * k; ctx.strokeStyle = ctx.fillStyle; ctx.beginPath(); ctx.moveTo(rnd() * W, rnd() * H); ctx.lineTo(rnd() * W, rnd() * H); ctx.stroke(); }
}
return c;
}
// the projector page around the code: light page, title, the small entry qr, a few text lines
function page(pw, ph, d, t, rnd) {
const c = document.createElement("canvas"); c.width = pw; c.height = ph;
const ctx = c.getContext("2d", { willReadFrequently: true });
ctx.fillStyle = "#f5f6fa"; ctx.fillRect(0, 0, pw, ph);
const cx = pw * 0.36, cy = ph * 0.54, unit = (d / 2 / DISC);
if (!t.nocode) (design.v1 ? renderV1 : render)(ctx, cx, cy, unit, t.theta, t.bits, t.anim, t.fade || null);
ctx.fillStyle = "#1c2036";
ctx.font = `700 ${d * 0.11}px system-ui`; ctx.fillText("Inscription", pw * 0.66, ph * 0.2);
ctx.font = `${d * 0.05}px system-ui`;
for (let i = 0; i < 3; i++) ctx.fillText("Ouvrez la page de vote", pw * 0.66, ph * (0.3 + i * 0.07));
const m = 25, q = d * 0.36, qx = pw * 0.68, qy = ph * 0.52, r2 = lcg(t.qseed || 7);
for (let i = 0; i < m; i++) for (let j = 0; j < m; j++) if (r2() < 0.5) ctx.fillRect(qx + (i * q) / m, qy + (j * q) / m, q / m + 0.5, q / m + 0.5);
if (t.nocode && t.decoy) {
// things a projector may show instead: a plain dark disc, a pie chart
ctx.beginPath(); ctx.arc(cx, cy, unit * (0.4 + rnd() * 0.8), 0, 7); ctx.fill();
if (t.decoy > 1) for (let i = 0; i < 5; i++) { ctx.lineWidth = unit * 0.1; ctx.strokeStyle = `rgba(28,32,54,${rnd()})`; ctx.beginPath(); ctx.arc(cx, cy, unit * (0.9 + i * 0.15), rnd() * 7, rnd() * 7); ctx.stroke(); }
}
// washed projection: raised black, lower white, colour cast. only the screen is affected
const [b0, w0] = t.wash || [0, 255], cast = t.cast || [1, 1, 1];
const id = ctx.getImageData(0, 0, pw, ph), px = id.data;
for (let i = 0; i < px.length; i += 4) for (let ch = 0; ch < 3; ch++) px[i + ch] = (b0 + (px[i + ch] / 255) * (w0 - b0)) * cast[ch];
ctx.putImageData(id, 0, 0);
return { canvas: c, id, cx, cy, unit };
}
// one sensor frame. t: W H frac tilt axis dist wash cast oblur pblur motion noise band gain dx dy theta bits anim fade
// glare: [dx, dy, radius, strength 0..1, tint] around the code centre, in code diameters
// returns { canvas, truth } where truth maps code space to pixel index coordinates of the frame
export function frame(room, t, rnd) {
const { W, H } = t, ss = 2;
const d = t.frac * W; // code disc diameter in sensor px
const sw = 2.3 * d, sh = 1.5 * d; // projected page in sensor px, before tilt
const P = page(Math.round(sw * ss), Math.round(sh * ss), d * ss, t, rnd);
const pw = P.canvas.width, ph = P.canvas.height;
const tl = (t.tilt * Math.PI) / 180, a = (t.axis * Math.PI) / 180, f = (t.dist || 3.5) * d;
// keep the code itself near the frame centre, the page hangs around it
const ox = W / 2 + (t.dx || 0) + (0.5 - 0.36) * sw, oy = H / 2 + (t.dy || 0) + (0.5 - 0.54) * sh;
const corner = (x, y) => {
const X = x * Math.cos(a) + y * Math.sin(a), Y = -x * Math.sin(a) + y * Math.cos(a);
const Y2 = Y * Math.cos(tl), Z2 = Y * Math.sin(tl);
const xr = X * Math.cos(a) - Y2 * Math.sin(a), yr = X * Math.sin(a) + Y2 * Math.cos(a), s = f / (f + Z2);
return [ox + xr * s, oy + yr * s];
};
const quad = [[-sw / 2, -sh / 2], [sw / 2, -sh / 2], [sw / 2, sh / 2], [-sw / 2, sh / 2]].map(([x, y]) => corner(x, y));
const src = [[0, 0], [pw, 0], [pw, ph], [0, ph]];
const inv = homography(quad, src), fwd = homography(src, quad);
const x0 = Math.max(0, Math.floor(Math.min(...quad.map((p) => p[0])))), x1 = Math.min(W, Math.ceil(Math.max(...quad.map((p) => p[0]))));
const y0 = Math.max(0, Math.floor(Math.min(...quad.map((p) => p[1])))), y1 = Math.min(H, Math.ceil(Math.max(...quad.map((p) => p[1]))));
const bw = (x1 - x0) * ss, bh = (y1 - y0) * ss;
const scene = document.createElement("canvas"); scene.width = W; scene.height = H;
const sctx = scene.getContext("2d");
sctx.drawImage(room, 0, 0);
if (bw > 0 && bh > 0) {
// warp at 2x then box-downscale, so small codes are area-sampled instead of aliased
const B = document.createElement("canvas"); B.width = bw; B.height = bh;
const bctx = B.getContext("2d"), od = bctx.createImageData(bw, bh), s = P.id.data;
for (let Y = 0; Y < bh; Y++) for (let X = 0; X < bw; X++) {
const [pu, pv] = applyH(inv, x0 + (X + 0.5) / ss, y0 + (Y + 0.5) / ss), u = pu - 0.5, v = pv - 0.5, o = (Y * bw + X) * 4;
if (u >= 0 && v >= 0 && u < pw - 1 && v < ph - 1) {
const ix = u | 0, iy = v | 0, fx = u - ix, fy = v - iy, i = (iy * pw + ix) * 4;
for (let ch = 0; ch < 3; ch++) od.data[o + ch] = (s[i + ch] * (1 - fx) + s[i + 4 + ch] * fx) * (1 - fy) + (s[i + pw * 4 + ch] * (1 - fx) + s[i + pw * 4 + 4 + ch] * fx) * fy;
od.data[o + 3] = 255;
}
}
bctx.putImageData(od, 0, 0);
sctx.imageSmoothingQuality = "high";
sctx.drawImage(B, x0, y0, x1 - x0, y1 - y0);
}
if (t.glare) {
// reflection of a window or lamp on the screen: a tinted bright veil over part of the code
const [gx, gy, gr, gs, tint] = t.glare, [ccx, ccy] = applyH(fwd, P.cx, P.cy);
const x = ccx + gx * d, y = ccy + gy * d, g = sctx.createRadialGradient(x, y, 0, x, y, gr * d);
const [tr, tg, tb] = tint || [255, 235, 245];
g.addColorStop(0, `rgba(${tr},${tg},${tb},${gs})`); g.addColorStop(0.5, `rgba(${tr},${tg},${tb},${gs * 0.6})`); g.addColorStop(1, `rgba(${tr},${tg},${tb},0)`);
sctx.globalCompositeOperation = "screen";
sctx.fillStyle = g; sctx.fillRect(0, 0, W, H);
sctx.globalCompositeOperation = "source-over";
}
const out = document.createElement("canvas"); out.width = W; out.height = H;
const octx = out.getContext("2d", { willReadFrequently: true });
// optical blur is angular (scales with sensor resolution), pixel softness is not
const sigma = Math.hypot((t.oblur || 0) * (W / 1280), t.pblur || 0);
octx.filter = `blur(${sigma}px) brightness(${t.gain || 1})`;
const [mx, my] = (t.motion || [0, 0]).map((v) => v * (W / 1280)), steps = Math.max(1, Math.ceil(Math.hypot(mx, my)));
for (let i = 0; i < steps; i++) {
const k = steps > 1 ? i / (steps - 1) - 0.5 : 0;
octx.globalAlpha = 1 / (i + 1);
octx.drawImage(scene, mx * k, my * k);
}
octx.globalAlpha = 1; octx.filter = "none";
if (t.noise || t.band) {
const id = octx.getImageData(0, 0, W, H), px = id.data, period = (t.bandPeriod || 90) * (H / 720), ph0 = rnd() * 7;
for (let y = 0, i = 0; y < H; y++) {
// rolling shutter vs projector/lamp flicker: horizontal brightness bands
const g = 1 + (t.band || 0) * Math.sin((y / period) * 2 * Math.PI + ph0);
for (let x = 0; x < W; x++, i += 4) {
const n = (rnd() + rnd() + rnd() - 1.5) * 2 * (t.noise || 0);
px[i] = px[i] * g + n; px[i + 1] = px[i + 1] * g + n; px[i + 2] = px[i + 2] * g + n;
}
}
octx.putImageData(id, 0, 0);
}
const truth = (x, y) => {
const [u, v] = applyH(fwd, P.cx + x * P.unit, P.cy + y * P.unit);
return [u - 0.5, v - 0.5];
};
return { canvas: out, truth, d };
}
// lossy video path of cheap phones: jpeg round trip
export async function jpeg(canvas, q) {
const img = new Image();
img.src = canvas.toDataURL("image/jpeg", q);
await img.decode();
const c = document.createElement("canvas"); c.width = canvas.width; c.height = canvas.height;
c.getContext("2d", { willReadFrequently: true }).drawImage(img, 0, 0);
return c;
}
+3 -17
View File
@@ -26,14 +26,14 @@
<main class="s-main"> <main class="s-main">
<section id="enroll" class="s-enroll" hidden> <section id="enroll" class="s-enroll" hidden>
<div class="qr-wrap"> <div class="qr-wrap">
<canvas id="qr" aria-label="Code d'inscription, renouvelé en continu"></canvas> <canvas id="qr" aria-label="QR code d'inscription, renouvelé en continu"></canvas>
<div class="tick"><div id="tick-bar"></div></div> <div class="tick"><div id="tick-bar"></div></div>
</div> </div>
<div class="s-steps"> <div class="s-steps">
<h2 id="qr-title">Inscription</h2> <h2 id="qr-title">Inscription</h2>
<ol id="qr-steps"> <ol id="qr-steps">
<li><span id="step1">Scannez ce code</span></li> <li><span>Scannez ce code</span></li>
<li id="step2"><span>Visez le cercle <b id="secs">5</b>&nbsp;s</span></li> <li><span>Visez l'écran <b id="secs">5</b>&nbsp;s</span></li>
</ol> </ol>
<p id="url-warn" class="notice warn" hidden></p> <p id="url-warn" class="notice warn" hidden></p>
</div> </div>
@@ -47,20 +47,6 @@
</section> </section>
</main> </main>
<aside id="entry" class="entry" hidden>
<div id="entry-q" class="entry-q" hidden>
<b id="entry-q-text"></b>
<ul id="entry-q-opts" class="entry-opts" hidden></ul>
<span id="entry-q-count"></span>
<div id="entry-q-turnout" class="turnout" hidden>
<b></b><span class="t-of"></span>
<div class="progress"><div></div><div class="p-extra"></div></div>
</div>
</div>
<canvas id="entry-qr" aria-label="QR code de la page de vote"></canvas>
<div><b id="entry-hint">Scannez avec l'appareil photo</b><span id="entry-url"></span></div>
</aside>
<footer class="s-foot"> <footer class="s-foot">
<div class="s-count"><b id="voters">0</b> <span id="voters-label">inscriptions</span></div> <div class="s-count"><b id="voters">0</b> <span id="voters-label">inscriptions</span></div>
</footer> </footer>
+3 -7
View File
@@ -28,7 +28,6 @@
<video id="video" playsinline muted></video> <video id="video" playsinline muted></video>
</div> </div>
<p id="scan-msg" class="scan-msg muted"></p> <p id="scan-msg" class="scan-msg muted"></p>
<div id="enroll-alt" class="cam-alt"></div>
<button id="start-cam" class="primary block" type="button">Activer la caméra</button> <button id="start-cam" class="primary block" type="button">Activer la caméra</button>
<button id="no-cam" class="link" type="button">Caméra indisponible ?</button> <button id="no-cam" class="link" type="button">Caméra indisponible ?</button>
</div> </div>
@@ -85,13 +84,10 @@
</dialog> </dialog>
<dialog id="presence"> <dialog id="presence">
<h2 id="p-title" tabindex="-1" autofocus>Visez le cercle</h2> <h2 tabindex="-1" autofocus>Visez l'écran</h2>
<div id="p-scan"> <div id="p-ring" class="dots"></div>
<div id="p-ring" class="dots"></div> <div class="cam"><video id="p-video" playsinline muted></video></div>
<div class="cam"><video id="p-video" playsinline muted></video></div>
</div>
<p id="p-msg" class="scan-msg bad"></p> <p id="p-msg" class="scan-msg bad"></p>
<div id="p-alt" class="cam-alt"></div>
<div class="actions"><button id="p-cancel" type="button">Annuler</button></div> <div class="actions"><button id="p-cancel" type="button">Annuler</button></div>
</dialog> </dialog>
</body> </body>
+29 -272
View File
@@ -35,8 +35,7 @@ def server(tmp_path_factory):
port = free_port() port = free_port()
tmp = tmp_path_factory.mktemp("db") tmp = tmp_path_factory.mktemp("db")
db = tmp / "test.db" db = tmp / "test.db"
env = {**os.environ, "PORT": str(port), "HOST": "127.0.0.1", "DB_PATH": str(db), "PUBLIC_URL": "", "HEARTBEAT_S": "1", env = {**os.environ, "PORT": str(port), "HOST": "127.0.0.1", "DB_PATH": str(db), "PUBLIC_URL": "", "HEARTBEAT_S": "1"}
"PASS_HOLD_MS": "1500"}
scheme, wscheme, ws_kw = "http", "ws", {} scheme, wscheme, ws_kw = "http", "ws", {}
if TLS: if TLS:
cert, key = tmp / "cert.pem", tmp / "key.pem" cert, key = tmp / "cert.pem", tmp / "key.pem"
@@ -91,8 +90,8 @@ async def projector(server, p, key=None):
async def reader(): async def reader():
async for raw in ws: async for raw in ws:
m = json.loads(raw) m = json.loads(raw)
if m["type"] in ("qr", "ring"): if m["type"] == "qr":
latest.update(tok=m["token"], slot=m["slot"]) latest.update(tok=m["url"].split("#", 1)[1], slot=m["slot"])
changed.set() changed.set()
task = asyncio.create_task(reader()) task = asyncio.create_task(reader())
@@ -169,28 +168,17 @@ def test_full_flow_and_anonymity(server):
assert admin(server, p, "POST", f"/questions/{qid}/close").status_code == 200 assert admin(server, p, "POST", f"/questions/{qid}/close").status_code == 200
q = admin(server, p, "GET", "").json()["questions"][0] q = admin(server, p, "GET", "").json()["questions"][0]
assert q["results"] == {"counts": [1, 0], "blank": 1, "ballots": 2, assert q["results"] == {"counts": [1, 0], "blank": 1, "ballots": 2}
"extra": {"counts": [0, 0], "blank": 0, "ballots": 0}}
r = await a.post(f"/api/v/{p['id']}/vote", json={"question_id": qid, "choices": [0]}) r = await a.post(f"/api/v/{p['id']}/vote", json={"question_id": qid, "choices": [0]})
assert r.status_code == 409 and r.json()["error"] == "not_open" assert r.status_code == 409 and r.json()["error"] == "not_open"
# closed too early: reopening keeps the ballots and the voted flags
assert admin(server, p, "POST", f"/questions/{qid}/reopen").status_code == 200
r = await a.post(f"/api/v/{p['id']}/vote", json={"question_id": qid, "choices": [1]})
assert r.status_code == 409 and r.json()["error"] == "already_voted"
assert admin(server, p, "POST", f"/questions/{qid}/close").status_code == 200
# voters only see results once published # voters only see results once published
me = (await a.get(f"/api/v/{p['id']}/me")).json() me = (await a.get(f"/api/v/{p['id']}/me")).json()
assert me["questions"] == [] assert me["questions"] == []
admin(server, p, "POST", f"/questions/{qid}/publish") admin(server, p, "POST", f"/questions/{qid}/publish")
me = (await a.get(f"/api/v/{p['id']}/me")).json() me = (await a.get(f"/api/v/{p['id']}/me")).json()
assert me["questions"][0]["results"]["counts"] == [1, 0] assert me["questions"][0]["results"]["counts"] == [1, 0]
# once the room has seen the tally there is no going back, even after hiding it
admin(server, p, "POST", f"/questions/{qid}/unpublish")
r = admin(server, p, "POST", f"/questions/{qid}/reopen")
assert r.status_code == 400 and r.json()["error"] == "already_shown"
await a.aclose() await a.aclose()
await b.aclose() await b.aclose()
@@ -202,7 +190,7 @@ def test_full_flow_and_anonymity(server):
assert con.execute("SELECT COUNT(*) FROM participation").fetchone()[0] >= 2 assert con.execute("SELECT COUNT(*) FROM participation").fetchone()[0] >= 2
def test_duplicate_token_counts_once(server): def test_stale_duplicate_and_forged_tokens(server):
p = create(server, scans_required=3) p = create(server, scans_required=3)
admin(server, p, "PATCH", "", json={"enrollment_open": True}) admin(server, p, "PATCH", "", json={"enrollment_open": True})
@@ -212,8 +200,25 @@ def test_duplicate_token_counts_once(server):
tok = await next_token() tok = await next_token()
r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": tok})).json() r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": tok})).json()
assert r["count"] == 1 and r["accepted"] assert r["count"] == 1 and r["accepted"]
# same code twice does not count twice
r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": tok})).json() r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": tok})).json()
assert r["count"] == 1 and not r["accepted"] assert r["count"] == 1 and not r["accepted"]
# forged mac
slot = tok.split(".")[0]
r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": f"{int(slot) + 1}.AAAAAAAAAAAA"})).json()
assert not r["valid"] and r["count"] == 1
# replaying an old photo of the screen
old = await next_token()
await asyncio.sleep(3.2)
r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": old})).json()
assert not r["valid"]
# a token from another poll is useless here
other = create(server)
admin(server, other, "PATCH", "", json={"enrollment_open": True})
async with projector(server, other) as other_next:
ot = await other_next()
r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": ot})).json()
assert not r["valid"]
await c.aclose() await c.aclose()
asyncio.run(run()) asyncio.run(run())
@@ -426,7 +431,7 @@ def proxied(tmp_path_factory):
def test_behind_proxy(proxied): def test_behind_proxy(proxied):
fwd = {"X-Forwarded-Host": "vote.example.org", "X-Forwarded-Proto": "https"} fwd = {"X-Forwarded-Host": "vote.example.org", "X-Forwarded-Proto": "https"}
p = httpx.post(proxied["base"] + "/api/polls", json={"title": "P", "interval_ms": 300, "scans_required": 3, "code_style": "qr"}).json() p = httpx.post(proxied["base"] + "/api/polls", json={"title": "P", "interval_ms": 300, "scans_required": 3}).json()
httpx.patch(f"{proxied['base']}/api/polls/{p['id']}", json={"enrollment_open": True}, httpx.patch(f"{proxied['base']}/api/polls/{p['id']}", json={"enrollment_open": True},
headers={"authorization": f"Bearer {p['admin_key']}"}) headers={"authorization": f"Bearer {p['admin_key']}"})
@@ -435,11 +440,9 @@ def test_behind_proxy(proxied):
await ws.send(json.dumps({"key": p["screen_key"]})) await ws.send(json.dumps({"key": p["screen_key"]}))
while True: while True:
m = json.loads(await asyncio.wait_for(ws.recv(), 3)) m = json.loads(await asyncio.wait_for(ws.recv(), 3))
if m["type"] == "entry":
entry = m
if m["type"] == "qr": if m["type"] == "qr":
break break
assert m["url"] == entry["url"] == f"https://vote.example.org/v/{p['id']}" assert m["url"].startswith(f"https://vote.example.org/v/{p['id']}#")
await ws.close() await ws.close()
# browser origin is the public host, not the rewritten Host: must pass the origin check # browser origin is the public host, not the rewritten Host: must pass the origin check
v = await websockets.connect(f"{proxied['ws']}/ws/{p['id']}/voter", origin="https://vote.example.org", v = await websockets.connect(f"{proxied['ws']}/ws/{p['id']}/voter", origin="https://vote.example.org",
@@ -502,10 +505,9 @@ def test_vote_needs_fresh_presence_scans(server):
await asyncio.sleep(3.5) # photo of the screen taken earlier await asyncio.sleep(3.5) # photo of the screen taken earlier
r = await a.post(url, json={"question_id": qid, "choices": [0], "presence": old}) r = await a.post(url, json={"question_id": qid, "choices": [0], "presence": old})
assert r.json()["error"] == "presence_required" assert r.json()["error"] == "presence_required"
# slow phone: two codes read a while ago and one just now, all distinct, counts fresh = [await next_token() for _ in range(3)]
mixed = old[1:] + [await next_token()] r = await a.post(url, json={"question_id": qid, "choices": [1], "presence": fresh})
r = await a.post(url, json={"question_id": qid, "choices": [1], "presence": mixed}) assert r.status_code == 200
assert r.status_code == 200, r.text
await a.aclose() await a.aclose()
asyncio.run(run()) asyncio.run(run())
@@ -572,16 +574,14 @@ def test_no_presence_qr_when_everyone_has_a_code(server):
ws = await websockets.connect(f"{server['ws']}/ws/{p['id']}/screen", **server["ws_kw"]) ws = await websockets.connect(f"{server['ws']}/ws/{p['id']}/screen", **server["ws_kw"])
await ws.send(json.dumps({"key": p["screen_key"]})) await ws.send(json.dumps({"key": p["screen_key"]}))
st = json.loads(await asyncio.wait_for(ws.recv(), 3)) st = json.loads(await asyncio.wait_for(ws.recv(), 3))
while st["type"] != "state": assert st["type"] == "state" and st["presence"] is False
st = json.loads(await asyncio.wait_for(ws.recv(), 3))
assert st["presence"] is False
t0 = time.time() t0 = time.time()
while time.time() - t0 < 2: while time.time() - t0 < 2:
try: try:
m = json.loads(await asyncio.wait_for(ws.recv(), 0.5)) m = json.loads(await asyncio.wait_for(ws.recv(), 0.5))
except asyncio.TimeoutError: except asyncio.TimeoutError:
continue continue
assert m["type"] not in ("qr", "ring") assert m["type"] != "qr"
await ws.close() await ws.close()
await a.aclose() await a.aclose()
@@ -609,246 +609,3 @@ def test_heartbeat_survives_dead_client(server):
await alive.close() await alive.close()
asyncio.run(run()) asyncio.run(run())
def test_ring_tokens_stale_and_forged(server):
from rotatyvote import tokens as tk
p = create(server, scans_required=3, code_style="ring")
admin(server, p, "PATCH", "", json={"enrollment_open": True})
con = sqlite3.connect(server["db"])
secret, iv = con.execute("SELECT secret, interval_ms FROM polls WHERE id=?", (p["id"],)).fetchone()
con.close()
async def run():
async with projector(server, p) as next_token:
c = device(server)
tok = await next_token()
assert tok.startswith("r")
r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": tok})).json()
assert r["count"] == 1 and r["accepted"]
s16 = int(tok[1:].split(".")[0])
# a camera app code is not a ring code
r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": tk.make_pass(secret, p["id"], 1)})).json()
assert not r["valid"]
# forged mac, malformed
r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": f"r{s16}.00000000"})).json()
assert not r["valid"]
r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": "r99999999.zz"})).json()
assert not r["valid"]
# stale ring code
old = await next_token()
await asyncio.sleep(3.2)
r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": old})).json()
assert not r["valid"]
# ring code of another poll
other = create(server, code_style="ring")
admin(server, other, "PATCH", "", json={"enrollment_open": True})
async with projector(server, other) as other_next:
ot = await other_next()
r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": ot})).json()
assert not r["valid"]
# and a full enrollment with ring codes only
d = device(server)
assert (await scan_until(d, server, p, next_token))["status"] == "enrolled"
for x in (c, d):
await x.aclose()
asyncio.run(run())
def test_entry_redirect(server):
p = create(server)
r = httpx.get(f"{server['base']}/V/{p['id'].upper()}", follow_redirects=False, verify=server["verify"])
assert r.status_code == 301 and r.headers["location"] == f"/v/{p['id']}"
def test_trial_enrolls_then_expires(server):
r = httpx.post(server["base"] + "/api/trial", verify=server["verify"])
assert r.status_code == 200
p = r.json()
assert "admin_key" not in p
async def run():
async with projector(server, p) as next_token:
c = await enroll(server, p, next_token)
# nobody can push a question on a trial, the first phone in opens the sample one
me = (await c.get(f"/api/v/{p['id']}/me")).json()
q = next(q for q in me["questions"] if q["state"] == "open")
assert me["vote_scans"] == 3
fresh = [await next_token() for _ in range(3)]
r = await c.post(f"/api/v/{p['id']}/vote", json={"question_id": q["id"], "choices": [0], "presence": fresh})
assert r.status_code == 200, r.text
await c.aclose()
asyncio.run(run())
# age it past the ttl, the next trial sweeps it away with everything it held
con = sqlite3.connect(server["db"])
con.execute("UPDATE polls SET created_at=created_at-? WHERE id=?", (3 * 3600 * 1000, p["id"]))
con.commit()
assert httpx.post(server["base"] + "/api/trial", verify=server["verify"]).status_code == 200
assert con.execute("SELECT COUNT(*) FROM polls WHERE id=?", (p["id"],)).fetchone()[0] == 0
assert con.execute("SELECT COUNT(*) FROM voters WHERE poll_id=?", (p["id"],)).fetchone()[0] == 0
con.close()
assert httpx.get(f"{server['base']}/screen/{p['id']}", verify=server["verify"]).status_code == 404
def test_hand_added_votes(server):
p = create(server, vote_scans=0)
admin(server, p, "PATCH", "", json={"enrollment_open": True})
async def run():
async with projector(server, p) as next_token:
a = await enroll(server, p, next_token)
qid = admin(server, p, "POST", "/questions", json={"text": "Q", "options": ["A", "B"], "open": True}).json()["id"]
assert (await a.post(f"/api/v/{p['id']}/vote", json={"question_id": qid, "choices": [0]})).status_code == 200
# paper ballots counted at the desk
assert admin(server, p, "POST", f"/questions/{qid}/extra", json={"counts": [2, 5], "blank": 1}).status_code == 200
q = admin(server, p, "GET", "").json()["questions"][0]
assert q["extra_ballots"] == 8 and q["extra"] == {"counts": [2, 5], "blank": 1, "ballots": 8}
assert "results" not in q # still open: no tally, hand-added or not
assert admin(server, p, "POST", f"/questions/{qid}/extra", json={"counts": [1]}).status_code == 400
assert admin(server, p, "POST", f"/questions/{qid}/extra", json={"counts": [-1, 0]}).status_code == 400
admin(server, p, "POST", f"/questions/{qid}/close")
r = admin(server, p, "GET", "").json()["questions"][0]["results"]
# phone ballots and hand-added ones stay apart
assert r["counts"] == [1, 0] and r["ballots"] == 1 and r["extra"]["counts"] == [2, 5]
await a.aclose()
asyncio.run(run())
def test_duplicated_screen_page(server):
p = create(server)
admin(server, p, "PATCH", "", json={"enrollment_open": True})
r = httpx.get(f"{server['base']}/present/{p['id']}", verify=server["verify"])
assert r.status_code == 200
# the admin page may only be framed by the site itself (duplicated screen drawer)
assert r.headers["x-frame-options"] == "SAMEORIGIN" and "frame-ancestors 'self'" in r.headers["content-security-policy"]
assert httpx.get(f"{server['base']}/present/nopenope", verify=server["verify"]).status_code == 404
async def run():
# the duplicated screen talks to the projector socket with the admin key
async with projector(server, p, key=p["admin_key"]) as next_token:
assert (await next_token()) is not None
asyncio.run(run())
async def camera_code(server, p, kind="entry"):
"""the code the camera app would read off the projector right now"""
ws = await websockets.connect(f"{server['ws']}/ws/{p['id']}/screen", **server["ws_kw"])
await ws.send(json.dumps({"key": p["screen_key"]}))
while True:
m = json.loads(await asyncio.wait_for(ws.recv(), 5))
if m["type"] == kind:
await ws.close()
return m
def test_camera_app_scan_enrolls_and_covers_votes(server):
from rotatyvote import tokens as tk
p = create(server, scans_required=5, vote_scans=3)
admin(server, p, "PATCH", "", json={"enrollment_open": True})
async def run():
e = await camera_code(server, p)
assert len(e["modules"]) == 33
a = device(server)
r = await a.get(f"/V/{p['id'].upper()}/{e['token'].upper()}", follow_redirects=False)
assert r.status_code == 303 and "no-store" in r.headers["cache-control"]
loc = r.headers["location"]
assert loc.startswith(f"/v/{p['id']}#c=")
claim = loc.split("#c=")[1]
# one scan is enough to enroll, the claim is single use
assert (await a.post(f"/api/v/{p['id']}/pass", json={"claim": claim})).json()["status"] == "enrolled"
b = device(server)
assert (await b.post(f"/api/v/{p['id']}/pass", json={"claim": claim})).json()["status"] == "expired"
url = f"/api/v/{p['id']}/vote"
q1 = admin(server, p, "POST", "/questions", json={"text": "Q1", "options": ["A", "B"], "open": True}).json()["id"]
# the scan that enrolled also covers a vote right after
assert (await a.post(url, json={"question_id": q1, "choices": [0]})).status_code == 200
await asyncio.sleep(1.6)
admin(server, p, "POST", f"/questions/{q1}/close")
q2 = admin(server, p, "POST", "/questions", json={"text": "Q2", "options": ["A", "B"], "open": True}).json()["id"]
r = await a.post(url, json={"question_id": q2, "choices": [1]})
assert r.json()["error"] == "presence_required"
# rescan with the camera app (or the page's camera on the classic qr): the code itself
e = await camera_code(server, p)
assert (await a.post(f"/api/v/{p['id']}/pass", json={"token": e["token"]})).json()["status"] == "pass"
assert (await a.post(url, json={"question_id": q2, "choices": [1]})).status_code == 200
# forged, malformed, other poll, stale
bad = await a.get(f"/V/{p['id']}/{e['slot']}-AAAAAAAAAA", follow_redirects=False)
assert bad.headers["location"] == f"/v/{p['id']}#cam=expired"
bad = await a.get(f"/V/{p['id']}/%C3%A9-%C3%A9", follow_redirects=False)
assert bad.headers["location"] == f"/v/{p['id']}#cam=expired"
other = create(server)
admin(server, other, "PATCH", "", json={"enrollment_open": True})
oe = await camera_code(server, other)
assert (await b.post(f"/api/v/{p['id']}/pass", json={"token": oe["token"]})).json()["status"] == "expired"
con = sqlite3.connect(server["db"])
secret = con.execute("SELECT secret FROM polls WHERE id=?", (p["id"],)).fetchone()[0]
con.close()
stale = tk.make_pass(secret, p["id"], e["slot"] - 6)
assert (await b.post(f"/api/v/{p['id']}/pass", json={"token": stale})).json()["status"] == "expired"
# gone from the screen 6 s ago: too late to join (4 s), still fine for a vote (12 s)
recent = tk.make_pass(secret, p["id"], tk.current_slot(3000) - 3)
assert (await b.post(f"/api/v/{p['id']}/pass", json={"token": recent})).json()["status"] == "late"
assert (await a.post(f"/api/v/{p['id']}/pass", json={"token": recent})).json()["status"] == "pass"
# late arrival after enrollment closed: nothing to do here
admin(server, p, "PATCH", "", json={"enrollment_open": False})
e = await camera_code(server, p)
assert (await b.post(f"/api/v/{p['id']}/pass", json={"token": e["token"]})).json()["status"] == "closed"
for x in (a, b):
await x.aclose()
asyncio.run(run())
def test_camera_app_scan_then_paper_code(server):
p = create(server, require_code=True, codes=2)
admin(server, p, "PATCH", "", json={"enrollment_open": True})
code = admin(server, p, "GET", "/codes").json()["codes"][0]["code"]
async def run():
e = await camera_code(server, p)
a = device(server)
assert (await a.post(f"/api/v/{p['id']}/pass", json={"token": e["token"]})).json()["status"] == "need_code"
assert (await a.get(f"/api/v/{p['id']}/me")).json()["need_code"]
assert (await a.post(f"/api/v/{p['id']}/code", json={"code": code})).json()["status"] == "enrolled"
await a.aclose()
asyncio.run(run())
def test_classic_qr_is_the_camera_code(server):
p = create(server, code_style="qr", vote_scans=2)
admin(server, p, "PATCH", "", json={"enrollment_open": True})
async def run():
m = await camera_code(server, p, "qr")
assert m["interval_ms"] == 3000 and len(m["modules"]) == 33
a = device(server)
assert (await a.post(f"/api/v/{p['id']}/pass", json={"token": m["token"]})).json()["status"] == "enrolled"
await a.aclose()
asyncio.run(run())
def test_camera_app_scan_can_be_turned_off(server):
p = create(server, camera_pass=False)
admin(server, p, "PATCH", "", json={"enrollment_open": True})
assert admin(server, p, "GET", "").json()["poll"]["camera_pass"] is False
async def run():
e = await camera_code(server, p)
assert "token" not in e and len(e["modules"]) == 29
a = device(server)
r = await a.get(f"/V/{p['id']}/1-AAAAAAAAAA", follow_redirects=False)
assert r.headers["location"] == f"/v/{p['id']}"
assert (await a.post(f"/api/v/{p['id']}/pass", json={"token": "1-AAAAAAAAAA"})).json()["status"] == "off"
admin(server, p, "PATCH", "", json={"camera_pass": True})
e = await camera_code(server, p)
assert (await a.post(f"/api/v/{p['id']}/pass", json={"token": e["token"]})).json()["status"] == "enrolled"
await a.aclose()
asyncio.run(run())
+71 -1
View File
@@ -1,10 +1,13 @@
"""tiny chrome devtools protocol client for the ring bench: headless chrome, pages, eval""" """tiny chrome devtools protocol client: headless chrome, pages, eval, screencast"""
import asyncio import asyncio
import base64
import itertools import itertools
import json import json
import os
import shutil import shutil
import subprocess import subprocess
import tempfile import tempfile
import time
import urllib.request import urllib.request
import websockets import websockets
@@ -93,6 +96,7 @@ class Page:
def __init__(self, browser, sid, w, h, dsf): def __init__(self, browser, sid, w, h, dsf):
self.b, self.sid, self.w, self.h, self.dsf = browser, sid, w, h, dsf self.b, self.sid, self.w, self.h, self.dsf = browser, sid, w, h, dsf
self.load = None self.load = None
self.frames = None
def send(self, method, params=None): def send(self, method, params=None):
return self.b.send(method, params, self.sid) return self.b.send(method, params, self.sid)
@@ -100,6 +104,15 @@ class Page:
def _event(self, method, params): def _event(self, method, params):
if method == "Page.loadEventFired" and self.load and not self.load.done(): if method == "Page.loadEventFired" and self.load and not self.load.done():
self.load.set_result(True) self.load.set_result(True)
elif method == "Page.screencastFrame":
if self.frames is not None:
ts = params["metadata"].get("timestamp", time.time())
path = os.path.join(self.frame_dir, f"{len(self.frames):06d}.jpg")
with open(path, "wb") as f:
f.write(base64.b64decode(params["data"]))
self.frames.append((ts, path))
asyncio.get_running_loop().create_task(
self.send("Page.screencastFrameAck", {"sessionId": params["sessionId"]}))
async def goto(self, url): async def goto(self, url):
self.load = asyncio.get_running_loop().create_future() self.load = asyncio.get_running_loop().create_future()
@@ -111,3 +124,60 @@ class Page:
if "exceptionDetails" in r: if "exceptionDetails" in r:
raise RuntimeError(r["exceptionDetails"].get("exception", {}).get("description", r["exceptionDetails"])) raise RuntimeError(r["exceptionDetails"].get("exception", {}).get("description", r["exceptionDetails"]))
return r.get("result", {}).get("value") return r.get("result", {}).get("value")
async def on_new_document(self, source):
await self.send("Page.addScriptToEvaluateOnNewDocument", {"source": source})
async def record(self, frame_dir):
os.makedirs(frame_dir, exist_ok=True)
self.frame_dir = frame_dir
self.frames = []
await self.send("Page.startScreencast", {"format": "jpeg", "quality": 90,
"maxWidth": int(self.w * self.dsf), "maxHeight": int(self.h * self.dsf)})
async def stop(self):
if getattr(self, "shooter", None):
self.shooting = False
try:
await asyncio.wait_for(self.shooter, 3)
except Exception:
self.shooter.cancel()
else:
try:
await asyncio.wait_for(self.send("Page.stopScreencast"), 3)
except Exception:
pass
async def record_shots(self, frame_dir, fps=24):
"""screenshot polling: slower than screencast but honours deviceScaleFactor"""
os.makedirs(frame_dir, exist_ok=True)
self.frames, self.shooting = [], True
async def loop():
while self.shooting:
t = time.time()
r = await self.send("Page.captureScreenshot", {"format": "jpeg", "quality": 90})
path = os.path.join(frame_dir, f"{len(self.frames):06d}.jpg")
with open(path, "wb") as f:
f.write(base64.b64decode(r["data"]))
self.frames.append((t, path))
await asyncio.sleep(max(0, 1 / fps - (time.time() - t)))
self.shooter = asyncio.get_running_loop().create_task(loop())
async def png(self, path, transparent=False):
if transparent:
await self.send("Emulation.setDefaultBackgroundColorOverride", {"color": {"r": 0, "g": 0, "b": 0, "a": 0}})
r = await self.send("Page.captureScreenshot", {"format": "png"})
with open(path, "wb") as f:
f.write(base64.b64decode(r["data"]))
async def mouse(self, kind, x, y, button="left", clicks=1):
await self.send("Input.dispatchMouseEvent",
{"type": kind, "x": x, "y": y, "button": button, "clickCount": clicks})
async def type(self, text, rng, target="document.activeElement"):
# write into the field directly: focus can drift between headless targets while screenshotting
await self.js(f"window.__tt = {target}; __tt.focus()")
for ch in text:
await self.js("__tt.value += " + json.dumps(ch) + "; __tt.dispatchEvent(new Event('input', {bubbles: true}))")
await asyncio.sleep(rng.uniform(0.05, 0.14) + (0.18 if ch == " " and rng.random() < 0.2 else 0))
+28 -224
View File
@@ -1,13 +1,10 @@
"""ring code bench: renders codes with perspective, blur, washed contrast and clutter in headless chrome, """ring code bench: renders codes with perspective, blur, washed contrast and clutter in headless chrome,
runs the real decoder and prints read rates. usage: uv run python tools/ringbench.py [trials per cell] runs the real decoder and prints read rates. usage: uv run python tools/ringbench.py [trials per cell]"""
env: SUITE=legacy,far,glare,seq,neg (default all but glare) PIPES=legacy,cap960,scan DIAG=legacy|native FAR_D=80,100 NEG=300
IV=700 FADE_K=0.3 (sequence code interval and wipe share) CPU=6 (slow phone) V1=1 (decoder and dash design from before the far-reading work, the baseline)"""
import asyncio import asyncio
import base64 import base64
import collections import collections
import itertools import itertools
import json import json
import math
import os import os
import random import random
import subprocess import subprocess
@@ -22,8 +19,7 @@ sys.path.insert(0, str(ROOT / "tools"))
from cdp import Browser # noqa: E402 from cdp import Browser # noqa: E402
from rotatyvote import ringcode # noqa: E402 from rotatyvote import ringcode # noqa: E402
PORT = int(os.environ.get("BENCH_PORT", "8200")) PORT = 8200
V1 = bool(os.environ.get("V1"))
rng = random.Random(11) rng = random.Random(11)
@@ -49,213 +45,8 @@ def trials(n):
return out return out
def code(r):
secret, slot = r.randbytes(32), r.randrange(1 << 36)
return {"bits": ringcode.render_bits(secret, "abcdefgh", 500, slot), "token": ringcode.token(secret, "abcdefgh", 500, slot)}
# washed projector: (black level, white level) of the screen as the camera sees it
WASH = {1.0: (0, 255), 0.45: (80, 195), 0.3: (105, 181)}
SENSORS = {1280: (1280, 720), 1920: (1920, 1080)}
def camera(r, d, contrast, blur, sensor):
"""one phone looking at a projected code d px wide in a 1280 px frame, plus what a real room adds"""
W, H = SENSORS[sensor]
return {"W": W, "H": H, "d": d, "frac": d / 1280, "contrast": contrast, "wash": WASH[contrast], "blur": blur, "sensor": sensor,
# optical blur is angular, pixel softness (demosaic, video codec) is per sensor pixel
"oblur": blur, "pblur": 0.6 + 0.2 * blur,
"cast": [r.uniform(0.9, 1.0), 1.0, r.uniform(0.95, 1.1)], "gain": r.uniform(0.85, 1.2),
"room": r.choice(["dark", "dark", "bright"]), "band": r.choice([0, 0, 0.06, 0.1]), "bandPeriod": r.uniform(40, 200),
"noise": r.uniform(4, 8), "axis": r.uniform(0, 360), "dx": r.uniform(-250, 250) * W / 1280, "dy": r.uniform(-120, 120) * W / 1280,
"theta": r.uniform(0, 6.283), "anim": r.uniform(0, 100), "qseed": r.randrange(1 << 20)}
def far_trials(n):
r = random.Random(23)
out = []
sizes = [int(x) for x in os.environ.get("FAR_D", "80,100,120,150,180").split(",")]
for d, contrast, blur, tilt, sensor in itertools.product(sizes, [0.45, 0.3], [0.7, 1.5], [0, 20], [1280, 1920]):
for _ in range(n):
t = camera(r, d, contrast, blur, sensor)
m = r.uniform(0, 1.5), r.uniform(0, 6.283)
t.update(code(r), tilt=tilt, motion=[m[0] * math.cos(m[1]), m[0] * math.sin(m[1])], jpeg=r.choice([0, 0, 0.6]))
out.append(t)
return out
def glare_trials(n):
"""a reflection on the screen lights part of the code, often with a laptop lid or screen seen at an angle"""
r = random.Random(53)
out = []
for d, tilt, strength, contrast in itertools.product([150, 250, 350], [0, 30, 45], [0.35, 0.6], [1.0, 0.45]):
for _ in range(n):
t = camera(r, d, contrast, r.choice([0.7, 1.5]), 1920)
a, k = r.uniform(0, 6.283), r.uniform(0.1, 0.6)
tint = r.choice([(255, 235, 245), (255, 250, 230), (230, 240, 255)])
t.update(code(r), tilt=tilt, glare=[k * math.cos(a), k * math.sin(a), r.uniform(0.5, 1.1), strength, tint],
glareS=strength, jpeg=r.choice([0, 0.6]))
out.append(t)
return out
async def run_glare(p, n, pipes):
diag = os.environ.get("DIAG")
res = await chunks(p, "runFar", "trials", glare_trials(n), {"pipes": pipes, "keep": 3, "diag": diag}, 10)
print(f"\n== reflection on the screen, single frames ({len(res)} frames), 1920 sensor ==")
table(res, ("d", "tilt", "glareS", "contrast"), pipes)
for pn in pipes:
wrong = sum(1 for r in res if r[pn]["token"] and not r[pn]["ok"])
print(f" {pn}: read {100 * sum(r[pn]['ok'] for r in res) / len(res):.0f} %, false tokens {wrong}")
if diag:
# where failing frames break when the true geometry is substituted stage by stage
for key in ("tilt", "glareS"):
for v in sorted({r[key] for r in res}):
sub = [r for r in res if r[key] == v and not r[pipes[0]]["ok"]]
st = collections.Counter(r["diag"]["stage"] for r in sub)
print(f" {key} {v}: {len(sub)} failures by stage {dict(st)} oracle sync {sum((r['diag']['oracleScore'] or 0) for r in sub) / max(1, len(sub)):.2f}"
f" byte errs with true geometry {sum(r['diag']['byteErr'] for r in sub) / max(1, len(sub)):.1f}")
out = ROOT / "tools" / "bench_out"
out.mkdir(exist_ok=True)
for i, r in enumerate(res[:3]):
if r.get("png"):
(out / f"glare_{i}.jpg").write_bytes(base64.b64decode(r["png"].split(",")[1]))
def neg_trials(n):
"""nothing to read: no code on the screen, bare dark discs, discs with pie-like arcs around"""
r = random.Random(31)
out = []
for i in range(n):
t = camera(r, r.choice([80, 120, 180, 300]), r.choice([0.45, 0.3]), r.choice([0.7, 1.5]), r.choice([1280, 1920]))
t.update(tilt=r.choice([0, 20]), nocode=True, decoy=i % 3)
out.append(t)
return out
def seqs(n):
r = random.Random(47)
out = []
fpss = [int(x) for x in os.environ.get("FPS", "15,7").split(",")]
for d, contrast, fps in itertools.product([60, 70, 80, 100, 120, 150], [0.45, 0.3], fpss):
for _ in range(n):
s = camera(r, d, contrast, r.choice([0.7, 1.5]), 1920)
iv = int(os.environ.get("IV", "500"))
s.update(tilt=r.choice([0, 10, 20]), fps=fps, secs=6, interval=iv, shake=r.uniform(0.3, 1.2),
fadeK=float(os.environ.get("FADE_K", "0.25")),
tokens=[code(r) for _ in range(14)], t0=r.randrange(1 << 20) * iv + r.uniform(0, iv * 0.8))
out.append(s)
return out
def table(rows, keys, pipes):
for key in keys:
vals = sorted({r[key] for r in rows})
for p in pipes:
cells = []
for v in vals:
sub = [r for r in rows if r[key] == v]
cells.append(f"{v}: {100 * sum(r[p]['ok'] for r in sub) / len(sub):3.0f}%")
print(f" {key:9s}{p:7s}", " ".join(cells))
async def chunks(p, fn, key, items, cfg, size):
# cdp calls time out after 60 s
out = []
for i in range(0, len(items), size):
out += await p.js(f"{fn}({json.dumps({**cfg, key: items[i:i + size], 'seed': 1000 + i, 'v1': V1})})")
return out
async def run_legacy(p, n):
ts = trials(n)
res = await p.js(f"runBench({json.dumps({'trials': ts, 'keep': 4, 'v1': V1})})")
harsh = [r for r in res if r.get("harsh")]
print(f"harsh perspective (close-up, 25 deg): {sum(r['ok'] for r in harsh)}/{len(harsh)}")
codes = [r for r in res if not r.get("nocode") and not r.get("harsh")]
for key in ("d", "tilt", "blur", "contrast"):
agg = collections.defaultdict(lambda: [0, 0, 0])
for r in codes:
a = agg[r[key]]
a[0] += 1; a[1] += (r["found"] or 0) > 0; a[2] += r["ok"]
print(f"{key:8s}", " ".join(f"{k}: ok {v[2]}/{v[0]}" for k, v in sorted(agg.items())))
ok = sum(r["ok"] for r in codes)
ms = sorted(r['ms'] for r in res)
print(f"codes read {ok}/{len(codes)} ({100 * ok / len(codes):.0f} %), decode ms/frame median {ms[len(ms) // 2]} p90 {ms[int(len(ms) * .9)]}")
fails = [r for r in codes if not r["ok"]]
print("failures (d, tilt, blur, contrast, found, score, errs):",
[(r["d"], r["tilt"], r["blur"], r["contrast"], r["found"], r["score"], r.get("errs")) for r in fails[:16]])
wrong = [r for r in res if r["token"] and not r["ok"]]
print("false tokens:", len(wrong), "(no-code frames:", sum(1 for r in res if r.get("nocode")), ")")
out = ROOT / "tools" / "bench_out"
out.mkdir(exist_ok=True)
for i, r in enumerate(res[:4]):
if r.get("png"):
(out / f"sample_{i}.jpg").write_bytes(base64.b64decode(r["png"].split(",")[1]))
async def run_far(p, n, pipes, diag):
ts = far_trials(n)
res = await chunks(p, "runFar", "trials", ts, {"pipes": pipes, "diag": diag, "keep": 3}, 10)
print(f"\n== far + washed projector, single frames ({len(res)} frames), d = code diameter in a 1280 px wide frame ==")
table(res, ("d", "contrast", "blur", "tilt", "sensor", "room"), pipes)
for pn in pipes:
ms = sorted(r[pn]["ms"] for r in res)
wrong = sum(1 for r in res if r[pn]["token"] and not r[pn]["ok"])
print(f" {pn}: read {100 * sum(r[pn]['ok'] for r in res) / len(res):.0f} %, ms/frame median {ms[len(ms) // 2]} p90 {ms[int(len(ms) * .9)]}, false tokens {wrong}")
if diag:
print(f" where {diag} resolution frames break (truth substituted stage by stage):")
for d in sorted({r["d"] for r in res}):
sub = [r["diag"] for r in res if r["d"] == d]
good = [x for x in sub if x["rank"] in range(4) and x.get("candOk")]
st = collections.Counter(x["stage"] + ("/" + x["loc"] if x["stage"] == "locate" else "") for x in sub if x not in good)
print(f" d {d}: ok {len(good)}/{len(sub)} fails by stage {dict(st)}"
f" bit errs with true geometry {sum(x['bitErr'] for x in sub) / len(sub):.1f} (ideal thr {sum(x['idealErr'] for x in sub) / len(sub):.1f})"
f" worst-ring d' {sum(min(x['dprime']) for x in sub) / len(sub):.1f} sync span {sum(x['span'] for x in sub) / len(sub):.0f} levels")
print(" bit errors with true geometry per decision rule, and bleed model (own, ring neighbours, adjacent rings, residual):")
for d in sorted({r["d"] for r in res}):
labs = [r["diag"]["lab"] for r in res if r["d"] == d and "isi" in r["diag"]["lab"]]
keys = [k for k in labs[0] if k != "isi"]
isi = [sum(x["isi"][i] for x in labs) / len(labs) for i in range(5)]
print(f" d {d}: " + " ".join(f"{k} {sum(x.get(k, 0) for x in labs) / len(labs):.1f}" for k in keys)
+ f" | own {isi[1]:.2f} ang {isi[2]:.2f} rad {isi[3]:.2f} resid {isi[4]:.2f}")
out = ROOT / "tools" / "bench_out"
out.mkdir(exist_ok=True)
for i, r in enumerate(res[:3]):
if r.get("png"):
(out / f"far_{i}.jpg").write_bytes(base64.b64decode(r["png"].split(",")[1]))
return res
async def run_neg(p, n, pipes):
ts = neg_trials(n)
res = await chunks(p, "runFar", "trials", ts, {"pipes": pipes}, 10)
print(f"\n== negatives ({len(res)} frames without a code) ==")
for pn in pipes:
print(f" {pn}: false tokens {sum(1 for r in res if r[pn]['token'])}")
async def run_seq(p, n, pipes):
ss = seqs(n)
res = await chunks(p, "runSeq", "seqs", ss, {"pipes": pipes}, 1)
print(f"\n== far sequences: 6 s = 12 tokens shown, 1920x1080 sensor, hand shake ({len(res)} sequences) ==")
for key in ("d", "contrast", "fps"):
for pn in pipes:
cells = []
for v in sorted({r[key] for r in res}):
sub = [r[pn] for r in res if r[key] == v]
done = sorted(x["first5"] for x in sub if x["first5"] is not None)
med = f"{done[len(done) // 2]:.1f}s" if done else "-"
cells.append(f"{v}: {sum(x['got'] for x in sub) / len(sub):4.1f} tok, 5 in 6s {100 * len(done) / len(sub):3.0f}% ({med})")
print(f" {key:9s}{pn:7s}", " ".join(cells))
for pn in pipes:
print(f" {pn}: false tokens {sum(r[pn]['false'] for r in res)}, ms/frame {sum(r[pn]['ms'] for r in res) / len(res):.1f}")
async def main(): async def main():
n = int(sys.argv[1]) if len(sys.argv) > 1 else 3 n = int(sys.argv[1]) if len(sys.argv) > 1 else 3
suites = os.environ.get("SUITE", "legacy,far,seq,neg").split(",")
pipes = os.environ.get("PIPES", "legacy" if V1 else "scan").split(",")
env = {**os.environ, "PORT": str(PORT), "HOST": "127.0.0.1", "DB_PATH": "/tmp/rv-bench.db"} env = {**os.environ, "PORT": str(PORT), "HOST": "127.0.0.1", "DB_PATH": "/tmp/rv-bench.db"}
server = subprocess.Popen([sys.executable, "-m", "rotatyvote"], cwd=ROOT, env=env, server = subprocess.Popen([sys.executable, "-m", "rotatyvote"], cwd=ROOT, env=env,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
@@ -266,7 +57,7 @@ async def main():
break break
except httpx.HTTPError: except httpx.HTTPError:
await asyncio.sleep(0.1) await asyncio.sleep(0.1)
b = Browser(int(os.environ.get("CDP_PORT", "9336"))) b = Browser(9336)
await b.start() await b.start()
p = await b.page(960, 720) p = await b.page(960, 720)
throttle = float(os.environ.get("CPU", "1")) throttle = float(os.environ.get("CPU", "1"))
@@ -278,20 +69,33 @@ async def main():
if await p.js("!!window.benchReady"): if await p.js("!!window.benchReady"):
break break
await asyncio.sleep(0.1) await asyncio.sleep(0.1)
if "legacy" in suites: ts = trials(n)
await run_legacy(p, n) res = await p.js(f"runBench({json.dumps({'trials': ts, 'keep': 4})})")
if "far" in suites: harsh = [r for r in res if r.get("harsh")]
await run_far(p, n, pipes, os.environ.get("DIAG")) print(f"harsh perspective (close-up, 25 deg): {sum(r['ok'] for r in harsh)}/{len(harsh)}")
if "glare" in suites: codes = [r for r in res if not r.get("nocode") and not r.get("harsh")]
await run_glare(p, n, pipes) for key in ("d", "tilt", "blur", "contrast"):
if "seq" in suites: agg = collections.defaultdict(lambda: [0, 0, 0])
await run_seq(p, max(1, n // 2), pipes) for r in codes:
if "neg" in suites: a = agg[r[key]]
await run_neg(p, int(os.environ.get("NEG", "300")), pipes) a[0] += 1; a[1] += (r["found"] or 0) > 0; a[2] += r["ok"]
print(f"{key:8s}", " ".join(f"{k}: ok {v[2]}/{v[0]}" for k, v in sorted(agg.items())))
ok = sum(r["ok"] for r in codes)
ms = sorted(r['ms'] for r in res)
print(f"codes read {ok}/{len(codes)} ({100 * ok / len(codes):.0f} %), decode ms/frame median {ms[len(ms) // 2]} p90 {ms[int(len(ms) * .9)]}")
fails = [r for r in codes if not r["ok"]]
print("failures (d, tilt, blur, contrast, found, score, errs):",
[(r["d"], r["tilt"], r["blur"], r["contrast"], r["found"], r["score"], r.get("errs")) for r in fails[:16]])
wrong = [r for r in res if r["token"] and not r["ok"]]
print("false tokens:", len(wrong), "(no-code frames:", sum(1 for r in res if r.get("nocode")), ")")
out = ROOT / "tools" / "bench_out"
out.mkdir(exist_ok=True)
for i, r in enumerate(res[:4]):
if r.get("png"):
(out / f"sample_{i}.jpg").write_bytes(base64.b64decode(r["png"].split(",")[1]))
await b.close() await b.close()
finally: finally:
server.terminate() server.terminate()
if __name__ == "__main__": asyncio.run(main())
asyncio.run(main())