use serde::Serialize;
use std::collections::VecDeque;
use std::io::{BufRead, BufReader};
use std::net::TcpStream;
use std::path::PathBuf;
use std::process::{Child, ChildStdin, Command, ExitStatus, Stdio};
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
use std::time::{Duration, Instant};
use tungstenite::Message;
pub const PROTOCOL: u32 = 1;
pub const READY_PREFIX: &str = "BREP-STREAM-READY ";
#[derive(Debug)]
pub enum Error {
Launch(String),
Connection(String),
Refused { code: String, message: String },
Timeout(String),
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::Launch(m) => write!(f, "launch: {m}"),
Error::Connection(m) => write!(f, "connection: {m}"),
Error::Refused { code, message } => write!(f, "refused ({code}): {message}"),
Error::Timeout(m) => write!(f, "timed out: {m}"),
}
}
}
impl std::error::Error for Error {}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
pub struct Mods {
#[serde(rename = "c")]
pub ctrl: bool,
#[serde(rename = "s")]
pub shift: bool,
#[serde(rename = "a")]
pub alt: bool,
#[serde(rename = "m")]
pub meta: bool,
}
impl Mods {
pub const NONE: Mods = Mods { ctrl: false, shift: false, alt: false, meta: false };
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PointerButton {
Primary,
Secondary,
Middle,
Back,
Forward,
}
impl PointerButton {
fn code(self) -> u8 {
match self {
PointerButton::Primary => 0,
PointerButton::Secondary => 1,
PointerButton::Middle => 2,
PointerButton::Back => 3,
PointerButton::Forward => 4,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WheelUnit {
Pixel,
Line,
Page,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TouchPhase {
Start,
Move,
End,
Cancel,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Input {
PointerMove { x: f32, y: f32 },
Button { x: f32, y: f32, button: PointerButton, down: bool, mods: Mods },
PointerLeave,
Wheel { dx: f32, dy: f32, unit: WheelUnit, mods: Mods },
Key { key: String, down: bool, repeat: bool, mods: Mods },
Text(String),
Paste(String),
ImePreedit(String),
ImeCommit(String),
Touch { id: u64, phase: TouchPhase, x: f32, y: f32, force: Option<f32> },
Focus(bool),
}
impl Input {
fn message(&self) -> serde_json::Value {
use serde_json::json;
match self {
Input::PointerMove { x, y } => json!({"t": "pm", "x": x, "y": y}),
Input::Button { x, y, button, down, mods } => json!({"t": "pb", "x": x, "y": y, "b": button.code(), "down": down, "mods": mods}),
Input::PointerLeave => json!({"t": "leave"}),
Input::Wheel { dx, dy, unit, mods } => {
let mode = match unit {
WheelUnit::Pixel => 0,
WheelUnit::Line => 1,
WheelUnit::Page => 2,
};
json!({"t": "wheel", "dx": dx, "dy": dy, "mode": mode, "mods": mods})
}
Input::Key { key, down, repeat, mods } => json!({"t": "key", "key": key, "code": "", "down": down, "repeat": repeat, "mods": mods}),
Input::Text(s) => json!({"t": "text", "s": s}),
Input::Paste(s) => json!({"t": "paste", "s": s}),
Input::ImePreedit(s) => json!({"t": "ime", "phase": "update", "s": s}),
Input::ImeCommit(s) => json!({"t": "ime", "phase": "commit", "s": s}),
Input::Touch { id, phase, x, y, force } => {
let phase = match phase {
TouchPhase::Start => "start",
TouchPhase::Move => "move",
TouchPhase::End => "end",
TouchPhase::Cancel => "cancel",
};
json!({"t": "touch", "id": id, "phase": phase, "x": x, "y": y, "force": force})
}
Input::Focus(on) => json!({"t": "focus", "on": on}),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Role {
Control,
View,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Rect {
pub x: u32,
pub y: u32,
pub width: u32,
pub height: u32,
}
impl Rect {
fn union(self, o: Rect) -> Rect {
let (x0, y0) = (self.x.min(o.x), self.y.min(o.y));
let x1 = (self.x + self.width).max(o.x + o.width);
let y1 = (self.y + self.height).max(o.y + o.height);
Rect { x: x0, y: y0, width: x1 - x0, height: y1 - y0 }
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Event {
Cursor(String),
Clipboard(String),
OpenUrl { url: String, new_tab: bool },
Role(Role),
ImeArea(Option<[f32; 4]>),
Closed(String),
Other(serde_json::Value),
}
#[derive(Debug, Clone, Default)]
pub struct Frame {
pub width: u32,
pub height: u32,
pub rgba: Vec<u8>,
pub seq: u32,
pub frames: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Update {
pub resized: bool,
pub dirty: Rect,
}
#[derive(Debug, Clone)]
pub struct ConnectOptions {
pub role: Role,
pub width: f32,
pub height: f32,
pub density: f32,
pub timeout: Duration,
}
impl Default for ConnectOptions {
fn default() -> Self {
ConnectOptions { role: Role::Control, width: 1280.0, height: 800.0, density: 1.0, timeout: Duration::from_secs(20) }
}
}
type Waker = Box<dyn Fn() + Send + Sync>;
struct Shared {
frame: Mutex<Frame>,
dirty: Mutex<Option<Update>>,
events: Mutex<VecDeque<Event>>,
role: Mutex<Role>,
closed: Mutex<Option<String>>,
changed: Condvar,
waker: Mutex<Option<Waker>>,
size: Mutex<(f32, f32, f32)>,
}
impl Shared {
fn wake(&self) {
self.changed.notify_all();
if let Some(w) = self.waker.lock().unwrap().as_ref() {
w();
}
}
fn event(&self, e: Event) {
self.events.lock().unwrap().push_back(e);
self.wake();
}
}
pub struct Client {
out: Sender<String>,
shared: Arc<Shared>,
session: String,
dropped: Arc<std::sync::atomic::AtomicBool>,
}
impl Drop for Client {
fn drop(&mut self) {
self.dropped.store(true, std::sync::atomic::Ordering::SeqCst);
}
}
const IO_POLL: Duration = Duration::from_millis(2);
impl Client {
pub fn connect(url: &str, token: &str, options: ConnectOptions) -> Result<Client, Error> {
let url = if url.starts_with("ws://") || url.starts_with("wss://") { url.to_string() } else { format!("ws://{url}/stream/ws") };
if url.starts_with("wss://") {
return Err(Error::Connection("wss:// is not supported; reach a remote session through a tunnel or a proxy that ends TLS".into()));
}
let (mut ws, _) = tungstenite::connect(url.as_str()).map_err(|e| Error::Connection(format!("{url}: {e}")))?;
let tungstenite::stream::MaybeTlsStream::Plain(stream) = ws.get_ref() else {
return Err(Error::Connection("not a plain TCP stream".into()));
};
stream.set_nodelay(true).ok();
stream.set_read_timeout(Some(Duration::from_millis(50))).map_err(|e| Error::Connection(e.to_string()))?;
let role = match options.role {
Role::Control => "control",
Role::View => "view",
};
let hello = serde_json::json!({"t": "hello", "v": PROTOCOL, "token": token, "role": role, "w": options.width, "h": options.height, "dpr": options.density});
ws.send(Message::Text(hello.to_string())).map_err(|e| Error::Connection(e.to_string()))?;
let start = Instant::now();
let welcome: serde_json::Value = loop {
if start.elapsed() > options.timeout {
return Err(Error::Timeout("no welcome from the server".into()));
}
match ws.read() {
Ok(Message::Text(t)) => break serde_json::from_str(&t).map_err(|e| Error::Connection(e.to_string()))?,
Ok(Message::Close(_)) => return Err(Error::Connection("the server closed the connection".into())),
Ok(_) => {}
Err(tungstenite::Error::Io(e)) if would_block(&e) => {}
Err(e) => return Err(Error::Connection(e.to_string())),
}
};
if welcome["t"] == "error" {
return Err(Error::Refused { code: welcome["code"].as_str().unwrap_or("").into(), message: welcome["msg"].as_str().unwrap_or("").into() });
}
if welcome["t"] != "welcome" {
return Err(Error::Connection(format!("expected a welcome, got {welcome}")));
}
if let tungstenite::stream::MaybeTlsStream::Plain(stream) = ws.get_ref() {
stream.set_read_timeout(Some(IO_POLL)).map_err(|e| Error::Connection(e.to_string()))?;
}
let role = if welcome["role"] == "control" { Role::Control } else { Role::View };
let shared = Arc::new(Shared {
frame: Mutex::new(Frame::default()),
dirty: Mutex::new(None),
events: Mutex::new(VecDeque::new()),
role: Mutex::new(role),
closed: Mutex::new(None),
changed: Condvar::new(),
waker: Mutex::new(None),
size: Mutex::new((options.width, options.height, options.density)),
});
let (out_tx, out_rx) = mpsc::channel::<String>();
let (frame_tx, frame_rx) = mpsc::channel::<Vec<u8>>();
{
let shared = shared.clone();
let out = out_tx.clone();
std::thread::Builder::new()
.name("brep-stream-decode".into())
.spawn(move || decode_loop(frame_rx, &shared, &out))
.map_err(|e| Error::Connection(e.to_string()))?;
}
let dropped = Arc::new(std::sync::atomic::AtomicBool::new(false));
{
let (shared, dropped) = (shared.clone(), dropped.clone());
std::thread::Builder::new()
.name("brep-stream-io".into())
.spawn(move || io_loop(ws, out_rx, frame_tx, &shared, &dropped))
.map_err(|e| Error::Connection(e.to_string()))?;
}
Ok(Client { out: out_tx, shared, session: welcome["session"].as_str().unwrap_or("").to_string(), dropped })
}
pub fn session_id(&self) -> &str {
&self.session
}
pub fn send(&self, input: Input) {
let _ = self.out.send(input.message().to_string());
}
pub fn resize(&self, width: f32, height: f32, density: f32) {
*self.shared.size.lock().unwrap() = (width, height, density);
let _ = self.out.send(serde_json::json!({"t": "resize", "w": width, "h": height, "dpr": density}).to_string());
}
pub fn take_control(&self) {
let _ = self.out.send(serde_json::json!({"t": "take_control"}).to_string());
}
pub fn set_quality(&self, jpeg: u8) {
let _ = self.out.send(serde_json::json!({"t": "quality", "jpeg": jpeg}).to_string());
}
pub fn role(&self) -> Role {
*self.shared.role.lock().unwrap()
}
pub fn closed(&self) -> Option<String> {
self.shared.closed.lock().unwrap().clone()
}
pub fn set_waker(&self, waker: impl Fn() + Send + Sync + 'static) {
*self.shared.waker.lock().unwrap() = Some(Box::new(waker));
}
pub fn frame(&self) -> MutexGuard<'_, Frame> {
self.shared.frame.lock().unwrap()
}
pub fn take_update(&self) -> Option<Update> {
self.shared.dirty.lock().unwrap().take()
}
pub fn poll_events(&self) -> Vec<Event> {
self.shared.events.lock().unwrap().drain(..).collect()
}
pub fn wait_frame(&self, timeout: Duration) -> Result<(), Error> {
let start = Instant::now();
let mut frame = self.shared.frame.lock().unwrap();
let seen = frame.frames;
while frame.frames == seen {
if let Some(why) = self.closed() {
return Err(Error::Connection(why));
}
let left = timeout.checked_sub(start.elapsed()).ok_or_else(|| Error::Timeout("no frame".into()))?;
frame = self.shared.changed.wait_timeout(frame, left.min(Duration::from_millis(200))).unwrap().0;
}
Ok(())
}
pub fn wait_still(&self, quiet: Duration, timeout: Duration) -> Result<(), Error> {
let start = Instant::now();
loop {
let frames = self.frame().frames;
std::thread::sleep(quiet);
if self.frame().frames == frames && frames > 0 {
return Ok(());
}
if let Some(why) = self.closed() {
return Err(Error::Connection(why));
}
if start.elapsed() > timeout {
return Err(Error::Timeout("the picture never went still".into()));
}
}
}
}
fn would_block(e: &std::io::Error) -> bool {
matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut)
}
fn io_loop(
mut ws: tungstenite::WebSocket<tungstenite::stream::MaybeTlsStream<TcpStream>>,
out: Receiver<String>,
frames: Sender<Vec<u8>>,
shared: &Shared,
dropped: &std::sync::atomic::AtomicBool,
) {
let why = loop {
if dropped.load(std::sync::atomic::Ordering::SeqCst) {
let _ = ws.close(None);
let _ = ws.flush();
return;
}
let mut gone = false;
loop {
match out.try_recv() {
Ok(text) => {
if ws.write(Message::Text(text)).is_err() {
gone = true;
break;
}
}
Err(mpsc::TryRecvError::Empty) => break,
Err(mpsc::TryRecvError::Disconnected) => {
let _ = ws.close(None);
let _ = ws.flush();
return;
}
}
}
if gone || ws.flush().is_err() {
break "the connection broke".to_string();
}
match ws.read() {
Ok(Message::Binary(m)) => {
if frames.send(m).is_err() {
break "closed".to_string();
}
}
Ok(Message::Text(t)) => {
if let Ok(v) = serde_json::from_str::<serde_json::Value>(&t) {
if v["t"] == "role" && v["role"] == "control" {
let (w, h, dpr) = *shared.size.lock().unwrap();
let _ = ws.write(Message::Text(serde_json::json!({"t": "resize", "w": w, "h": h, "dpr": dpr}).to_string()));
}
control(&v, shared);
}
}
Ok(Message::Close(frame)) => break frame.map(|f| f.reason.to_string()).filter(|r| !r.is_empty()).unwrap_or_else(|| "the server closed the session".into()),
Ok(_) => {}
Err(tungstenite::Error::Io(e)) if would_block(&e) => {}
Err(e) => break e.to_string(),
}
};
*shared.closed.lock().unwrap() = Some(why.clone());
shared.event(Event::Closed(why));
}
fn control(v: &serde_json::Value, shared: &Shared) {
let s = |k: &str| v[k].as_str().unwrap_or("").to_string();
let event = match v["t"].as_str().unwrap_or("") {
"cursor" => Event::Cursor(s("css")),
"clipboard" => Event::Clipboard(s("s")),
"open_url" => Event::OpenUrl { url: s("url"), new_tab: v["new_tab"].as_bool().unwrap_or(true) },
"role" => {
let role = if v["role"] == "control" { Role::Control } else { Role::View };
*shared.role.lock().unwrap() = role;
Event::Role(role)
}
"ime_area" => {
let f = |k: &str| v[k].as_f64().map(|x| x as f32);
Event::ImeArea(match (f("x"), f("y"), f("w"), f("h")) {
(Some(x), Some(y), Some(w), Some(h)) => Some([x, y, w, h]),
_ => None,
})
}
_ => Event::Other(v.clone()),
};
shared.event(event);
}
fn decode_loop(frames: Receiver<Vec<u8>>, shared: &Shared, out: &Sender<String>) {
while let Ok(m) = frames.recv() {
match apply(&m, shared) {
Ok(seq) => {
let _ = out.send(serde_json::json!({"t": "ack", "seq": seq}).to_string());
shared.wake();
}
Err(e) => shared.event(Event::Other(serde_json::json!({"t": "decode_error", "msg": e}))),
}
}
}
fn apply(m: &[u8], shared: &Shared) -> Result<u32, String> {
let u16_at = |o: usize| -> Result<u32, String> { m.get(o..o + 2).map(|b| u16::from_le_bytes([b[0], b[1]]) as u32).ok_or("short frame".to_string()) };
if m.len() < 12 || m[0] != 1 {
return Err("not a frame".into());
}
let n = u16_at(2)? as usize;
let seq = u32::from_le_bytes([m[4], m[5], m[6], m[7]]);
let (w, h) = (u16_at(8)?, u16_at(10)?);
let mut tiles = Vec::with_capacity(n);
let mut off = 12;
for _ in 0..n {
let (x, y, tw, th) = (u16_at(off)?, u16_at(off + 2)?, u16_at(off + 4)?, u16_at(off + 6)?);
let codec = *m.get(off + 8).ok_or("short frame")?;
let len = m.get(off + 10..off + 14).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize).ok_or("short frame")?;
off += 14;
let bytes = m.get(off..off + len).ok_or("short frame")?;
off += len;
let format = if codec == 2 { image::ImageFormat::Jpeg } else { image::ImageFormat::Png };
let tile = image::load_from_memory_with_format(bytes, format).map_err(|e| e.to_string())?.to_rgba8();
if (tile.width(), tile.height()) != (tw, th) || x + tw > w || y + th > h {
return Err("a tile does not fit the frame".into());
}
tiles.push((x, y, tile));
}
let mut frame = shared.frame.lock().unwrap();
let resized = (frame.width, frame.height) != (w, h);
if resized {
*frame = Frame { width: w, height: h, rgba: vec![0; (w * h * 4) as usize], seq: frame.seq, frames: frame.frames };
}
let mut dirty: Option<Rect> = None;
for (x, y, tile) in &tiles {
let (tw, th) = (tile.width(), tile.height());
for row in 0..th {
let dst = (((y + row) * w + x) * 4) as usize;
let src = (row * tw * 4) as usize;
frame.rgba[dst..dst + (tw * 4) as usize].copy_from_slice(&tile.as_raw()[src..src + (tw * 4) as usize]);
}
let r = Rect { x: *x, y: *y, width: tw, height: th };
dirty = Some(dirty.map_or(r, |d| d.union(r)));
}
frame.seq = seq;
frame.frames += 1;
drop(frame);
let mut held = shared.dirty.lock().unwrap();
let full = Rect { x: 0, y: 0, width: w, height: h };
*held = match (*held, resized, dirty) {
(_, true, _) => Some(Update { resized: true, dirty: full }),
(Some(u), false, Some(d)) => Some(Update { resized: u.resized, dirty: if u.resized { full } else { u.dirty.union(d) } }),
(None, false, Some(d)) => Some(Update { resized: false, dirty: d }),
(held, false, None) => held,
};
Ok(seq)
}
pub struct Launcher {
command: Command,
options: ConnectOptions,
ready_timeout: Duration,
}
impl Launcher {
pub fn new(program: impl AsRef<std::ffi::OsStr>) -> Launcher {
Launcher::from_command(Command::new(program))
}
pub fn from_command(command: Command) -> Launcher {
Launcher { command, options: ConnectOptions::default(), ready_timeout: Duration::from_secs(120) }
}
pub fn size(mut self, width: f32, height: f32, density: f32) -> Launcher {
(self.options.width, self.options.height, self.options.density) = (width, height, density);
self
}
pub fn ready_timeout(mut self, timeout: Duration) -> Launcher {
self.ready_timeout = timeout;
self
}
pub fn launch(mut self) -> Result<Session, Error> {
let token_file = std::env::temp_dir().join(format!(
"brep-stream-{}-{}.token",
std::process::id(),
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0)
));
self.command
.args(["--stream", "127.0.0.1:0", "--stream-until-stdin-closes", "--stream-token-file"])
.arg(&token_file)
.stdin(Stdio::piped())
.stdout(Stdio::piped());
let mut child = self.command.spawn().map_err(|e| Error::Launch(format!("{:?}: {e}", self.command.get_program())))?;
let stdin = child.stdin.take();
let stdout = child.stdout.take().ok_or_else(|| Error::Launch("no stdout".into()))?;
let (ready_tx, ready_rx) = mpsc::channel::<Result<serde_json::Value, String>>();
std::thread::Builder::new()
.name("brep-stream-stdout".into())
.spawn(move || {
let mut ready = Some(ready_tx);
for line in BufReader::new(stdout).lines() {
let Ok(line) = line else { break };
if let (Some(rest), Some(tx)) = (line.strip_prefix(READY_PREFIX), ready.as_ref()) {
let _ = tx.send(serde_json::from_str(rest).map_err(|e| e.to_string()));
ready = None;
}
}
if let Some(tx) = ready {
let _ = tx.send(Err("the app ended before it was ready".into()));
}
})
.map_err(|e| Error::Launch(e.to_string()))?;
let mut session = Session { child: Some(child), stdin, client: None, token_file: token_file.clone(), url: String::new(), token: String::new() };
let ready = match ready_rx.recv_timeout(self.ready_timeout) {
Ok(Ok(ready)) => ready,
Ok(Err(why)) => return Err(Error::Launch(format!("{why} ({})", session.exit_note()))),
Err(RecvTimeoutError::Timeout) => return Err(Error::Timeout(format!("the app was not ready in {} s", self.ready_timeout.as_secs()))),
Err(RecvTimeoutError::Disconnected) => return Err(Error::Launch("the app's output closed".into())),
};
let ws = ready["ws"].as_str().ok_or_else(|| Error::Launch(format!("a ready line without `ws`: {ready}")))?.to_string();
let token = std::fs::read_to_string(&token_file).map_err(|e| Error::Launch(format!("token file {}: {e}", token_file.display())))?;
let _ = std::fs::remove_file(&token_file);
session.client = Some(Client::connect(&ws, token.trim(), self.options)?);
(session.url, session.token) = (ws, token.trim().to_string());
Ok(session)
}
}
pub struct Session {
child: Option<Child>,
stdin: Option<ChildStdin>,
client: Option<Client>,
token_file: PathBuf,
url: String,
token: String,
}
impl Session {
pub fn url(&self) -> &str {
&self.url
}
pub fn token(&self) -> &str {
&self.token
}
pub fn pid(&self) -> Option<u32> {
self.child.as_ref().map(Child::id)
}
pub fn shutdown(mut self, timeout: Duration) -> std::io::Result<ExitStatus> {
self.end(timeout)
}
fn end(&mut self, timeout: Duration) -> std::io::Result<ExitStatus> {
self.client = None;
drop(self.stdin.take());
let Some(mut child) = self.child.take() else {
return Err(std::io::Error::other("already ended"));
};
let start = Instant::now();
loop {
if let Some(status) = child.try_wait()? {
return Ok(status);
}
if start.elapsed() > timeout {
child.kill()?;
return child.wait();
}
std::thread::sleep(Duration::from_millis(20));
}
}
fn exit_note(&mut self) -> String {
match self.child.as_mut().map(Child::try_wait) {
Some(Ok(Some(status))) => format!("it exited: {status}"),
_ => "it is still running".into(),
}
}
}
impl std::ops::Deref for Session {
type Target = Client;
fn deref(&self) -> &Client {
self.client.as_ref().expect("a launched session is connected")
}
}
impl Drop for Session {
fn drop(&mut self) {
let _ = self.end(Duration::from_secs(15));
let _ = std::fs::remove_file(&self.token_file);
}
}