Overlay de dessin partagé pour les jeux en stream
Un hôte partage son écran dans Discord ; show-me y affiche un overlay transparent où apparaissent les traits de tous les participants, relayés par un petit serveur WebSocket. - Serveur relais : salons à code, mode d'effacement auto ou manuel modifiable en direct. - Client Wayland (layer-shell) et Xorg : trait libre, ping, passage des clics hors mode dessin, commandes locales par socket Unix. - Spectateur : écho local des traits et calage interactif de la zone de dessin sur la vidéo, avec repères affichés chez l'hôte. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
commit
5c98f5dc9f
|
|
@ -0,0 +1 @@
|
|||
target/
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,7 @@
|
|||
[workspace]
|
||||
resolver = "2"
|
||||
members = ["crates/protocol", "crates/server", "crates/client"]
|
||||
|
||||
[profile.release]
|
||||
lto = "thin"
|
||||
strip = true
|
||||
|
|
@ -0,0 +1,115 @@
|
|||
# show-me
|
||||
|
||||
Dessiner à plusieurs sur l'écran de celui qui stream, pour jouer ensemble à distance à des jeux
|
||||
d'énigmes ou de point and click.
|
||||
|
||||
## Principe
|
||||
|
||||
Un joueur, l'**hôte**, partage son écran entier dans Discord. show-me affiche chez lui un overlay
|
||||
transparent où apparaissent les traits de tout le monde : comme ils sont sur son écran, tous les
|
||||
spectateurs du stream les voient, sans rien installer.
|
||||
|
||||
Les **spectateurs** qui veulent dessiner lancent show-me par-dessus la vidéo du stream. Leurs
|
||||
traits partent vers l'hôte par un petit serveur relais. Chez eux, un trait ne reste affiché qu'un
|
||||
instant (l'« écho »), le temps que la version dessinée chez l'hôte arrive par le stream.
|
||||
|
||||
Linux uniquement : Wayland (compositeurs gérant wlr-layer-shell) et Xorg.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
cargo build --release
|
||||
```
|
||||
|
||||
Deux binaires sont produits dans `target/release/` : `show-me` (le client) et `show-me-server`
|
||||
(le relais). Ils ne dépendent que de la libc.
|
||||
|
||||
## Serveur relais
|
||||
|
||||
```bash
|
||||
show-me-server --listen 127.0.0.1:7878
|
||||
```
|
||||
|
||||
Le serveur parle WebSocket sans chiffrement : placez-le derrière un reverse proxy (Caddy, nginx)
|
||||
qui fournit le `wss://`. Il ne conserve rien ; le code du salon sert de secret partagé.
|
||||
|
||||
## Utilisation
|
||||
|
||||
```bash
|
||||
# L'hôte, qui partage son écran entier dans Discord
|
||||
show-me run --server wss://show-me.example.org --room CODE --host
|
||||
|
||||
# Un spectateur
|
||||
show-me run --server wss://show-me.example.org --room CODE
|
||||
```
|
||||
|
||||
L'overlay ne capte ni la souris ni le clavier tant qu'on n'est pas en mode dessin. Il se pilote
|
||||
par des commandes, à lier à des raccourcis clavier du bureau :
|
||||
|
||||
| Commande | Effet |
|
||||
|---|---|
|
||||
| `show-me toggle` | entre ou sort du mode dessin |
|
||||
| `show-me clear` | efface mes traits |
|
||||
| `show-me clear --all` | efface les traits de tout le monde |
|
||||
| `show-me mode auto [secondes]` | les traits s'estompent tout seuls (5 s par défaut) |
|
||||
| `show-me mode manual` | les traits restent jusqu'à un « effacer » |
|
||||
| `show-me calibrate` | spectateur : cale la zone de dessin sur la vidéo |
|
||||
| `show-me calibrate reset` | spectateur : revient au calage plein écran |
|
||||
| `show-me quit` | arrête l'overlay |
|
||||
|
||||
En mode dessin, un cadre de couleur entoure la zone : clic gauche maintenu pour tracer, clic droit
|
||||
pour un « ping » (cercle animé). Le mode d'effacement vaut pour tout le salon et se change à tout
|
||||
moment.
|
||||
|
||||
Options de `show-me run` : `--name`, `--color rrggbb`, `--width` (épaisseur du trait),
|
||||
`--echo-secs` (durée de l'écho), `--monitor N`, `--region x,y,largeur,hauteur`,
|
||||
`--backend wayland|x11`.
|
||||
|
||||
### Caler la zone de dessin (spectateur)
|
||||
|
||||
Par défaut, show-me suppose que la vidéo du stream occupe tout l'écran. Si ce n'est pas le cas :
|
||||
|
||||
1. Lancez `show-me calibrate`. L'écran s'assombrit, et des repères blancs apparaissent aux quatre
|
||||
coins de l'écran de l'hôte, donc dans la vidéo.
|
||||
2. Glissez la souris d'un repère au repère opposé. Le rectangle est ajusté aux proportions de
|
||||
l'écran de l'hôte ; recommencez autant de fois que nécessaire.
|
||||
3. Validez par un clic droit.
|
||||
|
||||
La zone est enregistrée dans `~/.config/show-me/region` et reprise aux lancements suivants.
|
||||
|
||||
### Selon le système d'affichage
|
||||
|
||||
- **Wayland** : le compositeur doit gérer wlr-layer-shell (Sway, Hyprland, niri, River, KDE ; pas
|
||||
GNOME). Liez les commandes dans sa configuration, par exemple sous Sway
|
||||
`bindsym $mod+d exec show-me toggle`.
|
||||
- **Xorg** : la transparence exige un compositeur (intégré à Cinnamon, KDE, Xfce ; `picom`
|
||||
sinon). Liez les commandes dans les raccourcis clavier du bureau.
|
||||
|
||||
## Limites connues
|
||||
|
||||
- L'hôte doit partager son écran entier : une capture de fenêtre ne contient pas l'overlay.
|
||||
- Le serveur ne garde pas d'historique : un hôte qui relance show-me perd les traits affichés.
|
||||
- Sous Wayland avec mise à l'échelle (HiDPI), les traits sont rendus à la résolution logique.
|
||||
- Un changement de résolution en cours de route oblige à relancer show-me.
|
||||
- Pas encore testé avec une capture Discord réelle ni par-dessus un jeu en plein écran.
|
||||
|
||||
## Développement
|
||||
|
||||
- `crates/protocol` : messages JSON échangés ; coordonnées normalisées de 0 à 1 par rapport à
|
||||
l'écran de l'hôte.
|
||||
- `crates/server` : salons et diffusion.
|
||||
- `crates/client` : `scene.rs` (traits, estompage, rendu), `app.rs` (boucle principale),
|
||||
`net.rs` (connexion au relais), `ipc.rs` (commandes locales), `config.rs` (zone enregistrée),
|
||||
`backend/` (une implémentation par système d'affichage).
|
||||
|
||||
```bash
|
||||
cargo test
|
||||
```
|
||||
|
||||
Le backend Wayland se teste sans session Wayland : Sway peut tourner sans écran
|
||||
(`WLR_BACKENDS=headless`), on capture avec `grim` et on simule la souris avec
|
||||
`crates/client/examples/vptr.rs` (`cargo build --release --examples`). Le `XDG_RUNTIME_DIR`
|
||||
utilisé doit avoir un chemin court, sinon Sway ne peut pas créer son socket.
|
||||
|
||||
`scripts/test-remote.sh MACHINE` lance un test à deux machines : serveur et spectateur ici, hôte
|
||||
Wayland (Sway dans une fenêtre) sur une seconde machine joignable en SSH.
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
[package]
|
||||
name = "show-me"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.104"
|
||||
clap = { version = "4.6.7", features = ["derive"] }
|
||||
futures-util = "0.3.34"
|
||||
rustls = { version = "0.23.46", default-features = false, features = ["ring", "std", "tls12"] }
|
||||
serde_json = "1.0.154"
|
||||
show-me-protocol = { version = "0.1.0", path = "../protocol" }
|
||||
smithay-client-toolkit = { version = "0.21.1", default-features = false }
|
||||
tiny-skia = "0.12.0"
|
||||
tokio = { version = "1.54.1", features = ["rt", "macros", "net", "sync", "time"] }
|
||||
tokio-tungstenite = { version = "0.30.0", features = ["rustls-tls-webpki-roots"] }
|
||||
x11rb = { version = "0.14.0", features = ["xfixes", "randr"] }
|
||||
|
||||
[dev-dependencies]
|
||||
wayland-client = "0.31"
|
||||
wayland-protocols-wlr = { version = "0.3.12", features = ["client"] }
|
||||
|
|
@ -0,0 +1,77 @@
|
|||
//! Outil de test : pilote un pointeur virtuel (protocole wlr-virtual-pointer).
|
||||
//!
|
||||
//! Usage : vptr LARGEUR HAUTEUR [move X Y | down N | up N | sleep MS]...
|
||||
//! où N est 1 (gauche) ou 3 (droit). Sert à tester l'overlay dans un Sway sans écran.
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use wayland_client::globals::{GlobalListContents, registry_queue_init};
|
||||
use wayland_client::protocol::wl_pointer::ButtonState;
|
||||
use wayland_client::protocol::wl_registry;
|
||||
use wayland_client::{Connection, Dispatch, QueueHandle, delegate_noop};
|
||||
use wayland_protocols_wlr::virtual_pointer::v1::client::zwlr_virtual_pointer_manager_v1::ZwlrVirtualPointerManagerV1;
|
||||
use wayland_protocols_wlr::virtual_pointer::v1::client::zwlr_virtual_pointer_v1::ZwlrVirtualPointerV1;
|
||||
|
||||
struct State;
|
||||
|
||||
impl Dispatch<wl_registry::WlRegistry, GlobalListContents> for State {
|
||||
fn event(
|
||||
_: &mut Self,
|
||||
_: &wl_registry::WlRegistry,
|
||||
_: wl_registry::Event,
|
||||
_: &GlobalListContents,
|
||||
_: &Connection,
|
||||
_: &QueueHandle<Self>,
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
||||
delegate_noop!(State: ZwlrVirtualPointerManagerV1);
|
||||
delegate_noop!(State: ZwlrVirtualPointerV1);
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let num = |i: usize| -> u32 { args[i].parse().expect("nombre attendu") };
|
||||
let (width, height) = (num(0), num(1));
|
||||
|
||||
let conn = Connection::connect_to_env().expect("connexion Wayland");
|
||||
let (globals, mut queue) = registry_queue_init::<State>(&conn).expect("registre");
|
||||
let qh = queue.handle();
|
||||
let manager: ZwlrVirtualPointerManagerV1 = globals.bind(&qh, 1..=1, ()).expect("wlr-virtual-pointer absent");
|
||||
let pointer = manager.create_virtual_pointer(None, &qh, ());
|
||||
queue.roundtrip(&mut State).unwrap();
|
||||
// Laisse aux clients le temps de voir apparaître le pointeur.
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
|
||||
let start = Instant::now();
|
||||
let now = || start.elapsed().as_millis() as u32;
|
||||
let button = |n: u32| if n == 3 { 0x111 } else { 0x110 };
|
||||
let mut i = 2;
|
||||
while i < args.len() {
|
||||
match args[i].as_str() {
|
||||
"move" => {
|
||||
pointer.motion_absolute(now(), num(i + 1), num(i + 2), width, height);
|
||||
i += 3;
|
||||
}
|
||||
"down" => {
|
||||
pointer.button(now(), button(num(i + 1)), ButtonState::Pressed);
|
||||
i += 2;
|
||||
}
|
||||
"up" => {
|
||||
pointer.button(now(), button(num(i + 1)), ButtonState::Released);
|
||||
i += 2;
|
||||
}
|
||||
"sleep" => {
|
||||
std::thread::sleep(Duration::from_millis(num(i + 1) as u64));
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
other => panic!("commande inconnue : {other}"),
|
||||
}
|
||||
pointer.frame();
|
||||
queue.roundtrip(&mut State).unwrap();
|
||||
std::thread::sleep(Duration::from_millis(40));
|
||||
}
|
||||
pointer.destroy();
|
||||
queue.roundtrip(&mut State).unwrap();
|
||||
}
|
||||
|
|
@ -0,0 +1,401 @@
|
|||
//! Boucle principale : rassemble la souris, le réseau et les commandes locales, puis redessine.
|
||||
|
||||
use std::sync::mpsc::{self, RecvTimeoutError};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
use show_me_protocol::{Action, ClientMsg, EraseMode, MAX_POINTS_PER_MSG, Role, RoomSettings, ServerMsg};
|
||||
use tiny_skia::Pixmap;
|
||||
use tokio::sync::mpsc::UnboundedSender;
|
||||
|
||||
use crate::backend::wayland::WaylandBackend;
|
||||
use crate::backend::x11::X11Backend;
|
||||
use crate::backend::{Backend, Button, InputEvent};
|
||||
use crate::ipc::{self, Command};
|
||||
use crate::net::{self, NetEvent};
|
||||
use crate::config;
|
||||
use crate::scene::{Item, LOCAL, Rect, Scene, fit_aspect, letterbox, rect_between};
|
||||
|
||||
/// Intervalle minimal entre deux rendus.
|
||||
const MIN_FRAME: Duration = Duration::from_millis(8);
|
||||
|
||||
pub enum Event {
|
||||
Input(InputEvent),
|
||||
/// La surface doit être entièrement réaffichée.
|
||||
Redraw,
|
||||
Net(NetEvent),
|
||||
Ipc(Command),
|
||||
Fatal(String),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)]
|
||||
pub enum BackendKind {
|
||||
Wayland,
|
||||
X11,
|
||||
}
|
||||
|
||||
pub struct Config {
|
||||
/// Système d'affichage ; détecté d'après la session si absent.
|
||||
pub backend: Option<BackendKind>,
|
||||
pub server: String,
|
||||
pub room: String,
|
||||
pub name: String,
|
||||
pub role: Role,
|
||||
pub color: [u8; 3],
|
||||
/// Épaisseur du trait, en fraction de la hauteur de l'écran de l'hôte.
|
||||
pub width: f32,
|
||||
pub echo_secs: f32,
|
||||
pub monitor: Option<usize>,
|
||||
/// Zone de la vidéo du stream sur l'écran du spectateur (sinon déduite du rapport d'aspect de l'hôte).
|
||||
pub region: Option<Rect>,
|
||||
}
|
||||
|
||||
struct App {
|
||||
cfg: Config,
|
||||
backend: Box<dyn Backend>,
|
||||
net: UnboundedSender<ClientMsg>,
|
||||
scene: Scene,
|
||||
size: (i32, i32),
|
||||
view: Rect,
|
||||
host_aspect: Option<f32>,
|
||||
draw_mode: bool,
|
||||
/// Calage de la zone vidéo en cours (spectateur).
|
||||
calibrating: bool,
|
||||
/// Point de départ du rectangle en cours de tracé pendant le calage.
|
||||
drag: Option<(f32, f32)>,
|
||||
/// Trait en cours : identifiant et dernier point retenu, en pixels.
|
||||
current: Option<(u32, (f32, f32))>,
|
||||
pending: Vec<[f32; 2]>,
|
||||
next_id: u32,
|
||||
dirty: bool,
|
||||
full_redraw: bool,
|
||||
quit: bool,
|
||||
}
|
||||
|
||||
pub fn run(cfg: Config) -> Result<()> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let kind = cfg.backend.unwrap_or_else(|| {
|
||||
// Une session Wayland expose aussi DISPLAY (XWayland) : WAYLAND_DISPLAY prime.
|
||||
if std::env::var_os("WAYLAND_DISPLAY").is_some() { BackendKind::Wayland } else { BackendKind::X11 }
|
||||
});
|
||||
let backend: Box<dyn Backend> = match kind {
|
||||
BackendKind::Wayland => Box::new(WaylandBackend::new(cfg.monitor, tx.clone())?),
|
||||
BackendKind::X11 => Box::new(X11Backend::new(cfg.monitor, tx.clone())?),
|
||||
};
|
||||
let (w, h) = backend.size();
|
||||
ipc::listen(tx.clone())?;
|
||||
|
||||
let hello = ClientMsg::Hello {
|
||||
room: cfg.room.clone(),
|
||||
name: cfg.name.clone(),
|
||||
role: cfg.role,
|
||||
aspect: (cfg.role == Role::Host).then_some(w as f32 / h as f32),
|
||||
};
|
||||
let net = net::spawn(cfg.server.clone(), hello, tx);
|
||||
|
||||
let mut app = App {
|
||||
scene: Scene::new(cfg.role, cfg.echo_secs),
|
||||
cfg,
|
||||
backend,
|
||||
net,
|
||||
size: (w as i32, h as i32),
|
||||
view: Rect::new(0, 0, w as i32, h as i32),
|
||||
host_aspect: None,
|
||||
draw_mode: false,
|
||||
calibrating: false,
|
||||
drag: None,
|
||||
current: None,
|
||||
pending: Vec::new(),
|
||||
next_id: 1,
|
||||
dirty: true,
|
||||
full_redraw: true,
|
||||
quit: false,
|
||||
};
|
||||
app.update_view();
|
||||
|
||||
let mut pixmap = Pixmap::new(w, h).expect("taille d'écran non nulle");
|
||||
let mut shown: Vec<Item> = Vec::new();
|
||||
let mut next_frame = Instant::now();
|
||||
|
||||
while !app.quit {
|
||||
let now = Instant::now();
|
||||
let wait = if app.dirty { Some(next_frame.saturating_duration_since(now)) } else { app.scene.next_wake(now) };
|
||||
let first = match wait {
|
||||
None => rx.recv().ok(),
|
||||
Some(d) if d.is_zero() => rx.try_recv().ok(),
|
||||
Some(d) => match rx.recv_timeout(d) {
|
||||
Ok(e) => Some(e),
|
||||
Err(RecvTimeoutError::Timeout) => None,
|
||||
Err(RecvTimeoutError::Disconnected) => bail!("boucle d'événements interrompue"),
|
||||
},
|
||||
};
|
||||
match first {
|
||||
Some(event) => {
|
||||
app.handle(event)?;
|
||||
while let Ok(event) = rx.try_recv() {
|
||||
app.handle(event)?;
|
||||
}
|
||||
}
|
||||
// Réveil d'animation (fondu, ping).
|
||||
None => app.dirty = true,
|
||||
}
|
||||
app.flush_points();
|
||||
|
||||
let now = Instant::now();
|
||||
if app.dirty && now >= next_frame {
|
||||
let items = app.scene.render(&mut pixmap, app.view, now);
|
||||
let damage: Vec<Rect> = if app.full_redraw {
|
||||
vec![Rect::new(0, 0, app.size.0, app.size.1)]
|
||||
} else {
|
||||
// Seules les zones dont le contenu a changé depuis le dernier affichage.
|
||||
let gone = shown.iter().filter(|i| !items.contains(i));
|
||||
let new = items.iter().filter(|i| !shown.contains(i));
|
||||
gone.chain(new).map(|i| i.rect).collect()
|
||||
};
|
||||
app.backend.present(&pixmap, &damage)?;
|
||||
shown = items;
|
||||
app.dirty = false;
|
||||
app.full_redraw = false;
|
||||
next_frame = now + MIN_FRAME;
|
||||
}
|
||||
}
|
||||
|
||||
// Efface l'overlay avant de partir.
|
||||
pixmap.fill(tiny_skia::Color::TRANSPARENT);
|
||||
app.backend.present(&pixmap, &[Rect::new(0, 0, app.size.0, app.size.1)])?;
|
||||
ipc::cleanup();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl App {
|
||||
fn handle(&mut self, event: Event) -> Result<()> {
|
||||
self.dirty = true;
|
||||
match event {
|
||||
Event::Input(input) => self.on_input(input)?,
|
||||
Event::Redraw => self.full_redraw = true,
|
||||
Event::Net(net) => self.on_net(net),
|
||||
Event::Ipc(cmd) => self.on_command(cmd)?,
|
||||
Event::Fatal(message) => bail!(message),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn to_norm(&self, x: f32, y: f32) -> [f32; 2] {
|
||||
let nx = (x - self.view.x as f32) / self.view.w as f32;
|
||||
let ny = (y - self.view.y as f32) / self.view.h as f32;
|
||||
[nx.clamp(0.0, 1.0), ny.clamp(0.0, 1.0)]
|
||||
}
|
||||
|
||||
/// Applique une action localement et l'envoie au salon.
|
||||
fn act(&mut self, action: Action) {
|
||||
self.scene.apply(LOCAL, &action, Instant::now());
|
||||
let _ = self.net.send(ClientMsg::Action { action });
|
||||
}
|
||||
|
||||
fn on_input(&mut self, input: InputEvent) -> Result<()> {
|
||||
if self.calibrating {
|
||||
return self.on_calibration_input(input);
|
||||
}
|
||||
if !self.draw_mode {
|
||||
return Ok(());
|
||||
}
|
||||
match input {
|
||||
InputEvent::Press { x, y, button: Button::Left } => {
|
||||
self.end_stroke();
|
||||
let id = self.next_id;
|
||||
self.next_id = self.next_id.wrapping_add(1);
|
||||
self.act(Action::StrokeStart { id, color: self.cfg.color, width: self.cfg.width });
|
||||
self.current = Some((id, (x, y)));
|
||||
self.pending.push(self.to_norm(x, y));
|
||||
}
|
||||
InputEvent::Press { x, y, button: Button::Right } => {
|
||||
let [x, y] = self.to_norm(x, y);
|
||||
self.act(Action::Ping { x, y, color: self.cfg.color });
|
||||
}
|
||||
InputEvent::Motion { x, y } => {
|
||||
if let Some((_, last)) = &mut self.current {
|
||||
let (dx, dy) = (x - last.0, y - last.1);
|
||||
if dx * dx + dy * dy >= 1.0 {
|
||||
*last = (x, y);
|
||||
let p = self.to_norm(x, y);
|
||||
self.pending.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
InputEvent::Release { button: Button::Left, .. } => self.end_stroke(),
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Pendant le calage : glisser trace la zone de la vidéo, le clic droit valide.
|
||||
fn on_calibration_input(&mut self, input: InputEvent) -> Result<()> {
|
||||
match input {
|
||||
InputEvent::Press { x, y, button: Button::Left } => self.drag = Some((x, y)),
|
||||
InputEvent::Motion { x, y } => {
|
||||
if let Some(start) = self.drag {
|
||||
self.scene.calib = Some(rect_between(start, (x, y)));
|
||||
}
|
||||
}
|
||||
InputEvent::Release { button: Button::Left } => {
|
||||
if self.drag.take().is_some() {
|
||||
// Un simple clic ou un geste minuscule ne change rien.
|
||||
if let Some(r) = self.scene.calib.filter(|r| r.w >= 64 && r.h >= 36) {
|
||||
self.cfg.region = Some(match self.host_aspect {
|
||||
Some(aspect) => fit_aspect(r, aspect),
|
||||
None => r,
|
||||
});
|
||||
}
|
||||
self.update_view();
|
||||
}
|
||||
}
|
||||
InputEvent::Press { button: Button::Right, .. } => self.finish_calibration()?,
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn start_calibration(&mut self) -> Result<()> {
|
||||
if self.cfg.role == Role::Host {
|
||||
eprintln!("show-me: le calage ne concerne que les spectateurs");
|
||||
return Ok(());
|
||||
}
|
||||
self.set_draw_mode(false)?;
|
||||
self.calibrating = true;
|
||||
self.drag = None;
|
||||
self.scene.calib = Some(self.view);
|
||||
self.backend.set_draw_mode(true)?;
|
||||
// L'hôte affiche des repères aux coins de son écran, visibles dans le stream.
|
||||
self.act(Action::Guides { on: true });
|
||||
eprintln!("show-me: calage : glissez d'un coin à l'autre de la vidéo, clic droit pour valider");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn finish_calibration(&mut self) -> Result<()> {
|
||||
self.calibrating = false;
|
||||
self.drag = None;
|
||||
self.scene.calib = None;
|
||||
self.backend.set_draw_mode(false)?;
|
||||
self.act(Action::Guides { on: false });
|
||||
if let Some(r) = self.cfg.region {
|
||||
match config::save_region(r) {
|
||||
Ok(()) => eprintln!("show-me: zone calée et enregistrée : {},{},{},{}", r.x, r.y, r.w, r.h),
|
||||
Err(e) => eprintln!("show-me: zone calée mais non enregistrée : {e:#}"),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn flush_points(&mut self) {
|
||||
let Some((id, _)) = self.current else { return };
|
||||
let points = std::mem::take(&mut self.pending);
|
||||
for chunk in points.chunks(MAX_POINTS_PER_MSG) {
|
||||
self.act(Action::StrokePoints { id, points: chunk.to_vec() });
|
||||
}
|
||||
}
|
||||
|
||||
fn end_stroke(&mut self) {
|
||||
self.flush_points();
|
||||
if let Some((id, _)) = self.current.take() {
|
||||
self.act(Action::StrokeEnd { id });
|
||||
}
|
||||
}
|
||||
|
||||
fn set_draw_mode(&mut self, on: bool) -> Result<()> {
|
||||
if self.calibrating {
|
||||
self.finish_calibration()?;
|
||||
}
|
||||
if on == self.draw_mode {
|
||||
return Ok(());
|
||||
}
|
||||
if !on {
|
||||
self.end_stroke();
|
||||
}
|
||||
self.draw_mode = on;
|
||||
self.scene.border = on.then_some(self.cfg.color);
|
||||
self.backend.set_draw_mode(on)
|
||||
}
|
||||
|
||||
fn on_command(&mut self, cmd: Command) -> Result<()> {
|
||||
match cmd {
|
||||
Command::Draw(state) => self.set_draw_mode(state.unwrap_or(!self.draw_mode))?,
|
||||
Command::Mode(mode, secs) => {
|
||||
let current = self.scene.settings();
|
||||
let settings = RoomSettings { mode, fade_secs: secs.unwrap_or(current.fade_secs) }.sanitized();
|
||||
// Appliqué tout de suite ; le serveur le confirmera à tout le salon.
|
||||
self.scene.set_settings(settings, Instant::now());
|
||||
let _ = self.net.send(ClientMsg::SetSettings { settings });
|
||||
}
|
||||
Command::Clear(scope) => self.act(Action::Clear { scope }),
|
||||
Command::Calibrate(false) if self.calibrating => self.finish_calibration()?,
|
||||
Command::Calibrate(false) => self.start_calibration()?,
|
||||
Command::Calibrate(true) => {
|
||||
self.cfg.region = None;
|
||||
config::clear_region();
|
||||
self.update_view();
|
||||
eprintln!("show-me: calage automatique rétabli");
|
||||
}
|
||||
Command::Quit => self.quit = true,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn on_net(&mut self, event: NetEvent) {
|
||||
let now = Instant::now();
|
||||
match event {
|
||||
NetEvent::Connected => eprintln!("show-me: connecté à {}", self.cfg.server),
|
||||
NetEvent::Disconnected(reason) => {
|
||||
eprintln!("show-me: déconnecté ({reason}), nouvel essai…");
|
||||
self.scene.clear_guides();
|
||||
}
|
||||
NetEvent::Msg(msg) => match msg {
|
||||
ServerMsg::Welcome { settings, host_aspect, peers, .. } => {
|
||||
let names: Vec<&str> = peers.iter().map(|p| p.name.as_str()).collect();
|
||||
eprintln!("show-me: salon « {} », déjà présents : {:?}", self.cfg.room, names);
|
||||
self.apply_settings(settings, now);
|
||||
self.host_aspect = host_aspect;
|
||||
self.update_view();
|
||||
if self.calibrating {
|
||||
// Après une reconnexion, redemande les repères à l'hôte.
|
||||
let _ = self.net.send(ClientMsg::Action { action: Action::Guides { on: true } });
|
||||
}
|
||||
}
|
||||
ServerMsg::PeerJoined { peer } => eprintln!("show-me: {} a rejoint le salon", peer.name),
|
||||
ServerMsg::PeerLeft { id } => self.scene.peer_left(id, now),
|
||||
ServerMsg::Action { from, action } => self.scene.apply(from, &action, now),
|
||||
ServerMsg::Settings { settings } => self.apply_settings(settings, now),
|
||||
ServerMsg::HostAspect { aspect } => {
|
||||
self.host_aspect = aspect;
|
||||
self.update_view();
|
||||
}
|
||||
ServerMsg::Error { message } => eprintln!("show-me: refusé par le serveur : {message}"),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_settings(&mut self, settings: RoomSettings, now: Instant) {
|
||||
if settings != self.scene.settings() {
|
||||
let mode = match settings.mode {
|
||||
EraseMode::Auto => format!("auto ({} s)", settings.fade_secs),
|
||||
EraseMode::Manual => "manuel".to_string(),
|
||||
};
|
||||
eprintln!("show-me: mode d'effacement : {mode}");
|
||||
}
|
||||
self.scene.set_settings(settings, now);
|
||||
}
|
||||
|
||||
/// Recalcule la zone de l'écran qui correspond à l'écran de l'hôte.
|
||||
fn update_view(&mut self) {
|
||||
let full = Rect::new(0, 0, self.size.0, self.size.1);
|
||||
self.view = match (self.cfg.role, self.cfg.region, self.host_aspect) {
|
||||
(Role::Host, _, _) => full,
|
||||
(Role::Viewer, Some(region), _) => region,
|
||||
(Role::Viewer, None, Some(aspect)) => letterbox(self.size.0, self.size.1, aspect),
|
||||
(Role::Viewer, None, None) => full,
|
||||
};
|
||||
if self.calibrating && self.drag.is_none() {
|
||||
self.scene.calib = Some(self.view);
|
||||
}
|
||||
self.dirty = true;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
//! Couche fenêtre : une surface transparente, au-dessus de tout, qui laisse passer les clics
|
||||
//! sauf en mode dessin. Une implémentation par système d'affichage.
|
||||
|
||||
use anyhow::Result;
|
||||
use tiny_skia::Pixmap;
|
||||
|
||||
use crate::scene::Rect;
|
||||
|
||||
pub mod wayland;
|
||||
pub mod x11;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Button {
|
||||
Left,
|
||||
Right,
|
||||
Other,
|
||||
}
|
||||
|
||||
/// Événement souris, en pixels dans la surface.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum InputEvent {
|
||||
Press { x: f32, y: f32, button: Button },
|
||||
Motion { x: f32, y: f32 },
|
||||
Release { button: Button },
|
||||
}
|
||||
|
||||
pub trait Backend {
|
||||
/// Taille de la surface en pixels (celle de l'écran couvert).
|
||||
fn size(&self) -> (u32, u32);
|
||||
/// En mode dessin la surface capte la souris ; sinon les clics la traversent.
|
||||
fn set_draw_mode(&mut self, on: bool) -> Result<()>;
|
||||
/// Affiche les zones `rects` du tampon (RGBA prémultiplié, taille `size()`).
|
||||
fn present(&mut self, pixmap: &Pixmap, rects: &[Rect]) -> Result<()>;
|
||||
}
|
||||
|
|
@ -0,0 +1,337 @@
|
|||
//! Backend Wayland : surface layer-shell sur la couche « overlay », tampons partagés wl_shm.
|
||||
//! Exige un compositeur qui gère wlr-layer-shell (Sway, Hyprland, niri, River, KDE… pas GNOME).
|
||||
//!
|
||||
//! Les événements Wayland sont traités dans un fil dédié ; l'affichage se fait depuis la boucle
|
||||
//! principale, les objets Wayland pouvant être utilisés depuis plusieurs fils.
|
||||
|
||||
use std::sync::mpsc::{self, Sender};
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, anyhow};
|
||||
use smithay_client_toolkit::compositor::{CompositorHandler, CompositorState, Region};
|
||||
use smithay_client_toolkit::output::{OutputHandler, OutputState};
|
||||
use smithay_client_toolkit::reexports::client::globals::registry_queue_init;
|
||||
use smithay_client_toolkit::reexports::client::protocol::{wl_output, wl_pointer, wl_seat, wl_shm, wl_surface};
|
||||
use smithay_client_toolkit::reexports::client::{Connection, QueueHandle};
|
||||
use smithay_client_toolkit::registry::{ProvidesRegistryState, RegistryState};
|
||||
use smithay_client_toolkit::seat::pointer::{
|
||||
CursorIcon, PointerEvent, PointerEventKind, PointerHandler, ThemeSpec, ThemedPointer,
|
||||
};
|
||||
use smithay_client_toolkit::seat::{Capability, SeatHandler, SeatState};
|
||||
use smithay_client_toolkit::shell::WaylandSurface;
|
||||
use smithay_client_toolkit::shell::wlr_layer::{
|
||||
Anchor, KeyboardInteractivity, Layer, LayerShell, LayerShellHandler, LayerSurface, LayerSurfaceConfigure,
|
||||
};
|
||||
use smithay_client_toolkit::shm::slot::SlotPool;
|
||||
use smithay_client_toolkit::shm::{Shm, ShmHandler};
|
||||
use smithay_client_toolkit::{delegate_registry, registry_handlers};
|
||||
use tiny_skia::Pixmap;
|
||||
|
||||
use super::{Backend, Button, InputEvent};
|
||||
use crate::app::Event;
|
||||
use crate::scene::Rect;
|
||||
|
||||
// Codes de boutons Linux (linux/input-event-codes.h).
|
||||
const BTN_LEFT: u32 = 0x110;
|
||||
const BTN_RIGHT: u32 = 0x111;
|
||||
|
||||
pub struct WaylandBackend {
|
||||
conn: Connection,
|
||||
layer: LayerSurface,
|
||||
pool: SlotPool,
|
||||
/// Région vide : appliquée comme région d'entrée, elle laisse passer les clics.
|
||||
empty_region: Region,
|
||||
width: u32,
|
||||
height: u32,
|
||||
}
|
||||
|
||||
/// État détenu par le fil qui traite les événements Wayland.
|
||||
struct State {
|
||||
registry_state: RegistryState,
|
||||
seat_state: SeatState,
|
||||
output_state: OutputState,
|
||||
shm: Shm,
|
||||
pointer: Option<ThemedPointer>,
|
||||
compositor: CompositorState,
|
||||
events: Sender<Event>,
|
||||
/// Signale la taille reçue à la première configuration.
|
||||
configured: Option<Sender<(u32, u32)>>,
|
||||
size: (u32, u32),
|
||||
}
|
||||
|
||||
impl WaylandBackend {
|
||||
/// Crée l'overlay sur la sortie `monitor` (au choix du compositeur par défaut).
|
||||
pub fn new(monitor: Option<usize>, events: Sender<Event>) -> Result<Self> {
|
||||
let conn = Connection::connect_to_env().context("connexion au compositeur Wayland")?;
|
||||
let (globals, mut queue) = registry_queue_init::<State>(&conn).context("registre Wayland")?;
|
||||
let qh = queue.handle();
|
||||
|
||||
let compositor = CompositorState::bind(&globals, &qh).context("wl_compositor indisponible")?;
|
||||
let layer_shell = LayerShell::bind(&globals, &qh).map_err(|_| {
|
||||
anyhow!("ce compositeur ne gère pas wlr-layer-shell (c'est le cas de GNOME) : overlay impossible")
|
||||
})?;
|
||||
let shm = Shm::bind(&globals, &qh).context("wl_shm indisponible")?;
|
||||
let empty_region = Region::new(&compositor).context("création de région")?;
|
||||
|
||||
// Taille provisoire : la réserve grandit toute seule à la création des tampons.
|
||||
let pool = SlotPool::new(4096, &shm).context("mémoire partagée")?;
|
||||
|
||||
let (configured_tx, configured_rx) = mpsc::channel();
|
||||
let mut state = State {
|
||||
registry_state: RegistryState::new(&globals),
|
||||
seat_state: SeatState::new(&globals, &qh),
|
||||
output_state: OutputState::new(&globals, &qh),
|
||||
pointer: None,
|
||||
events,
|
||||
configured: Some(configured_tx),
|
||||
size: (0, 0),
|
||||
shm,
|
||||
compositor,
|
||||
};
|
||||
|
||||
// Un aller-retour pour connaître les sorties avant d'en choisir une.
|
||||
queue.roundtrip(&mut state).context("dialogue initial avec le compositeur")?;
|
||||
let output = match monitor {
|
||||
None => None,
|
||||
Some(index) => {
|
||||
let count = state.output_state.outputs().count();
|
||||
Some(
|
||||
state
|
||||
.output_state
|
||||
.outputs()
|
||||
.nth(index)
|
||||
.with_context(|| format!("moniteur {index} introuvable ({count} détectés)"))?,
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
let surface = state.compositor.create_surface(&qh);
|
||||
let layer = layer_shell.create_layer_surface(&qh, surface, Layer::Overlay, Some("show-me"), output.as_ref());
|
||||
// Ancrée aux quatre bords, taille laissée au compositeur : toute la sortie.
|
||||
layer.set_anchor(Anchor::TOP | Anchor::BOTTOM | Anchor::LEFT | Anchor::RIGHT);
|
||||
layer.set_size(0, 0);
|
||||
// -1 : ne pas être décalée par les barres et panneaux.
|
||||
layer.set_exclusive_zone(-1);
|
||||
layer.set_keyboard_interactivity(KeyboardInteractivity::None);
|
||||
layer.set_input_region(Some(empty_region.wl_region()));
|
||||
// Premier commit sans tampon : le compositeur répond par la configuration.
|
||||
layer.commit();
|
||||
conn.flush()?;
|
||||
|
||||
std::thread::spawn(move || {
|
||||
loop {
|
||||
if let Err(e) = queue.blocking_dispatch(&mut state) {
|
||||
let _ = state.events.send(Event::Fatal(format!("connexion Wayland perdue : {e}")));
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let (width, height) = configured_rx
|
||||
.recv_timeout(Duration::from_secs(5))
|
||||
.map_err(|_| anyhow!("le compositeur n'a pas configuré la surface"))?;
|
||||
|
||||
Ok(Self { conn, layer, pool, empty_region, width, height })
|
||||
}
|
||||
}
|
||||
|
||||
impl Backend for WaylandBackend {
|
||||
fn size(&self) -> (u32, u32) {
|
||||
(self.width, self.height)
|
||||
}
|
||||
|
||||
fn set_draw_mode(&mut self, on: bool) -> Result<()> {
|
||||
// Sans région d'entrée explicite, toute la surface capte la souris.
|
||||
let region = if on { None } else { Some(self.empty_region.wl_region()) };
|
||||
self.layer.set_input_region(region);
|
||||
self.layer.commit();
|
||||
self.conn.flush()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn present(&mut self, pixmap: &Pixmap, rects: &[Rect]) -> Result<()> {
|
||||
if rects.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let (w, h) = (self.width as i32, self.height as i32);
|
||||
let (buffer, canvas) =
|
||||
self.pool.create_buffer(w, h, w * 4, wl_shm::Format::Argb8888).context("création de tampon")?;
|
||||
// tiny-skia stocke du RGBA, wl_shm ARGB8888 est du BGRA en mémoire (les deux prémultipliés).
|
||||
// Chaque tampon étant neuf, il faut le remplir en entier.
|
||||
for (dst, src) in canvas.chunks_exact_mut(4).zip(pixmap.data().chunks_exact(4)) {
|
||||
dst.copy_from_slice(&[src[2], src[1], src[0], src[3]]);
|
||||
}
|
||||
let surface = self.layer.wl_surface();
|
||||
buffer.attach_to(surface).context("attache du tampon")?;
|
||||
for r in rects {
|
||||
if let Some(r) = r.clipped(w, h) {
|
||||
surface.damage_buffer(r.x, r.y, r.w, r.h);
|
||||
}
|
||||
}
|
||||
self.layer.commit();
|
||||
self.conn.flush()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl LayerShellHandler for State {
|
||||
fn closed(&mut self, _: &Connection, _: &QueueHandle<Self>, _: &LayerSurface) {
|
||||
let _ = self.events.send(Event::Fatal("le compositeur a fermé l'overlay".into()));
|
||||
}
|
||||
|
||||
fn configure(
|
||||
&mut self,
|
||||
_: &Connection,
|
||||
_: &QueueHandle<Self>,
|
||||
_: &LayerSurface,
|
||||
configure: LayerSurfaceConfigure,
|
||||
_serial: u32,
|
||||
) {
|
||||
let size = configure.new_size;
|
||||
if let Some(tx) = self.configured.take() {
|
||||
self.size = size;
|
||||
let _ = tx.send(size);
|
||||
} else if size != self.size {
|
||||
let _ = self.events.send(Event::Fatal("la taille de l'écran a changé, relancez show-me".into()));
|
||||
} else {
|
||||
let _ = self.events.send(Event::Redraw);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PointerHandler for State {
|
||||
fn pointer_frame(
|
||||
&mut self,
|
||||
conn: &Connection,
|
||||
_: &QueueHandle<Self>,
|
||||
_: &wl_pointer::WlPointer,
|
||||
events: &[PointerEvent],
|
||||
) {
|
||||
let button = |code: u32| match code {
|
||||
BTN_LEFT => Button::Left,
|
||||
BTN_RIGHT => Button::Right,
|
||||
_ => Button::Other,
|
||||
};
|
||||
for event in events {
|
||||
let (x, y) = (event.position.0 as f32, event.position.1 as f32);
|
||||
let input = match event.kind {
|
||||
PointerEventKind::Enter { .. } => {
|
||||
// Le pointeur n'entre qu'en mode dessin : curseur en croix.
|
||||
if let Some(pointer) = &self.pointer {
|
||||
let _ = pointer.set_cursor(conn, CursorIcon::Crosshair);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
PointerEventKind::Motion { .. } => InputEvent::Motion { x, y },
|
||||
PointerEventKind::Press { button: code, .. } => InputEvent::Press { x, y, button: button(code) },
|
||||
PointerEventKind::Release { button: code, .. } => InputEvent::Release { button: button(code) },
|
||||
_ => continue,
|
||||
};
|
||||
let _ = self.events.send(Event::Input(input));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SeatHandler for State {
|
||||
fn seat_state(&mut self) -> &mut SeatState {
|
||||
&mut self.seat_state
|
||||
}
|
||||
|
||||
fn new_seat(&mut self, _: &Connection, _: &QueueHandle<Self>, _: wl_seat::WlSeat) {}
|
||||
|
||||
fn new_capability(
|
||||
&mut self,
|
||||
_: &Connection,
|
||||
qh: &QueueHandle<Self>,
|
||||
seat: wl_seat::WlSeat,
|
||||
capability: Capability,
|
||||
) {
|
||||
if capability == Capability::Pointer && self.pointer.is_none() {
|
||||
// Surface qui portera l'image du curseur.
|
||||
let surface = self.compositor.create_surface(qh);
|
||||
match self.seat_state.get_pointer_with_theme::<_, ()>(
|
||||
qh,
|
||||
&seat,
|
||||
self.shm.wl_shm(),
|
||||
surface,
|
||||
ThemeSpec::default(),
|
||||
) {
|
||||
Ok(pointer) => self.pointer = Some(pointer),
|
||||
Err(e) => eprintln!("show-me: pointeur indisponible : {e}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_capability(&mut self, _: &Connection, _: &QueueHandle<Self>, _: wl_seat::WlSeat, capability: Capability) {
|
||||
// Souris débranchée : on libère le pointeur, il sera recréé à son retour.
|
||||
if capability == Capability::Pointer {
|
||||
if let Some(pointer) = self.pointer.take() {
|
||||
pointer.pointer().release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_seat(&mut self, _: &Connection, _: &QueueHandle<Self>, _: wl_seat::WlSeat) {}
|
||||
}
|
||||
|
||||
impl CompositorHandler for State {
|
||||
fn scale_factor_changed(&mut self, _: &Connection, _: &QueueHandle<Self>, _: &wl_surface::WlSurface, _: i32) {}
|
||||
|
||||
fn transform_changed(
|
||||
&mut self,
|
||||
_: &Connection,
|
||||
_: &QueueHandle<Self>,
|
||||
_: &wl_surface::WlSurface,
|
||||
_: wl_output::Transform,
|
||||
) {
|
||||
}
|
||||
|
||||
fn frame(&mut self, _: &Connection, _: &QueueHandle<Self>, _: &wl_surface::WlSurface, _: u32) {}
|
||||
|
||||
fn surface_enter(
|
||||
&mut self,
|
||||
_: &Connection,
|
||||
_: &QueueHandle<Self>,
|
||||
_: &wl_surface::WlSurface,
|
||||
_: &wl_output::WlOutput,
|
||||
) {
|
||||
}
|
||||
|
||||
fn surface_leave(
|
||||
&mut self,
|
||||
_: &Connection,
|
||||
_: &QueueHandle<Self>,
|
||||
_: &wl_surface::WlSurface,
|
||||
_: &wl_output::WlOutput,
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
||||
impl OutputHandler for State {
|
||||
fn output_state(&mut self) -> &mut OutputState {
|
||||
&mut self.output_state
|
||||
}
|
||||
|
||||
fn new_output(&mut self, _: &Connection, _: &QueueHandle<Self>, _: wl_output::WlOutput) {}
|
||||
|
||||
fn update_output(&mut self, _: &Connection, _: &QueueHandle<Self>, _: wl_output::WlOutput) {}
|
||||
|
||||
fn output_destroyed(&mut self, _: &Connection, _: &QueueHandle<Self>, _: wl_output::WlOutput) {}
|
||||
}
|
||||
|
||||
impl ShmHandler for State {
|
||||
fn shm_state(&mut self) -> &mut Shm {
|
||||
&mut self.shm
|
||||
}
|
||||
}
|
||||
|
||||
delegate_registry!(State);
|
||||
|
||||
impl ProvidesRegistryState for State {
|
||||
fn registry(&mut self) -> &mut RegistryState {
|
||||
&mut self.registry_state
|
||||
}
|
||||
registry_handlers![OutputState, SeatState];
|
||||
}
|
||||
|
||||
smithay_client_toolkit::delegate_dispatch2!(State);
|
||||
|
|
@ -0,0 +1,222 @@
|
|||
//! Backend Xorg : fenêtre ARGB sans décoration (override-redirect), région d'entrée XFixes.
|
||||
//! La transparence exige un compositeur (Muffin, KWin, picom…).
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::mpsc::Sender;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use tiny_skia::Pixmap;
|
||||
use x11rb::connection::{Connection, RequestConnection};
|
||||
use x11rb::wrapper::ConnectionExt as _;
|
||||
use x11rb::protocol::Event as XEvent;
|
||||
use x11rb::protocol::randr::ConnectionExt as _;
|
||||
use x11rb::protocol::shape::SK;
|
||||
use x11rb::protocol::xfixes::ConnectionExt as _;
|
||||
use x11rb::protocol::xproto::{
|
||||
ChangeWindowAttributesAux, ColormapAlloc, ConfigureWindowAux, ConnectionExt as _, CreateGCAux,
|
||||
CreateWindowAux, EventMask, ImageFormat, ImageOrder, Rectangle, StackMode, VisualClass, WindowClass,
|
||||
};
|
||||
use x11rb::rust_connection::RustConnection;
|
||||
|
||||
use super::{Backend, Button, InputEvent};
|
||||
use crate::app::Event;
|
||||
use crate::scene::Rect;
|
||||
|
||||
/// Taille maximale d'un envoi d'image ; au-delà, on découpe en bandes.
|
||||
const MAX_CHUNK_BYTES: usize = 1 << 20;
|
||||
|
||||
pub struct X11Backend {
|
||||
conn: Arc<RustConnection>,
|
||||
window: u32,
|
||||
gc: u32,
|
||||
cursor: u32,
|
||||
width: u16,
|
||||
height: u16,
|
||||
chunk_bytes: usize,
|
||||
scratch: Vec<u8>,
|
||||
}
|
||||
|
||||
impl X11Backend {
|
||||
/// Crée l'overlay sur le moniteur `monitor` (le principal par défaut).
|
||||
pub fn new(monitor: Option<usize>, events: Sender<Event>) -> Result<Self> {
|
||||
let (conn, screen_num) = x11rb::connect(None).context("connexion au serveur X")?;
|
||||
let conn = Arc::new(conn);
|
||||
let setup = conn.setup();
|
||||
if setup.image_byte_order != ImageOrder::LSB_FIRST {
|
||||
bail!("serveur X gros-boutiste non pris en charge");
|
||||
}
|
||||
let screen = &setup.roots[screen_num];
|
||||
let root = screen.root;
|
||||
|
||||
let monitors = conn.randr_get_monitors(root, true)?.reply().context("RandR")?.monitors;
|
||||
let mon = match monitor {
|
||||
Some(i) => monitors.get(i).with_context(|| format!("moniteur {i} introuvable ({} détectés)", monitors.len()))?,
|
||||
None => monitors.iter().find(|m| m.primary).or(monitors.first()).context("aucun moniteur")?,
|
||||
};
|
||||
let (x, y, width, height) = (mon.x, mon.y, mon.width, mon.height);
|
||||
|
||||
let visual = screen
|
||||
.allowed_depths
|
||||
.iter()
|
||||
.filter(|d| d.depth == 32)
|
||||
.flat_map(|d| d.visuals.iter())
|
||||
.find(|v| v.class == VisualClass::TRUE_COLOR && v.red_mask == 0xff0000 && v.blue_mask == 0xff)
|
||||
.context("pas de visuel ARGB 32 bits")?
|
||||
.visual_id;
|
||||
|
||||
let cm_atom = conn.intern_atom(false, format!("_NET_WM_CM_S{screen_num}").as_bytes())?.reply()?.atom;
|
||||
if conn.get_selection_owner(cm_atom)?.reply()?.owner == x11rb::NONE {
|
||||
eprintln!("show-me: aucun compositeur détecté, l'overlay ne sera pas transparent (lancez picom)");
|
||||
}
|
||||
|
||||
let colormap = conn.generate_id()?;
|
||||
conn.create_colormap(ColormapAlloc::NONE, colormap, root, visual)?;
|
||||
let window = conn.generate_id()?;
|
||||
conn.create_window(
|
||||
32,
|
||||
window,
|
||||
root,
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
height,
|
||||
0,
|
||||
WindowClass::INPUT_OUTPUT,
|
||||
visual,
|
||||
&CreateWindowAux::new()
|
||||
.background_pixel(0)
|
||||
.border_pixel(0)
|
||||
.override_redirect(1)
|
||||
.colormap(colormap)
|
||||
.event_mask(
|
||||
EventMask::EXPOSURE
|
||||
| EventMask::BUTTON_PRESS
|
||||
| EventMask::BUTTON_RELEASE
|
||||
| EventMask::POINTER_MOTION,
|
||||
),
|
||||
)?;
|
||||
conn.change_property8(
|
||||
x11rb::protocol::xproto::PropMode::REPLACE,
|
||||
window,
|
||||
x11rb::protocol::xproto::AtomEnum::WM_NAME,
|
||||
x11rb::protocol::xproto::AtomEnum::STRING,
|
||||
b"show-me",
|
||||
)?;
|
||||
|
||||
let gc = conn.generate_id()?;
|
||||
conn.create_gc(gc, window, &CreateGCAux::new())?;
|
||||
|
||||
// Curseur en croix pour le mode dessin (police « cursor » standard, glyphe 34).
|
||||
let font = conn.generate_id()?;
|
||||
conn.open_font(font, b"cursor")?;
|
||||
let cursor = conn.generate_id()?;
|
||||
conn.create_glyph_cursor(cursor, font, font, 34, 35, 0, 0, 0, 0xffff, 0xffff, 0xffff)?;
|
||||
conn.close_font(font)?;
|
||||
|
||||
conn.xfixes_query_version(5, 0)?.reply().context("extension XFixes")?;
|
||||
|
||||
let chunk_bytes = MAX_CHUNK_BYTES.min(conn.maximum_request_bytes().saturating_sub(1024));
|
||||
let mut backend =
|
||||
Self { conn: conn.clone(), window, gc, cursor, width, height, chunk_bytes, scratch: Vec::new() };
|
||||
backend.set_draw_mode(false)?;
|
||||
conn.map_window(window)?;
|
||||
conn.flush()?;
|
||||
|
||||
std::thread::spawn(move || {
|
||||
loop {
|
||||
let event = match conn.wait_for_event() {
|
||||
Ok(e) => e,
|
||||
Err(e) => {
|
||||
let _ = events.send(Event::Fatal(format!("connexion X perdue : {e}")));
|
||||
return;
|
||||
}
|
||||
};
|
||||
let button = |detail: u8| match detail {
|
||||
1 => Button::Left,
|
||||
3 => Button::Right,
|
||||
_ => Button::Other,
|
||||
};
|
||||
let out = match event {
|
||||
XEvent::Expose(_) => Event::Redraw,
|
||||
XEvent::ButtonPress(e) => Event::Input(InputEvent::Press {
|
||||
x: e.event_x as f32,
|
||||
y: e.event_y as f32,
|
||||
button: button(e.detail),
|
||||
}),
|
||||
XEvent::ButtonRelease(e) => Event::Input(InputEvent::Release { button: button(e.detail) }),
|
||||
XEvent::MotionNotify(e) => {
|
||||
Event::Input(InputEvent::Motion { x: e.event_x as f32, y: e.event_y as f32 })
|
||||
}
|
||||
XEvent::Error(e) => {
|
||||
eprintln!("show-me: erreur X : {e:?}");
|
||||
continue;
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
if events.send(out).is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(backend)
|
||||
}
|
||||
}
|
||||
|
||||
impl Backend for X11Backend {
|
||||
fn size(&self) -> (u32, u32) {
|
||||
(self.width as u32, self.height as u32)
|
||||
}
|
||||
|
||||
fn set_draw_mode(&mut self, on: bool) -> Result<()> {
|
||||
// Région d'entrée vide : les clics traversent la fenêtre.
|
||||
let rects: &[Rectangle] =
|
||||
if on { &[Rectangle { x: 0, y: 0, width: self.width, height: self.height }] } else { &[] };
|
||||
let region = self.conn.generate_id()?;
|
||||
self.conn.xfixes_create_region(region, rects)?;
|
||||
self.conn.xfixes_set_window_shape_region(self.window, SK::INPUT, 0, 0, region)?;
|
||||
self.conn.xfixes_destroy_region(region)?;
|
||||
let cursor = if on { self.cursor } else { x11rb::NONE };
|
||||
self.conn.change_window_attributes(self.window, &ChangeWindowAttributesAux::new().cursor(cursor))?;
|
||||
self.conn.configure_window(self.window, &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE))?;
|
||||
self.conn.flush()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn present(&mut self, pixmap: &Pixmap, rects: &[Rect]) -> Result<()> {
|
||||
let stride = pixmap.width() as usize * 4;
|
||||
let src = pixmap.data();
|
||||
for r in rects {
|
||||
let Some(r) = r.clipped(self.width as i32, self.height as i32) else { continue };
|
||||
let row_bytes = r.w as usize * 4;
|
||||
let rows_per_chunk = (self.chunk_bytes / row_bytes).max(1);
|
||||
let mut row = 0usize;
|
||||
while row < r.h as usize {
|
||||
let rows = rows_per_chunk.min(r.h as usize - row);
|
||||
self.scratch.clear();
|
||||
for y in 0..rows {
|
||||
let start = (r.y as usize + row + y) * stride + r.x as usize * 4;
|
||||
// tiny-skia stocke du RGBA, X attend du BGRA (les deux prémultipliés).
|
||||
for px in src[start..start + row_bytes].chunks_exact(4) {
|
||||
self.scratch.extend_from_slice(&[px[2], px[1], px[0], px[3]]);
|
||||
}
|
||||
}
|
||||
self.conn.put_image(
|
||||
ImageFormat::Z_PIXMAP,
|
||||
self.window,
|
||||
self.gc,
|
||||
r.w as u16,
|
||||
rows as u16,
|
||||
r.x as i16,
|
||||
(r.y as usize + row) as i16,
|
||||
0,
|
||||
32,
|
||||
&self.scratch,
|
||||
)?;
|
||||
row += rows;
|
||||
}
|
||||
}
|
||||
self.conn.flush()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
//! Réglages conservés d'un lancement à l'autre (pour l'instant : la zone calée par le spectateur).
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
|
||||
use crate::scene::Rect;
|
||||
|
||||
/// Lit une zone écrite sous la forme `x,y,largeur,hauteur`.
|
||||
pub fn parse_region(s: &str) -> Result<Rect> {
|
||||
let parts: Vec<i32> = s
|
||||
.split(',')
|
||||
.map(|p| p.trim().parse())
|
||||
.collect::<Result<_, _>>()
|
||||
.with_context(|| format!("région invalide : {s}"))?;
|
||||
match parts.as_slice() {
|
||||
&[x, y, w, h] if w > 0 && h > 0 => Ok(Rect::new(x, y, w, h)),
|
||||
_ => bail!("région invalide : {s} (attendu : x,y,largeur,hauteur)"),
|
||||
}
|
||||
}
|
||||
|
||||
fn region_path() -> Option<PathBuf> {
|
||||
let base = std::env::var_os("XDG_CONFIG_HOME")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))?;
|
||||
Some(base.join("show-me").join("region"))
|
||||
}
|
||||
|
||||
/// Zone enregistrée par le dernier calage, s'il y en a une.
|
||||
pub fn load_region() -> Option<Rect> {
|
||||
let text = std::fs::read_to_string(region_path()?).ok()?;
|
||||
parse_region(text.trim()).ok()
|
||||
}
|
||||
|
||||
pub fn save_region(r: Rect) -> Result<()> {
|
||||
let path = region_path().context("dossier de configuration introuvable")?;
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
std::fs::write(&path, format!("{},{},{},{}\n", r.x, r.y, r.w, r.h))
|
||||
.with_context(|| format!("écriture de {}", path.display()))
|
||||
}
|
||||
|
||||
pub fn clear_region() {
|
||||
if let Some(path) = region_path() {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,138 @@
|
|||
//! Commandes envoyées à l'instance en cours (`show-me toggle`, etc.) par un socket Unix.
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::os::unix::net::{UnixListener, UnixStream};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::mpsc::Sender;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use show_me_protocol::{ClearScope, EraseMode};
|
||||
|
||||
use crate::app::Event;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum Command {
|
||||
/// `None` : bascule.
|
||||
Draw(Option<bool>),
|
||||
Mode(EraseMode, Option<f32>),
|
||||
Clear(ClearScope),
|
||||
/// Calage de la zone vidéo ; `true` : revenir au calage automatique.
|
||||
Calibrate(bool),
|
||||
Quit,
|
||||
}
|
||||
|
||||
impl Command {
|
||||
pub fn to_line(self) -> String {
|
||||
match self {
|
||||
Command::Draw(None) => "toggle".into(),
|
||||
Command::Draw(Some(true)) => "draw on".into(),
|
||||
Command::Draw(Some(false)) => "draw off".into(),
|
||||
Command::Mode(EraseMode::Manual, _) => "mode manual".into(),
|
||||
Command::Mode(EraseMode::Auto, None) => "mode auto".into(),
|
||||
Command::Mode(EraseMode::Auto, Some(s)) => format!("mode auto {s}"),
|
||||
Command::Clear(ClearScope::Mine) => "clear mine".into(),
|
||||
Command::Clear(ClearScope::All) => "clear all".into(),
|
||||
Command::Calibrate(false) => "calibrate".into(),
|
||||
Command::Calibrate(true) => "calibrate reset".into(),
|
||||
Command::Quit => "quit".into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(line: &str) -> Result<Self> {
|
||||
let words: Vec<&str> = line.split_whitespace().collect();
|
||||
Ok(match words.as_slice() {
|
||||
["toggle"] => Command::Draw(None),
|
||||
["draw", "on"] => Command::Draw(Some(true)),
|
||||
["draw", "off"] => Command::Draw(Some(false)),
|
||||
["mode", "manual"] => Command::Mode(EraseMode::Manual, None),
|
||||
["mode", "auto"] => Command::Mode(EraseMode::Auto, None),
|
||||
["mode", "auto", secs] => Command::Mode(EraseMode::Auto, Some(secs.parse().context("durée invalide")?)),
|
||||
["clear", "mine"] => Command::Clear(ClearScope::Mine),
|
||||
["clear", "all"] => Command::Clear(ClearScope::All),
|
||||
["calibrate"] => Command::Calibrate(false),
|
||||
["calibrate", "reset"] => Command::Calibrate(true),
|
||||
["quit"] => Command::Quit,
|
||||
_ => bail!("commande inconnue : {line}"),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn socket_path() -> PathBuf {
|
||||
let dir = std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from).unwrap_or_else(std::env::temp_dir);
|
||||
dir.join("show-me.sock")
|
||||
}
|
||||
|
||||
/// Envoie une commande à l'instance en cours.
|
||||
pub fn send(cmd: Command) -> Result<()> {
|
||||
let path = socket_path();
|
||||
let mut stream = UnixStream::connect(&path)
|
||||
.with_context(|| format!("aucune instance de show-me en cours ({})", path.display()))?;
|
||||
writeln!(stream, "{}", cmd.to_line())?;
|
||||
let mut reply = String::new();
|
||||
BufReader::new(stream).read_line(&mut reply)?;
|
||||
match reply.trim() {
|
||||
"ok" => Ok(()),
|
||||
other => bail!("{other}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Écoute les commandes et les transmet à la boucle principale.
|
||||
pub fn listen(events: Sender<Event>) -> Result<()> {
|
||||
let path = socket_path();
|
||||
if UnixStream::connect(&path).is_ok() {
|
||||
bail!("show-me tourne déjà (utilisez `show-me quit` pour l'arrêter)");
|
||||
}
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let listener = UnixListener::bind(&path).with_context(|| format!("création de {}", path.display()))?;
|
||||
std::thread::spawn(move || {
|
||||
for stream in listener.incoming().flatten() {
|
||||
let mut line = String::new();
|
||||
let mut reader = BufReader::new(stream);
|
||||
if reader.read_line(&mut line).is_err() {
|
||||
continue;
|
||||
}
|
||||
let mut stream = reader.into_inner();
|
||||
match Command::parse(&line) {
|
||||
Ok(cmd) => {
|
||||
let _ = writeln!(stream, "ok");
|
||||
if events.send(Event::Ipc(cmd)).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = writeln!(stream, "erreur : {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn cleanup() {
|
||||
let _ = std::fs::remove_file(socket_path());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn commands_round_trip() {
|
||||
for cmd in [
|
||||
Command::Draw(None),
|
||||
Command::Draw(Some(true)),
|
||||
Command::Draw(Some(false)),
|
||||
Command::Mode(EraseMode::Manual, None),
|
||||
Command::Mode(EraseMode::Auto, None),
|
||||
Command::Mode(EraseMode::Auto, Some(7.5)),
|
||||
Command::Clear(ClearScope::Mine),
|
||||
Command::Clear(ClearScope::All),
|
||||
Command::Calibrate(false),
|
||||
Command::Calibrate(true),
|
||||
Command::Quit,
|
||||
] {
|
||||
assert_eq!(Command::parse(&cmd.to_line()).unwrap(), cmd);
|
||||
}
|
||||
assert!(Command::parse("n'importe quoi").is_err());
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,166 @@
|
|||
//! show-me : dessiner à plusieurs sur l'écran de celui qui stream.
|
||||
|
||||
mod app;
|
||||
mod backend;
|
||||
mod config;
|
||||
mod ipc;
|
||||
mod net;
|
||||
mod scene;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use clap::{Args, Parser, Subcommand, ValueEnum};
|
||||
use show_me_protocol::{ClearScope, EraseMode, Role};
|
||||
|
||||
use crate::ipc::Command;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(about = "Dessiner à plusieurs sur l'écran de celui qui stream", version)]
|
||||
struct Cli {
|
||||
#[command(subcommand)]
|
||||
cmd: Cmd,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Cmd {
|
||||
/// Lance l'overlay et rejoint un salon.
|
||||
Run(RunArgs),
|
||||
/// Bascule le mode dessin (à lier à un raccourci clavier).
|
||||
Toggle,
|
||||
/// Active ou désactive le mode dessin.
|
||||
Draw { state: OnOff },
|
||||
/// Change le mode d'effacement du salon, pour tout le monde.
|
||||
Mode {
|
||||
mode: ModeArg,
|
||||
/// En mode auto : délai avant effacement, en secondes.
|
||||
secs: Option<f32>,
|
||||
},
|
||||
/// Efface mes traits, ou ceux de tout le monde avec --all.
|
||||
Clear {
|
||||
#[arg(long)]
|
||||
all: bool,
|
||||
},
|
||||
/// Spectateur : cale la zone de dessin sur la vidéo du stream (glisser d'un coin à l'autre,
|
||||
/// clic droit pour valider). Avec « reset » : revient au calage automatique plein écran.
|
||||
Calibrate { action: Option<CalibrateArg> },
|
||||
/// Arrête l'overlay.
|
||||
Quit,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, ValueEnum)]
|
||||
enum OnOff {
|
||||
On,
|
||||
Off,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, ValueEnum)]
|
||||
enum CalibrateArg {
|
||||
Reset,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, ValueEnum)]
|
||||
enum ModeArg {
|
||||
Auto,
|
||||
Manual,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
struct RunArgs {
|
||||
/// Adresse du serveur relais, par exemple wss://show-me.example.org ou ws://127.0.0.1:7878.
|
||||
#[arg(long)]
|
||||
server: String,
|
||||
/// Code du salon, partagé entre les participants.
|
||||
#[arg(long)]
|
||||
room: String,
|
||||
/// Nom affiché (par défaut : le nom d'utilisateur).
|
||||
#[arg(long)]
|
||||
name: Option<String>,
|
||||
/// Je suis celui qui partage son écran : affiche les traits de tout le monde.
|
||||
#[arg(long)]
|
||||
host: bool,
|
||||
/// Couleur du trait en hexadécimal, par exemple ff3b30 (par défaut : déduite du nom).
|
||||
#[arg(long)]
|
||||
color: Option<String>,
|
||||
/// Épaisseur du trait, en pixels sur un écran de 1080 lignes.
|
||||
#[arg(long, default_value_t = 5.0)]
|
||||
width: f32,
|
||||
/// Spectateur : durée d'affichage local d'un trait avant qu'il n'arrive par le stream.
|
||||
#[arg(long, default_value_t = 1.5)]
|
||||
echo_secs: f32,
|
||||
/// Système d'affichage (par défaut : détecté d'après la session).
|
||||
#[arg(long)]
|
||||
backend: Option<app::BackendKind>,
|
||||
/// Numéro du moniteur à couvrir (par défaut : le principal).
|
||||
#[arg(long)]
|
||||
monitor: Option<usize>,
|
||||
/// Spectateur : position de la vidéo du stream sur le moniteur, sous la forme x,y,largeur,hauteur.
|
||||
/// Par défaut : la zone du dernier calage (`show-me calibrate`), sinon le plein écran.
|
||||
#[arg(long)]
|
||||
region: Option<String>,
|
||||
}
|
||||
|
||||
const PALETTE: [[u8; 3]; 8] = [
|
||||
[0xff, 0x3b, 0x30],
|
||||
[0xff, 0x95, 0x00],
|
||||
[0xff, 0xd6, 0x0a],
|
||||
[0x34, 0xc7, 0x59],
|
||||
[0x00, 0xc7, 0xbe],
|
||||
[0x0a, 0x84, 0xff],
|
||||
[0xbf, 0x5a, 0xf2],
|
||||
[0xff, 0x37, 0x5f],
|
||||
];
|
||||
|
||||
fn color_for(name: &str) -> [u8; 3] {
|
||||
let hash = name.bytes().fold(0u32, |h, b| h.wrapping_mul(31).wrapping_add(b as u32));
|
||||
PALETTE[hash as usize % PALETTE.len()]
|
||||
}
|
||||
|
||||
fn parse_color(s: &str) -> Result<[u8; 3]> {
|
||||
let hex = s.trim_start_matches('#');
|
||||
if hex.len() != 6 || !hex.is_ascii() {
|
||||
bail!("couleur invalide : {s} (attendu : rrggbb)");
|
||||
}
|
||||
let n = u32::from_str_radix(hex, 16).with_context(|| format!("couleur invalide : {s}"))?;
|
||||
Ok([(n >> 16) as u8, (n >> 8) as u8, n as u8])
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
match Cli::parse().cmd {
|
||||
Cmd::Run(args) => {
|
||||
let _ = rustls::crypto::ring::default_provider().install_default();
|
||||
let name = match args.name {
|
||||
Some(n) => n,
|
||||
None => std::env::var("USER").unwrap_or_else(|_| "anonyme".into()),
|
||||
};
|
||||
let color = match &args.color {
|
||||
Some(c) => parse_color(c)?,
|
||||
None => color_for(&name),
|
||||
};
|
||||
if !(1.0..=40.0).contains(&args.width) {
|
||||
bail!("épaisseur invalide : {} (entre 1 et 40)", args.width);
|
||||
}
|
||||
app::run(app::Config {
|
||||
backend: args.backend,
|
||||
server: args.server,
|
||||
room: args.room,
|
||||
name,
|
||||
role: if args.host { Role::Host } else { Role::Viewer },
|
||||
color,
|
||||
width: args.width / 1080.0,
|
||||
echo_secs: args.echo_secs.clamp(0.1, 30.0),
|
||||
monitor: args.monitor,
|
||||
region: match args.region.as_deref() {
|
||||
Some(s) => Some(config::parse_region(s)?),
|
||||
None if !args.host => config::load_region(),
|
||||
None => None,
|
||||
},
|
||||
})
|
||||
}
|
||||
Cmd::Toggle => ipc::send(Command::Draw(None)),
|
||||
Cmd::Draw { state } => ipc::send(Command::Draw(Some(matches!(state, OnOff::On)))),
|
||||
Cmd::Mode { mode: ModeArg::Auto, secs } => ipc::send(Command::Mode(EraseMode::Auto, secs)),
|
||||
Cmd::Mode { mode: ModeArg::Manual, .. } => ipc::send(Command::Mode(EraseMode::Manual, None)),
|
||||
Cmd::Clear { all } => ipc::send(Command::Clear(if all { ClearScope::All } else { ClearScope::Mine })),
|
||||
Cmd::Calibrate { action } => ipc::send(Command::Calibrate(action.is_some())),
|
||||
Cmd::Quit => ipc::send(Command::Quit),
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,80 @@
|
|||
//! Connexion au serveur relais, dans un fil dédié, avec reconnexion automatique.
|
||||
|
||||
use std::sync::mpsc::Sender;
|
||||
use std::time::Duration;
|
||||
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use show_me_protocol::{ClientMsg, ServerMsg};
|
||||
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
|
||||
use crate::app::Event;
|
||||
|
||||
pub enum NetEvent {
|
||||
Connected,
|
||||
Disconnected(String),
|
||||
Msg(ServerMsg),
|
||||
}
|
||||
|
||||
/// Lance le fil réseau. `hello` est renvoyé à chaque (re)connexion.
|
||||
pub fn spawn(url: String, hello: ClientMsg, events: Sender<Event>) -> UnboundedSender<ClientMsg> {
|
||||
let (tx, rx) = unbounded_channel();
|
||||
std::thread::spawn(move || {
|
||||
let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().expect("runtime tokio");
|
||||
rt.block_on(run(url, hello, events, rx));
|
||||
});
|
||||
tx
|
||||
}
|
||||
|
||||
async fn run(url: String, hello: ClientMsg, events: Sender<Event>, mut rx: UnboundedReceiver<ClientMsg>) {
|
||||
loop {
|
||||
let reason = match session(&url, &hello, &events, &mut rx).await {
|
||||
Ok(()) => "connexion fermée".to_string(),
|
||||
Err(e) => format!("{e:#}"),
|
||||
};
|
||||
if events.send(Event::Net(NetEvent::Disconnected(reason))).is_err() {
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_secs(2)).await;
|
||||
// Ce qui a été dessiné hors ligne n'est pas rejoué.
|
||||
while rx.try_recv().is_ok() {}
|
||||
}
|
||||
}
|
||||
|
||||
async fn session(
|
||||
url: &str,
|
||||
hello: &ClientMsg,
|
||||
events: &Sender<Event>,
|
||||
rx: &mut UnboundedReceiver<ClientMsg>,
|
||||
) -> anyhow::Result<()> {
|
||||
let (mut ws, _) = tokio::time::timeout(Duration::from_secs(10), tokio_tungstenite::connect_async(url))
|
||||
.await
|
||||
.map_err(|_| anyhow::anyhow!("délai de connexion dépassé"))??;
|
||||
ws.send(Message::text(serde_json::to_string(hello)?)).await?;
|
||||
events.send(Event::Net(NetEvent::Connected))?;
|
||||
|
||||
// Garde la connexion ouverte à travers les reverse proxies.
|
||||
let mut keepalive = tokio::time::interval(Duration::from_secs(20));
|
||||
loop {
|
||||
tokio::select! {
|
||||
incoming = ws.next() => {
|
||||
let Some(msg) = incoming else { return Ok(()) };
|
||||
match msg? {
|
||||
Message::Text(t) => match serde_json::from_str::<ServerMsg>(t.as_str()) {
|
||||
Ok(m) => events.send(Event::Net(NetEvent::Msg(m)))?,
|
||||
Err(e) => eprintln!("show-me: message serveur ignoré : {e}"),
|
||||
},
|
||||
Message::Close(_) => return Ok(()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
outgoing = rx.recv() => {
|
||||
let Some(msg) = outgoing else { return Ok(()) };
|
||||
ws.send(Message::text(serde_json::to_string(&msg)?)).await?;
|
||||
}
|
||||
_ = keepalive.tick() => {
|
||||
ws.send(Message::Ping(Default::default())).await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,505 @@
|
|||
//! État des dessins et rendu dans un tampon RGBA.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use show_me_protocol::{Action, ClearScope, ClientId, EraseMode, Role, RoomSettings};
|
||||
use tiny_skia::{LineCap, LineJoin, Paint, PathBuilder, Pixmap, Stroke as SkStroke, Transform};
|
||||
|
||||
/// Zone dessinée lors d'un rendu. Deux rendus successifs donnant le même `Item`
|
||||
/// ont produit les mêmes pixels à cet endroit : inutile de les renvoyer à l'écran.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Item {
|
||||
pub rect: Rect,
|
||||
pub key: u64,
|
||||
}
|
||||
|
||||
/// Identifiant utilisé localement pour nos propres traits (le serveur attribue des ids >= 1).
|
||||
pub const LOCAL: ClientId = 0;
|
||||
|
||||
const FRAME: Duration = Duration::from_millis(16);
|
||||
const PING_SECS: f32 = 1.2;
|
||||
/// Durée du fondu de l'écho local chez un spectateur.
|
||||
const ECHO_FADE_SECS: f32 = 0.4;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Rect {
|
||||
pub x: i32,
|
||||
pub y: i32,
|
||||
pub w: i32,
|
||||
pub h: i32,
|
||||
}
|
||||
|
||||
impl Rect {
|
||||
pub fn new(x: i32, y: i32, w: i32, h: i32) -> Self {
|
||||
Self { x, y, w, h }
|
||||
}
|
||||
|
||||
fn from_bounds(x0: f32, y0: f32, x1: f32, y1: f32, margin: f32) -> Self {
|
||||
let x = (x0 - margin).floor() as i32;
|
||||
let y = (y0 - margin).floor() as i32;
|
||||
Self { x, y, w: (x1 + margin).ceil() as i32 - x, h: (y1 + margin).ceil() as i32 - y }
|
||||
}
|
||||
|
||||
/// Intersection avec une surface de taille `w` x `h`, ou `None` si elle est vide.
|
||||
pub fn clipped(self, w: i32, h: i32) -> Option<Rect> {
|
||||
let x0 = self.x.max(0);
|
||||
let y0 = self.y.max(0);
|
||||
let x1 = (self.x + self.w).min(w);
|
||||
let y1 = (self.y + self.h).min(h);
|
||||
(x1 > x0 && y1 > y0).then(|| Rect::new(x0, y0, x1 - x0, y1 - y0))
|
||||
}
|
||||
}
|
||||
|
||||
struct Stroke {
|
||||
owner: ClientId,
|
||||
id: u32,
|
||||
color: [u8; 3],
|
||||
width: f32,
|
||||
points: Vec<[f32; 2]>,
|
||||
ended: Option<Instant>,
|
||||
}
|
||||
|
||||
struct PingFx {
|
||||
x: f32,
|
||||
y: f32,
|
||||
color: [u8; 3],
|
||||
start: Instant,
|
||||
}
|
||||
|
||||
pub struct Scene {
|
||||
role: Role,
|
||||
settings: RoomSettings,
|
||||
echo_secs: f32,
|
||||
strokes: Vec<Stroke>,
|
||||
pings: Vec<PingFx>,
|
||||
/// Couleur du cadre affiché en mode dessin, le cas échéant.
|
||||
pub border: Option<[u8; 3]>,
|
||||
/// Hôte : spectateurs en cours de calage, pour qui on affiche des repères aux coins.
|
||||
guides: BTreeSet<ClientId>,
|
||||
/// Spectateur en cours de calage : zone laissée claire dans le voile sombre.
|
||||
pub calib: Option<Rect>,
|
||||
}
|
||||
|
||||
impl Scene {
|
||||
pub fn new(role: Role, echo_secs: f32) -> Self {
|
||||
Self {
|
||||
role,
|
||||
settings: RoomSettings::default(),
|
||||
echo_secs,
|
||||
strokes: Vec::new(),
|
||||
pings: Vec::new(),
|
||||
border: None,
|
||||
guides: BTreeSet::new(),
|
||||
calib: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn settings(&self) -> RoomSettings {
|
||||
self.settings
|
||||
}
|
||||
|
||||
pub fn set_settings(&mut self, settings: RoomSettings, now: Instant) {
|
||||
if self.settings.mode == EraseMode::Manual && settings.mode == EraseMode::Auto {
|
||||
// Les traits conservés jusque-là commencent leur compte à rebours maintenant.
|
||||
for s in &mut self.strokes {
|
||||
if s.ended.is_some() {
|
||||
s.ended = Some(now);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.settings = settings;
|
||||
}
|
||||
|
||||
/// Applique une action venant de `owner` (`LOCAL` pour les nôtres).
|
||||
pub fn apply(&mut self, owner: ClientId, action: &Action, now: Instant) {
|
||||
// Un spectateur voit les traits des autres dans le stream : il n'affiche que les siens.
|
||||
let shown = self.role == Role::Host || owner == LOCAL;
|
||||
match action {
|
||||
Action::StrokeStart { id, color, width } if shown => {
|
||||
self.strokes.push(Stroke {
|
||||
owner,
|
||||
id: *id,
|
||||
color: *color,
|
||||
width: *width,
|
||||
points: Vec::new(),
|
||||
ended: None,
|
||||
});
|
||||
}
|
||||
Action::StrokePoints { id, points } if shown => {
|
||||
if let Some(s) = self.find(owner, *id) {
|
||||
s.points.extend_from_slice(points);
|
||||
}
|
||||
}
|
||||
Action::StrokeEnd { id } if shown => {
|
||||
if let Some(s) = self.find(owner, *id) {
|
||||
s.ended = Some(now);
|
||||
}
|
||||
}
|
||||
Action::Ping { x, y, color } if shown => {
|
||||
self.pings.push(PingFx { x: *x, y: *y, color: *color, start: now });
|
||||
}
|
||||
Action::Clear { scope: ClearScope::All } => {
|
||||
self.strokes.clear();
|
||||
self.pings.clear();
|
||||
}
|
||||
Action::Clear { scope: ClearScope::Mine } => {
|
||||
self.strokes.retain(|s| s.owner != owner);
|
||||
}
|
||||
Action::Guides { on } if self.role == Role::Host && owner != LOCAL => {
|
||||
if *on {
|
||||
self.guides.insert(owner);
|
||||
} else {
|
||||
self.guides.remove(&owner);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Retire tous les repères de calage (connexion au salon perdue).
|
||||
pub fn clear_guides(&mut self) {
|
||||
self.guides.clear();
|
||||
}
|
||||
|
||||
/// Un participant est parti : termine ses traits en cours et retire ses repères.
|
||||
pub fn peer_left(&mut self, owner: ClientId, now: Instant) {
|
||||
self.guides.remove(&owner);
|
||||
for s in &mut self.strokes {
|
||||
if s.owner == owner && s.ended.is_none() {
|
||||
s.ended = Some(now);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn find(&mut self, owner: ClientId, id: u32) -> Option<&mut Stroke> {
|
||||
self.strokes.iter_mut().rev().find(|s| s.owner == owner && s.id == id)
|
||||
}
|
||||
|
||||
/// (durée de vie après la fin du trait, durée du fondu final), ou `None` si le trait est permanent.
|
||||
fn lifetime(&self) -> Option<(f32, f32)> {
|
||||
match self.role {
|
||||
Role::Viewer => Some((self.echo_secs, ECHO_FADE_SECS.min(self.echo_secs))),
|
||||
Role::Host => match self.settings.mode {
|
||||
EraseMode::Manual => None,
|
||||
EraseMode::Auto => Some((self.settings.fade_secs, self.settings.fade_secs.min(1.0))),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Opacité d'un trait, ou `None` s'il a expiré.
|
||||
fn alpha(&self, s: &Stroke, now: Instant) -> Option<f32> {
|
||||
let (Some((life, fade)), Some(ended)) = (self.lifetime(), s.ended) else { return Some(1.0) };
|
||||
let elapsed = now.duration_since(ended).as_secs_f32();
|
||||
(elapsed < life).then(|| ((life - elapsed) / fade).min(1.0))
|
||||
}
|
||||
|
||||
/// Délai avant le prochain rendu nécessaire aux animations, ou `None` si la scène est statique.
|
||||
pub fn next_wake(&self, now: Instant) -> Option<Duration> {
|
||||
if !self.pings.is_empty() {
|
||||
return Some(FRAME);
|
||||
}
|
||||
let (life, fade) = self.lifetime()?;
|
||||
self.strokes
|
||||
.iter()
|
||||
.filter_map(|s| s.ended)
|
||||
.map(|ended| {
|
||||
let until_fade = (life - fade) - now.duration_since(ended).as_secs_f32();
|
||||
if until_fade <= 0.0 { FRAME } else { Duration::from_secs_f32(until_fade).max(FRAME) }
|
||||
})
|
||||
.min()
|
||||
}
|
||||
|
||||
/// Dessine la scène dans `pixmap`, à l'intérieur de `view`, et renvoie les zones touchées.
|
||||
pub fn render(&mut self, pixmap: &mut Pixmap, view: Rect, now: Instant) -> Vec<Item> {
|
||||
pixmap.fill(tiny_skia::Color::TRANSPARENT);
|
||||
let mut items: Vec<Item> = Vec::new();
|
||||
|
||||
let alphas: Vec<Option<f32>> = self.strokes.iter().map(|s| self.alpha(s, now)).collect();
|
||||
let mut keep = alphas.iter().map(Option::is_some);
|
||||
self.strokes.retain(|_| keep.next().unwrap());
|
||||
self.pings.retain(|p| now.duration_since(p.start).as_secs_f32() < PING_SECS);
|
||||
|
||||
let to_px = |p: [f32; 2]| (view.x as f32 + p[0] * view.w as f32, view.y as f32 + p[1] * view.h as f32);
|
||||
|
||||
for (s, alpha) in self.strokes.iter().zip(alphas.into_iter().flatten()) {
|
||||
let Some(&first) = s.points.first() else { continue };
|
||||
let width = (s.width * view.h as f32).max(1.5);
|
||||
let (fx, fy) = to_px(first);
|
||||
let (mut x0, mut y0, mut x1, mut y1) = (fx, fy, fx, fy);
|
||||
let mut pb = PathBuilder::new();
|
||||
pb.move_to(fx, fy);
|
||||
let mut moved = false;
|
||||
// Lissage : courbes quadratiques passant par les milieux des segments.
|
||||
let mut prev = (fx, fy);
|
||||
for &p in &s.points[1..] {
|
||||
let (x, y) = to_px(p);
|
||||
moved |= (x - fx).abs() > 0.01 || (y - fy).abs() > 0.01;
|
||||
pb.quad_to(prev.0, prev.1, (prev.0 + x) / 2.0, (prev.1 + y) / 2.0);
|
||||
prev = (x, y);
|
||||
x0 = x0.min(x);
|
||||
y0 = y0.min(y);
|
||||
x1 = x1.max(x);
|
||||
y1 = y1.max(y);
|
||||
}
|
||||
pb.line_to(prev.0, prev.1);
|
||||
let a = (alpha * 255.0) as u8;
|
||||
if moved {
|
||||
if let Some(path) = pb.finish() {
|
||||
// Liseré sombre pour rester lisible sur fond clair.
|
||||
stroke(pixmap, &path, [0, 0, 0], a / 2, width + 2.5);
|
||||
stroke(pixmap, &path, s.color, a, width);
|
||||
}
|
||||
} else {
|
||||
fill_circle(pixmap, fx, fy, width / 2.0 + 1.25, [0, 0, 0], a / 2);
|
||||
fill_circle(pixmap, fx, fy, width / 2.0, s.color, a);
|
||||
}
|
||||
let key = ((s.points.len() as u64) << 8) | a as u64;
|
||||
items.push(Item { rect: Rect::from_bounds(x0, y0, x1, y1, width / 2.0 + 3.0), key });
|
||||
}
|
||||
|
||||
for p in &self.pings {
|
||||
let t = now.duration_since(p.start).as_secs_f32() / PING_SECS;
|
||||
let (cx, cy) = to_px([p.x, p.y]);
|
||||
let h = view.h as f32;
|
||||
let max_r = 0.05 * h;
|
||||
// Deux ondes décalées.
|
||||
for phase in [0.0, 0.35] {
|
||||
let u = t - phase;
|
||||
if !(0.0..1.0).contains(&u) {
|
||||
continue;
|
||||
}
|
||||
let r = 0.008 * h + (max_r - 0.008 * h) * (1.0 - (1.0 - u) * (1.0 - u));
|
||||
let a = ((1.0 - u) * 255.0) as u8;
|
||||
if let Some(path) = PathBuilder::from_circle(cx, cy, r) {
|
||||
stroke(pixmap, &path, [0, 0, 0], a / 2, 0.006 * h + 2.5);
|
||||
stroke(pixmap, &path, p.color, a, 0.006 * h);
|
||||
}
|
||||
}
|
||||
fill_circle(pixmap, cx, cy, 0.006 * h, p.color, ((1.0 - t) * 255.0) as u8);
|
||||
let rect = Rect::from_bounds(cx - max_r, cy - max_r, cx + max_r, cy + max_r, 0.006 * h + 3.0);
|
||||
items.push(Item { rect, key: now.duration_since(p.start).as_micros() as u64 });
|
||||
}
|
||||
|
||||
if let Some(color) = self.border {
|
||||
const T: i32 = 3;
|
||||
let sides = [
|
||||
Rect::new(view.x, view.y, view.w, T),
|
||||
Rect::new(view.x, view.y + view.h - T, view.w, T),
|
||||
Rect::new(view.x, view.y, T, view.h),
|
||||
Rect::new(view.x + view.w - T, view.y, T, view.h),
|
||||
];
|
||||
let mut paint = Paint::default();
|
||||
paint.set_color_rgba8(color[0], color[1], color[2], 200);
|
||||
for r in sides {
|
||||
if let Some(sk) = tiny_skia::Rect::from_xywh(r.x as f32, r.y as f32, r.w as f32, r.h as f32) {
|
||||
pixmap.fill_rect(sk, &paint, Transform::identity(), None);
|
||||
}
|
||||
let key = u32::from_be_bytes([0, color[0], color[1], color[2]]) as u64;
|
||||
items.push(Item { rect: r, key });
|
||||
}
|
||||
}
|
||||
|
||||
if !self.guides.is_empty() {
|
||||
// Repères en équerre aux quatre coins, visibles dans le stream.
|
||||
let len = (view.h as f32 * 0.08) as i32;
|
||||
const T: i32 = 5;
|
||||
for (right, bottom) in [(false, false), (true, false), (false, true), (true, true)] {
|
||||
let x = if right { view.x + view.w - len } else { view.x };
|
||||
let y = if bottom { view.y + view.h - len } else { view.y };
|
||||
let bar_h = Rect::new(x, if bottom { y + len - T } else { y }, len, T);
|
||||
let bar_v = Rect::new(if right { x + len - T } else { x }, y, T, len);
|
||||
for bar in [bar_h, bar_v] {
|
||||
fill_rect(pixmap, Rect::new(bar.x - 1, bar.y - 1, bar.w + 2, bar.h + 2), [0, 0, 0], 255);
|
||||
}
|
||||
for bar in [bar_h, bar_v] {
|
||||
fill_rect(pixmap, bar, [255, 255, 255], 255);
|
||||
}
|
||||
items.push(Item { rect: Rect::new(x - 1, y - 1, len + 2, len + 2), key: 1 });
|
||||
}
|
||||
}
|
||||
|
||||
let (w, h) = (pixmap.width() as i32, pixmap.height() as i32);
|
||||
if let Some(hole) = self.calib {
|
||||
// Voile sombre partout sauf sur la zone en cours de calage, entourée d'un liseré.
|
||||
let hole = hole.clipped(w, h).unwrap_or(Rect::new(0, 0, 0, 0));
|
||||
let veil = [
|
||||
Rect::new(0, 0, w, hole.y),
|
||||
Rect::new(0, hole.y + hole.h, w, h - hole.y - hole.h),
|
||||
Rect::new(0, hole.y, hole.x, hole.h),
|
||||
Rect::new(hole.x + hole.w, hole.y, w - hole.x - hole.w, hole.h),
|
||||
];
|
||||
for r in veil {
|
||||
fill_rect(pixmap, r, [0, 0, 0], 120);
|
||||
}
|
||||
const T: i32 = 2;
|
||||
for r in [
|
||||
Rect::new(hole.x, hole.y, hole.w, T),
|
||||
Rect::new(hole.x, hole.y + hole.h - T, hole.w, T),
|
||||
Rect::new(hole.x, hole.y, T, hole.h),
|
||||
Rect::new(hole.x + hole.w - T, hole.y, T, hole.h),
|
||||
] {
|
||||
fill_rect(pixmap, r, [255, 255, 255], 255);
|
||||
}
|
||||
let key = (1 << 63)
|
||||
| ((hole.x as u64 & 0x7fff) << 48)
|
||||
| ((hole.y as u64 & 0xffff) << 32)
|
||||
| ((hole.w as u64 & 0xffff) << 16)
|
||||
| (hole.h as u64 & 0xffff);
|
||||
items.push(Item { rect: Rect::new(0, 0, w, h), key });
|
||||
}
|
||||
|
||||
items.into_iter().filter_map(|i| Some(Item { rect: i.rect.clipped(w, h)?, key: i.key })).collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn stroke(pixmap: &mut Pixmap, path: &tiny_skia::Path, color: [u8; 3], alpha: u8, width: f32) {
|
||||
let mut paint = Paint::default();
|
||||
paint.set_color_rgba8(color[0], color[1], color[2], alpha);
|
||||
paint.anti_alias = true;
|
||||
let style = SkStroke { width, line_cap: LineCap::Round, line_join: LineJoin::Round, ..Default::default() };
|
||||
pixmap.stroke_path(path, &paint, &style, Transform::identity(), None);
|
||||
}
|
||||
|
||||
fn fill_rect(pixmap: &mut Pixmap, r: Rect, color: [u8; 3], alpha: u8) {
|
||||
let Some(sk) = tiny_skia::Rect::from_xywh(r.x as f32, r.y as f32, r.w as f32, r.h as f32) else { return };
|
||||
let mut paint = Paint::default();
|
||||
paint.set_color_rgba8(color[0], color[1], color[2], alpha);
|
||||
pixmap.fill_rect(sk, &paint, Transform::identity(), None);
|
||||
}
|
||||
|
||||
fn fill_circle(pixmap: &mut Pixmap, x: f32, y: f32, r: f32, color: [u8; 3], alpha: u8) {
|
||||
let Some(path) = PathBuilder::from_circle(x, y, r) else { return };
|
||||
let mut paint = Paint::default();
|
||||
paint.set_color_rgba8(color[0], color[1], color[2], alpha);
|
||||
paint.anti_alias = true;
|
||||
pixmap.fill_path(&path, &paint, tiny_skia::FillRule::Winding, Transform::identity(), None);
|
||||
}
|
||||
|
||||
/// Plus grand rectangle de rapport `aspect` centré dans une surface `w` x `h`.
|
||||
pub fn letterbox(w: i32, h: i32, aspect: f32) -> Rect {
|
||||
let (wf, hf) = (w as f32, h as f32);
|
||||
if wf / hf > aspect {
|
||||
let vw = (hf * aspect).round() as i32;
|
||||
Rect::new((w - vw) / 2, 0, vw, h)
|
||||
} else {
|
||||
let vh = (wf / aspect).round() as i32;
|
||||
Rect::new(0, (h - vh) / 2, w, vh)
|
||||
}
|
||||
}
|
||||
|
||||
/// Rectangle allant de `a` à `b`, quel que soit le sens du geste.
|
||||
pub fn rect_between(a: (f32, f32), b: (f32, f32)) -> Rect {
|
||||
let (x0, y0) = (a.0.min(b.0).round() as i32, a.1.min(b.1).round() as i32);
|
||||
let (x1, y1) = (a.0.max(b.0).round() as i32, a.1.max(b.1).round() as i32);
|
||||
Rect::new(x0, y0, x1 - x0, y1 - y0)
|
||||
}
|
||||
|
||||
/// Ramène un rectangle tracé à la main au rapport `aspect` exact, en gardant son centre et sa
|
||||
/// surface : les imprécisions du geste en largeur et en hauteur se compensent.
|
||||
pub fn fit_aspect(r: Rect, aspect: f32) -> Rect {
|
||||
let w = (r.w as f32 * r.h as f32 * aspect).sqrt();
|
||||
let h = w / aspect;
|
||||
let (cx, cy) = (r.x as f32 + r.w as f32 / 2.0, r.y as f32 + r.h as f32 / 2.0);
|
||||
Rect::new((cx - w / 2.0).round() as i32, (cy - h / 2.0).round() as i32, w.round() as i32, h.round() as i32)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn stroke_actions(id: u32) -> [Action; 3] {
|
||||
[
|
||||
Action::StrokeStart { id, color: [255, 0, 0], width: 0.004 },
|
||||
Action::StrokePoints { id, points: vec![[0.1, 0.1], [0.5, 0.5]] },
|
||||
Action::StrokeEnd { id },
|
||||
]
|
||||
}
|
||||
|
||||
fn draw(scene: &mut Scene, owner: ClientId, id: u32, now: Instant) {
|
||||
for a in stroke_actions(id) {
|
||||
scene.apply(owner, &a, now);
|
||||
}
|
||||
}
|
||||
|
||||
fn render(scene: &mut Scene, now: Instant) -> Vec<Item> {
|
||||
let mut pixmap = Pixmap::new(200, 100).unwrap();
|
||||
scene.render(&mut pixmap, Rect::new(0, 0, 200, 100), now)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn letterbox_fits_both_ways() {
|
||||
assert_eq!(letterbox(1920, 1200, 16.0 / 9.0), Rect::new(0, 60, 1920, 1080));
|
||||
assert_eq!(letterbox(2560, 1080, 16.0 / 9.0), Rect::new(320, 0, 1920, 1080));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fit_aspect_keeps_center_and_fixes_ratio() {
|
||||
// Tracé un peu trop large et pas assez haut autour d'une vidéo 16:9 de 1600x900.
|
||||
let r = fit_aspect(Rect::new(95, 110, 1610, 890), 16.0 / 9.0);
|
||||
assert!((r.w as f32 / r.h as f32 - 16.0 / 9.0).abs() < 0.01);
|
||||
assert!((r.w - 1600).abs() <= 6 && (r.h - 900).abs() <= 4, "{r:?}");
|
||||
assert!((r.x + r.w / 2 - 900).abs() <= 1 && (r.y + r.h / 2 - 555).abs() <= 1);
|
||||
assert_eq!(rect_between((300.0, 200.0), (100.0, 50.0)), Rect::new(100, 50, 200, 150));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_shows_guides_while_a_viewer_calibrates() {
|
||||
let t0 = Instant::now();
|
||||
let mut scene = Scene::new(Role::Host, 1.5);
|
||||
scene.apply(7, &Action::Guides { on: true }, t0);
|
||||
assert_eq!(render(&mut scene, t0).len(), 4);
|
||||
scene.peer_left(7, t0);
|
||||
assert!(render(&mut scene, t0).is_empty());
|
||||
|
||||
// Un spectateur n'affiche jamais de repères, seulement son voile de calage.
|
||||
let mut viewer = Scene::new(Role::Viewer, 1.5);
|
||||
viewer.apply(7, &Action::Guides { on: true }, t0);
|
||||
assert!(render(&mut viewer, t0).is_empty());
|
||||
viewer.calib = Some(Rect::new(20, 10, 100, 50));
|
||||
assert_eq!(render(&mut viewer, t0).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_mode_expires_strokes() {
|
||||
let t0 = Instant::now();
|
||||
let mut scene = Scene::new(Role::Host, 1.5);
|
||||
draw(&mut scene, 7, 1, t0);
|
||||
assert_eq!(render(&mut scene, t0 + Duration::from_secs(4)).len(), 1);
|
||||
assert!(scene.next_wake(t0 + Duration::from_secs(1)).unwrap() > FRAME);
|
||||
assert_eq!(scene.next_wake(t0 + Duration::from_millis(4500)), Some(FRAME));
|
||||
assert!(render(&mut scene, t0 + Duration::from_secs(6)).is_empty());
|
||||
assert_eq!(scene.next_wake(t0 + Duration::from_secs(6)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manual_mode_keeps_strokes_until_switch_or_clear() {
|
||||
let t0 = Instant::now();
|
||||
let mut scene = Scene::new(Role::Host, 1.5);
|
||||
scene.set_settings(RoomSettings { mode: EraseMode::Manual, fade_secs: 5.0 }, t0);
|
||||
draw(&mut scene, 7, 1, t0);
|
||||
draw(&mut scene, 8, 1, t0);
|
||||
let later = t0 + Duration::from_secs(100);
|
||||
assert_eq!(render(&mut scene, later).len(), 2);
|
||||
assert_eq!(scene.next_wake(later), None);
|
||||
|
||||
scene.apply(7, &Action::Clear { scope: ClearScope::Mine }, later);
|
||||
assert_eq!(render(&mut scene, later).len(), 1);
|
||||
|
||||
// Le passage en auto relance le compte à rebours à partir de maintenant.
|
||||
scene.set_settings(RoomSettings { mode: EraseMode::Auto, fade_secs: 5.0 }, later);
|
||||
assert_eq!(render(&mut scene, later + Duration::from_secs(4)).len(), 1);
|
||||
assert!(render(&mut scene, later + Duration::from_secs(6)).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn viewer_only_echoes_own_strokes() {
|
||||
let t0 = Instant::now();
|
||||
let mut scene = Scene::new(Role::Viewer, 1.5);
|
||||
draw(&mut scene, 7, 1, t0);
|
||||
assert!(render(&mut scene, t0).is_empty());
|
||||
draw(&mut scene, LOCAL, 1, t0);
|
||||
assert_eq!(render(&mut scene, t0 + Duration::from_secs(1)).len(), 1);
|
||||
assert!(render(&mut scene, t0 + Duration::from_secs(2)).is_empty());
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
[package]
|
||||
name = "show-me-protocol"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1.0.229", features = ["derive"] }
|
||||
|
|
@ -0,0 +1,115 @@
|
|||
//! Messages échangés entre les clients show-me et le serveur relais (JSON sur WebSocket).
|
||||
//!
|
||||
//! Toutes les coordonnées sont normalisées entre 0 et 1 par rapport à l'écran de l'hôte.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub type ClientId = u32;
|
||||
|
||||
pub const MAX_ROOM_LEN: usize = 64;
|
||||
pub const MAX_NAME_LEN: usize = 32;
|
||||
pub const MAX_POINTS_PER_MSG: usize = 512;
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Role {
|
||||
/// Celui qui partage son écran : affiche les traits de tout le monde.
|
||||
Host,
|
||||
/// Regarde le stream : envoie ses traits, n'affiche qu'un écho local.
|
||||
Viewer,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum EraseMode {
|
||||
/// Les traits s'estompent `fade_secs` secondes après avoir été terminés.
|
||||
Auto,
|
||||
/// Les traits restent jusqu'à un « effacer ».
|
||||
Manual,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq)]
|
||||
pub struct RoomSettings {
|
||||
pub mode: EraseMode,
|
||||
pub fade_secs: f32,
|
||||
}
|
||||
|
||||
impl Default for RoomSettings {
|
||||
fn default() -> Self {
|
||||
Self { mode: EraseMode::Auto, fade_secs: 5.0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl RoomSettings {
|
||||
pub fn sanitized(mut self) -> Self {
|
||||
if !self.fade_secs.is_finite() {
|
||||
self.fade_secs = 5.0;
|
||||
}
|
||||
self.fade_secs = self.fade_secs.clamp(0.5, 600.0);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ClearScope {
|
||||
Mine,
|
||||
All,
|
||||
}
|
||||
|
||||
/// Action de dessin, relayée telle quelle aux autres participants du salon.
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||
pub enum Action {
|
||||
/// `width` est une fraction de la hauteur de l'écran de l'hôte.
|
||||
StrokeStart { id: u32, color: [u8; 3], width: f32 },
|
||||
StrokePoints { id: u32, points: Vec<[f32; 2]> },
|
||||
StrokeEnd { id: u32 },
|
||||
Ping { x: f32, y: f32, color: [u8; 3] },
|
||||
Clear { scope: ClearScope },
|
||||
/// Un spectateur cale sa zone : l'hôte affiche des repères aux coins de son écran.
|
||||
Guides { on: bool },
|
||||
}
|
||||
|
||||
impl Action {
|
||||
/// Vérifie les bornes : le serveur rejette les actions invalides.
|
||||
pub fn is_valid(&self) -> bool {
|
||||
let ok = |v: f32| v.is_finite() && (-0.5..=1.5).contains(&v);
|
||||
match self {
|
||||
Action::StrokeStart { width, .. } => width.is_finite() && (0.0005..=0.05).contains(width),
|
||||
Action::StrokePoints { points, .. } => {
|
||||
points.len() <= MAX_POINTS_PER_MSG && points.iter().all(|p| ok(p[0]) && ok(p[1]))
|
||||
}
|
||||
Action::Ping { x, y, .. } => ok(*x) && ok(*y),
|
||||
Action::StrokeEnd { .. } | Action::Clear { .. } | Action::Guides { .. } => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
|
||||
pub struct Peer {
|
||||
pub id: ClientId,
|
||||
pub name: String,
|
||||
pub role: Role,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum ClientMsg {
|
||||
/// Premier message obligatoire. `aspect` (largeur / hauteur de l'écran) est fourni par l'hôte.
|
||||
Hello { room: String, name: String, role: Role, aspect: Option<f32> },
|
||||
Action { action: Action },
|
||||
SetSettings { settings: RoomSettings },
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum ServerMsg {
|
||||
Welcome { you: ClientId, settings: RoomSettings, host_aspect: Option<f32>, peers: Vec<Peer> },
|
||||
PeerJoined { peer: Peer },
|
||||
PeerLeft { id: ClientId },
|
||||
Action { from: ClientId, action: Action },
|
||||
Settings { settings: RoomSettings },
|
||||
HostAspect { aspect: Option<f32> },
|
||||
Error { message: String },
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
[package]
|
||||
name = "show-me-server"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.104"
|
||||
clap = { version = "4.6.7", features = ["derive"] }
|
||||
futures-util = "0.3.34"
|
||||
serde_json = "1.0.154"
|
||||
show-me-protocol = { version = "0.1.0", path = "../protocol" }
|
||||
tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "net", "sync", "time"] }
|
||||
tokio-tungstenite = "0.30.0"
|
||||
|
|
@ -0,0 +1,232 @@
|
|||
//! Serveur relais show-me : des salons, et la diffusion des actions entre participants.
|
||||
//!
|
||||
//! Écoute en WebSocket simple ; le TLS est à la charge du reverse proxy.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use clap::Parser;
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use show_me_protocol::{
|
||||
ClientId, ClientMsg, MAX_NAME_LEN, MAX_ROOM_LEN, Peer, Role, RoomSettings, ServerMsg,
|
||||
};
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
use tokio::sync::mpsc;
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
use tokio_tungstenite::tungstenite::protocol::WebSocketConfig;
|
||||
|
||||
const MAX_MESSAGE_BYTES: usize = 64 * 1024;
|
||||
const MAX_ROOMS: usize = 1024;
|
||||
const MAX_CLIENTS_PER_ROOM: usize = 32;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(about = "Serveur relais show-me")]
|
||||
struct Args {
|
||||
/// Adresse d'écoute (WebSocket sans TLS, à placer derrière un reverse proxy).
|
||||
#[arg(long, default_value = "127.0.0.1:7878")]
|
||||
listen: SocketAddr,
|
||||
}
|
||||
|
||||
struct Member {
|
||||
peer: Peer,
|
||||
tx: mpsc::UnboundedSender<ServerMsg>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Room {
|
||||
settings: RoomSettings,
|
||||
/// Hôte courant et rapport largeur/hauteur de son écran.
|
||||
host: Option<(ClientId, f32)>,
|
||||
members: HashMap<ClientId, Member>,
|
||||
}
|
||||
|
||||
impl Room {
|
||||
fn broadcast(&self, msg: &ServerMsg, except: Option<ClientId>) {
|
||||
for (id, m) in &self.members {
|
||||
if Some(*id) != except {
|
||||
let _ = m.tx.send(msg.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
rooms: Mutex<HashMap<String, Room>>,
|
||||
next_id: AtomicU32,
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
let args = Args::parse();
|
||||
let listener = TcpListener::bind(args.listen).await.with_context(|| format!("écoute sur {}", args.listen))?;
|
||||
eprintln!("show-me-server écoute sur ws://{}", args.listen);
|
||||
let state = Arc::new(State { next_id: AtomicU32::new(1), ..Default::default() });
|
||||
loop {
|
||||
let (stream, addr) = listener.accept().await?;
|
||||
let state = state.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = handle(stream, state).await {
|
||||
eprintln!("{addr}: {e:#}");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn parse(msg: &Message) -> Result<Option<ClientMsg>> {
|
||||
match msg {
|
||||
Message::Text(t) => Ok(Some(serde_json::from_str(t.as_str()).context("message invalide")?)),
|
||||
Message::Close(_) => bail!("fermé"),
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle(stream: TcpStream, state: Arc<State>) -> Result<()> {
|
||||
stream.set_nodelay(true).ok();
|
||||
let config = WebSocketConfig::default()
|
||||
.max_message_size(Some(MAX_MESSAGE_BYTES))
|
||||
.max_frame_size(Some(MAX_MESSAGE_BYTES));
|
||||
let ws = tokio_tungstenite::accept_async_with_config(stream, Some(config)).await?;
|
||||
let (mut sink, mut source) = ws.split();
|
||||
|
||||
// Le premier message doit être un Hello, dans les dix secondes.
|
||||
let hello = tokio::time::timeout(Duration::from_secs(10), async {
|
||||
loop {
|
||||
let msg = source.next().await.context("connexion fermée avant Hello")??;
|
||||
if let Some(m) = parse(&msg)? {
|
||||
return anyhow::Ok(m);
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.context("pas de Hello")??;
|
||||
let ClientMsg::Hello { room: room_name, name, role, aspect } = hello else {
|
||||
bail!("le premier message doit être Hello");
|
||||
};
|
||||
|
||||
let refuse = |message: &str| ServerMsg::Error { message: message.to_string() };
|
||||
let aspect = aspect.filter(|a| a.is_finite() && (0.2..=10.0).contains(a));
|
||||
let error = if room_name.is_empty() || room_name.len() > MAX_ROOM_LEN {
|
||||
Some(refuse("nom de salon invalide"))
|
||||
} else if name.is_empty() || name.len() > MAX_NAME_LEN {
|
||||
Some(refuse("nom invalide"))
|
||||
} else if role == Role::Host && aspect.is_none() {
|
||||
Some(refuse("l'hôte doit fournir le rapport d'aspect de son écran"))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(e) = error {
|
||||
sink.send(Message::text(serde_json::to_string(&e)?)).await.ok();
|
||||
bail!("Hello refusé");
|
||||
}
|
||||
|
||||
let id = state.next_id.fetch_add(1, Ordering::Relaxed);
|
||||
let peer = Peer { id, name, role };
|
||||
let (tx, mut rx) = mpsc::unbounded_channel::<ServerMsg>();
|
||||
|
||||
// Entrée dans le salon.
|
||||
let joined = {
|
||||
let mut rooms = state.rooms.lock().unwrap();
|
||||
if !rooms.contains_key(&room_name) && rooms.len() >= MAX_ROOMS {
|
||||
Err(refuse("trop de salons"))
|
||||
} else {
|
||||
let room = rooms.entry(room_name.clone()).or_default();
|
||||
if room.members.len() >= MAX_CLIENTS_PER_ROOM {
|
||||
Err(refuse("salon plein"))
|
||||
} else {
|
||||
if role == Role::Host {
|
||||
room.host = aspect.map(|a| (id, a));
|
||||
}
|
||||
let host_aspect = room.host.map(|(_, a)| a);
|
||||
tx.send(ServerMsg::Welcome {
|
||||
you: id,
|
||||
settings: room.settings,
|
||||
host_aspect,
|
||||
peers: room.members.values().map(|m| m.peer.clone()).collect(),
|
||||
})
|
||||
.ok();
|
||||
room.broadcast(&ServerMsg::PeerJoined { peer: peer.clone() }, None);
|
||||
if role == Role::Host {
|
||||
room.broadcast(&ServerMsg::HostAspect { aspect: host_aspect }, None);
|
||||
}
|
||||
room.members.insert(id, Member { peer: peer.clone(), tx });
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
};
|
||||
if let Err(e) = joined {
|
||||
sink.send(Message::text(serde_json::to_string(&e)?)).await.ok();
|
||||
bail!("entrée refusée");
|
||||
}
|
||||
eprintln!("[{room_name}] + {} ({:?}, #{id})", peer.name, peer.role);
|
||||
|
||||
let writer = tokio::spawn(async move {
|
||||
while let Some(msg) = rx.recv().await {
|
||||
let Ok(text) = serde_json::to_string(&msg) else { continue };
|
||||
if sink.send(Message::text(text)).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let result = read_loop(&mut source, &state, &room_name, id).await;
|
||||
|
||||
// Sortie du salon.
|
||||
{
|
||||
let mut rooms = state.rooms.lock().unwrap();
|
||||
if let Some(room) = rooms.get_mut(&room_name) {
|
||||
room.members.remove(&id);
|
||||
room.broadcast(&ServerMsg::PeerLeft { id }, None);
|
||||
if room.host.is_some_and(|(h, _)| h == id) {
|
||||
room.host = None;
|
||||
room.broadcast(&ServerMsg::HostAspect { aspect: None }, None);
|
||||
}
|
||||
if room.members.is_empty() {
|
||||
rooms.remove(&room_name);
|
||||
}
|
||||
}
|
||||
}
|
||||
writer.abort();
|
||||
eprintln!("[{room_name}] - {} (#{id})", peer.name);
|
||||
result
|
||||
}
|
||||
|
||||
async fn read_loop(
|
||||
source: &mut (impl StreamExt<Item = Result<Message, tokio_tungstenite::tungstenite::Error>> + Unpin),
|
||||
state: &State,
|
||||
room_name: &str,
|
||||
id: ClientId,
|
||||
) -> Result<()> {
|
||||
while let Some(msg) = source.next().await {
|
||||
let msg = match msg {
|
||||
Ok(m) => m,
|
||||
Err(_) => break,
|
||||
};
|
||||
let parsed = match parse(&msg) {
|
||||
Ok(Some(m)) => m,
|
||||
Ok(None) => continue,
|
||||
Err(_) if matches!(msg, Message::Close(_)) => break,
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let rooms = &mut state.rooms.lock().unwrap();
|
||||
let Some(room) = rooms.get_mut(room_name) else { break };
|
||||
match parsed {
|
||||
ClientMsg::Hello { .. } => bail!("Hello en double"),
|
||||
ClientMsg::Action { action } => {
|
||||
if !action.is_valid() {
|
||||
bail!("action invalide");
|
||||
}
|
||||
room.broadcast(&ServerMsg::Action { from: id, action }, Some(id));
|
||||
}
|
||||
ClientMsg::SetSettings { settings } => {
|
||||
room.settings = settings.sanitized();
|
||||
room.broadcast(&ServerMsg::Settings { settings: room.settings }, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
#!/bin/sh
|
||||
# À lancer sur la machine distante (par scripts/test-remote.sh) : ouvre Sway dans une fenêtre de
|
||||
# la session Xorg en cours, avec show-me en mode hôte dedans.
|
||||
# Usage : remote-host.sh ADRESSE_DU_SERVEUR
|
||||
set -eu
|
||||
DIR=$(dirname "$(readlink -f "$0")")
|
||||
SERVER=${1:?adresse du serveur attendue, par exemple ws://127.0.0.1:7878}
|
||||
export DISPLAY=${DISPLAY:-:0}
|
||||
unset WAYLAND_DISPLAY
|
||||
CFG=$(mktemp)
|
||||
trap 'rm -f "$CFG"' EXIT
|
||||
cat > "$CFG" <<CFGEOF
|
||||
xwayland disable
|
||||
output * bg #2b5278 solid_color
|
||||
default_border pixel 2
|
||||
# Raccourcis actifs quand la fenêtre Sway a le focus.
|
||||
bindsym F9 exec $DIR/show-me toggle
|
||||
bindsym F10 exec $DIR/show-me clear --all
|
||||
bindsym F11 exec $DIR/show-me mode manual
|
||||
bindsym F12 exec $DIR/show-me mode auto 5
|
||||
bindsym Escape exec $DIR/show-me quit, exit
|
||||
exec foot
|
||||
exec $DIR/show-me run --server $SERVER --room test --name Distant --host
|
||||
CFGEOF
|
||||
WLR_BACKENDS=x11 exec sway -c "$CFG"
|
||||
|
|
@ -0,0 +1,54 @@
|
|||
#!/bin/sh
|
||||
# Test à deux machines : serveur et spectateur ici, hôte Wayland (Sway en fenêtre) sur une
|
||||
# seconde machine joignable en SSH, où sway est installé et une session Xorg ouverte.
|
||||
# Le serveur n'écoute qu'en local : la machine distante le joint par un tunnel SSH inverse, ce
|
||||
# qui évite d'ouvrir un port dans le pare-feu.
|
||||
# Usage : scripts/test-remote.sh MACHINE [start|stop]
|
||||
set -eu
|
||||
cd "$(dirname "$(readlink -f "$0")")/.."
|
||||
REMOTE=${1:?Usage : $0 MACHINE [start|stop]}
|
||||
BIN=target/release
|
||||
PORT=7878
|
||||
PIDFILE="${XDG_RUNTIME_DIR:-/tmp}/show-me-test-server.pid"
|
||||
|
||||
stop() {
|
||||
"$BIN/show-me" quit 2>/dev/null || true
|
||||
ssh "$REMOTE" 'show-me-test/show-me quit 2>/dev/null; pkill -x sway 2>/dev/null; true'
|
||||
[ -f "$PIDFILE" ] && kill "$(cat "$PIDFILE")" 2>/dev/null || true
|
||||
rm -f "$PIDFILE"
|
||||
}
|
||||
|
||||
case "${2:-start}" in
|
||||
stop)
|
||||
stop
|
||||
echo "Test arrêté."
|
||||
;;
|
||||
start)
|
||||
ssh "$REMOTE" 'command -v sway >/dev/null' || {
|
||||
echo "sway manque sur $REMOTE : installez-le puis recommencez." >&2
|
||||
exit 1
|
||||
}
|
||||
stop
|
||||
ssh "$REMOTE" 'mkdir -p show-me-test'
|
||||
scp -q "$BIN/show-me" scripts/remote-host.sh "$REMOTE:show-me-test/"
|
||||
"$BIN/show-me-server" --listen 127.0.0.1:$PORT >/dev/null 2>&1 &
|
||||
echo $! > "$PIDFILE"
|
||||
sleep 0.5
|
||||
# Une fenêtre Sway s'ouvre sur l'écran de la machine distante.
|
||||
ssh -f -o ExitOnForwardFailure=yes -R "$PORT:127.0.0.1:$PORT" "$REMOTE" \
|
||||
"sh show-me-test/remote-host.sh ws://127.0.0.1:$PORT >show-me-test/hote.log 2>&1"
|
||||
sleep 2
|
||||
"$BIN/show-me" run --server "ws://127.0.0.1:$PORT" --room test >/dev/null 2>&1 &
|
||||
cat <<MSG
|
||||
Test lancé.
|
||||
Ici : « $BIN/show-me toggle » pour entrer/sortir du mode dessin, puis tracez.
|
||||
Distant : les traits apparaissent dans la fenêtre Sway. Avec le focus dessus :
|
||||
F9 mode dessin, F10 tout effacer, F11 manuel, F12 auto, Échap quitter.
|
||||
Arrêt : scripts/test-remote.sh $REMOTE stop
|
||||
MSG
|
||||
;;
|
||||
*)
|
||||
echo "Usage : $0 MACHINE [start|stop]" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
Loading…
Reference in New Issue