Skip to main content

brep_stream_client/
lib.rs

1//! Embed the next.BREP.io CAD application in a Rust program.
2//!
3//! `brep-app --stream` runs the CAD application with no window and no display
4//! and serves its whole user interface over a WebSocket: every frame it draws,
5//! as tiles, and every input it should take. This crate is the native end of
6//! that connection, so a Rust program can show the CAD session inside its own
7//! window (any toolkit: it hands you RGBA pixels) and drive it, with no browser.
8//!
9//! ```no_run
10//! use brep_stream_client::{Input, Launcher, Mods, PointerButton};
11//! # fn main() -> Result<(), brep_stream_client::Error> {
12//! // Start the app (it must be installed: `cargo install BREP_app`, or the
13//! // desktop download) at 1280 x 800 logical pixels, density 1.
14//! let session = Launcher::new("brep-app").size(1280.0, 800.0, 1.0).launch()?;
15//! session.wait_frame(std::time::Duration::from_secs(120))?;
16//! {
17//!     let frame = session.frame();
18//!     println!("{} x {} pixels", frame.width, frame.height);
19//! }
20//! // Click the File menu.
21//! session.send(Input::Button { x: 148.0, y: 19.0, button: PointerButton::Primary, down: true, mods: Mods::NONE });
22//! session.send(Input::Button { x: 148.0, y: 19.0, button: PointerButton::Primary, down: false, mods: Mods::NONE });
23//! # Ok(()) }
24//! ```
25//!
26//! Coordinates are logical pixels (egui points, CSS pixels) from the top-left
27//! of the session; frames are physical pixels, `density` times as many.
28//! [`Launcher`] starts `brep-app` as a child process that ends when the
29//! [`Session`] is dropped; [`Client::connect`] attaches to one already running
30//! (`brep-app --stream ADDR`), given its address and session token.
31//!
32//! The protocol is version 1 of the stream. Plain `ws://` only: put TLS
33//! in front of a remote session with a reverse proxy, or reach it over
34//! an SSH tunnel.
35use serde::Serialize;
36use std::collections::VecDeque;
37use std::io::{BufRead, BufReader};
38use std::net::TcpStream;
39use std::path::PathBuf;
40use std::process::{Child, ChildStdin, Command, ExitStatus, Stdio};
41use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
42use std::sync::{Arc, Condvar, Mutex, MutexGuard};
43use std::time::{Duration, Instant};
44use tungstenite::Message;
45
46/// The stream protocol version this crate speaks.
47pub const PROTOCOL: u32 = 1;
48/// The line `brep-app --stream` prints when the session accepts connections.
49pub const READY_PREFIX: &str = "BREP-STREAM-READY ";
50
51/// What went wrong.
52#[derive(Debug)]
53pub enum Error {
54    /// Starting the app, or reading what it printed.
55    Launch(String),
56    /// The connection: refused, closed, or not a stream server.
57    Connection(String),
58    /// The server refused the session (`auth`: wrong token; `version`).
59    Refused { code: String, message: String },
60    /// Nothing arrived in time.
61    Timeout(String),
62}
63
64impl std::fmt::Display for Error {
65    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66        match self {
67            Error::Launch(m) => write!(f, "launch: {m}"),
68            Error::Connection(m) => write!(f, "connection: {m}"),
69            Error::Refused { code, message } => write!(f, "refused ({code}): {message}"),
70            Error::Timeout(m) => write!(f, "timed out: {m}"),
71        }
72    }
73}
74
75impl std::error::Error for Error {}
76
77/// Modifier keys held with an input. `meta` is Cmd on a Mac keyboard; the
78/// session treats it, like Ctrl, as the command key.
79#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
80pub struct Mods {
81    #[serde(rename = "c")]
82    pub ctrl: bool,
83    #[serde(rename = "s")]
84    pub shift: bool,
85    #[serde(rename = "a")]
86    pub alt: bool,
87    #[serde(rename = "m")]
88    pub meta: bool,
89}
90
91impl Mods {
92    pub const NONE: Mods = Mods { ctrl: false, shift: false, alt: false, meta: false };
93}
94
95#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96pub enum PointerButton {
97    Primary,
98    Secondary,
99    Middle,
100    Back,
101    Forward,
102}
103
104impl PointerButton {
105    fn code(self) -> u8 {
106        match self {
107            PointerButton::Primary => 0,
108            PointerButton::Secondary => 1,
109            PointerButton::Middle => 2,
110            PointerButton::Back => 3,
111            PointerButton::Forward => 4,
112        }
113    }
114}
115
116/// What a wheel delta counts.
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118pub enum WheelUnit {
119    Pixel,
120    Line,
121    Page,
122}
123
124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125pub enum TouchPhase {
126    Start,
127    Move,
128    End,
129    Cancel,
130}
131
132/// One input for the session. Positions are logical pixels from the session's
133/// top-left corner.
134#[derive(Debug, Clone, PartialEq)]
135pub enum Input {
136    PointerMove { x: f32, y: f32 },
137    Button { x: f32, y: f32, button: PointerButton, down: bool, mods: Mods },
138    /// The pointer left the session's area.
139    PointerLeave,
140    /// A wheel turn, as a browser reports it: positive `dy` scrolls the page
141    /// down (moves the content up).
142    Wheel { dx: f32, dy: f32, unit: WheelUnit, mods: Mods },
143    /// A key, named as egui or a browser's `KeyboardEvent.key` names it:
144    /// `"A"`, `"Enter"`, `"Escape"`, `"ArrowUp"`, `"F2"`, `"Delete"`.
145    /// Ctrl/Cmd + C and X copy and cut (the copied text arrives as
146    /// [`Event::Clipboard`]); paste with [`Input::Paste`].
147    Key { key: String, down: bool, repeat: bool, mods: Mods },
148    /// Typed text (what a key press types, or an input method's result).
149    Text(String),
150    /// Paste this text where the session's keyboard focus is.
151    Paste(String),
152    /// An input method's composition in progress (empty: dismissed).
153    ImePreedit(String),
154    /// An input method's final text.
155    ImeCommit(String),
156    Touch { id: u64, phase: TouchPhase, x: f32, y: f32, force: Option<f32> },
157    /// The host window gained or lost keyboard focus.
158    Focus(bool),
159}
160
161impl Input {
162    fn message(&self) -> serde_json::Value {
163        use serde_json::json;
164        match self {
165            Input::PointerMove { x, y } => json!({"t": "pm", "x": x, "y": y}),
166            Input::Button { x, y, button, down, mods } => json!({"t": "pb", "x": x, "y": y, "b": button.code(), "down": down, "mods": mods}),
167            Input::PointerLeave => json!({"t": "leave"}),
168            Input::Wheel { dx, dy, unit, mods } => {
169                let mode = match unit {
170                    WheelUnit::Pixel => 0,
171                    WheelUnit::Line => 1,
172                    WheelUnit::Page => 2,
173                };
174                json!({"t": "wheel", "dx": dx, "dy": dy, "mode": mode, "mods": mods})
175            }
176            Input::Key { key, down, repeat, mods } => json!({"t": "key", "key": key, "code": "", "down": down, "repeat": repeat, "mods": mods}),
177            Input::Text(s) => json!({"t": "text", "s": s}),
178            Input::Paste(s) => json!({"t": "paste", "s": s}),
179            Input::ImePreedit(s) => json!({"t": "ime", "phase": "update", "s": s}),
180            Input::ImeCommit(s) => json!({"t": "ime", "phase": "commit", "s": s}),
181            Input::Touch { id, phase, x, y, force } => {
182                let phase = match phase {
183                    TouchPhase::Start => "start",
184                    TouchPhase::Move => "move",
185                    TouchPhase::End => "end",
186                    TouchPhase::Cancel => "cancel",
187                };
188                json!({"t": "touch", "id": id, "phase": phase, "x": x, "y": y, "force": force})
189            }
190            Input::Focus(on) => json!({"t": "focus", "on": on}),
191        }
192    }
193}
194
195/// This client's part in the session: one client controls it (its input and
196/// size apply); the others watch.
197#[derive(Debug, Clone, Copy, PartialEq, Eq)]
198pub enum Role {
199    Control,
200    View,
201}
202
203/// A pixel rectangle `x, y, width, height`.
204#[derive(Debug, Clone, Copy, PartialEq, Eq)]
205pub struct Rect {
206    pub x: u32,
207    pub y: u32,
208    pub width: u32,
209    pub height: u32,
210}
211
212impl Rect {
213    fn union(self, o: Rect) -> Rect {
214        let (x0, y0) = (self.x.min(o.x), self.y.min(o.y));
215        let x1 = (self.x + self.width).max(o.x + o.width);
216        let y1 = (self.y + self.height).max(o.y + o.height);
217        Rect { x: x0, y: y0, width: x1 - x0, height: y1 - y0 }
218    }
219}
220
221/// Something the session told this client.
222#[derive(Debug, Clone, PartialEq)]
223pub enum Event {
224    /// The pointer's cursor over the session, as a CSS cursor name
225    /// (`default`, `pointer`, `text`, `grab`, `ew-resize`, ...).
226    Cursor(String),
227    /// Text the session copied: put it on the host's clipboard.
228    Clipboard(String),
229    /// The session asked to open a link.
230    OpenUrl { url: String, new_tab: bool },
231    /// This client's role changed.
232    Role(Role),
233    /// Where a text cursor is (logical pixels), for placing an input method's
234    /// window; `None` when no text field has focus.
235    ImeArea(Option<[f32; 4]>),
236    /// The connection ended.
237    Closed(String),
238    /// Any other message, as sent.
239    Other(serde_json::Value),
240}
241
242/// The session's picture as this client holds it.
243#[derive(Debug, Clone, Default)]
244pub struct Frame {
245    /// Physical pixels.
246    pub width: u32,
247    pub height: u32,
248    /// Straight RGBA, row-major, `width * height * 4` bytes.
249    pub rgba: Vec<u8>,
250    /// The server's sequence number of the last frame applied.
251    pub seq: u32,
252    /// How many frames have been applied.
253    pub frames: u64,
254}
255
256/// What changed since the last [`Client::take_update`].
257#[derive(Debug, Clone, Copy, PartialEq, Eq)]
258pub struct Update {
259    /// The size changed (re-create a texture rather than patch it).
260    pub resized: bool,
261    /// The changed area (all of it after a resize).
262    pub dirty: Rect,
263}
264
265/// How [`Client::connect`] introduces itself.
266#[derive(Debug, Clone)]
267pub struct ConnectOptions {
268    pub role: Role,
269    /// The session's size in logical pixels, and the density (physical pixels
270    /// per logical pixel). Only a controlling client's size applies.
271    pub width: f32,
272    pub height: f32,
273    pub density: f32,
274    /// How long to wait for the server's welcome.
275    pub timeout: Duration,
276}
277
278impl Default for ConnectOptions {
279    fn default() -> Self {
280        ConnectOptions { role: Role::Control, width: 1280.0, height: 800.0, density: 1.0, timeout: Duration::from_secs(20) }
281    }
282}
283
284type Waker = Box<dyn Fn() + Send + Sync>;
285
286struct Shared {
287    frame: Mutex<Frame>,
288    dirty: Mutex<Option<Update>>,
289    events: Mutex<VecDeque<Event>>,
290    role: Mutex<Role>,
291    closed: Mutex<Option<String>>,
292    changed: Condvar,
293    waker: Mutex<Option<Waker>>,
294    /// The size last asked for (logical width, height, density): sent again
295    /// when this client becomes the controller.
296    size: Mutex<(f32, f32, f32)>,
297}
298
299impl Shared {
300    fn wake(&self) {
301        self.changed.notify_all();
302        if let Some(w) = self.waker.lock().unwrap().as_ref() {
303            w();
304        }
305    }
306
307    fn event(&self, e: Event) {
308        self.events.lock().unwrap().push_back(e);
309        self.wake();
310    }
311}
312
313/// A connection to a streamed session. Cheap to share by reference; every
314/// method takes `&self`. Its threads end when it is dropped.
315pub struct Client {
316    out: Sender<String>,
317    shared: Arc<Shared>,
318    session: String,
319    /// Set when the client is dropped: the connection's thread closes it.
320    /// (The decode thread holds a sender of its own for acks, so the channel
321    /// alone never says the client is gone.)
322    dropped: Arc<std::sync::atomic::AtomicBool>,
323}
324
325impl Drop for Client {
326    fn drop(&mut self) {
327        self.dropped.store(true, std::sync::atomic::Ordering::SeqCst);
328    }
329}
330
331/// How often the connection's thread looks for input to send while it waits
332/// for the server: the most an input waits before it leaves.
333const IO_POLL: Duration = Duration::from_millis(2);
334
335impl Client {
336    /// Connect to a running `brep-app --stream`: `url` is its WebSocket
337    /// (`ws://127.0.0.1:8770/stream/ws`) or its address (`127.0.0.1:8770`),
338    /// `token` the session token from its token file.
339    pub fn connect(url: &str, token: &str, options: ConnectOptions) -> Result<Client, Error> {
340        let url = if url.starts_with("ws://") || url.starts_with("wss://") { url.to_string() } else { format!("ws://{url}/stream/ws") };
341        if url.starts_with("wss://") {
342            return Err(Error::Connection("wss:// is not supported; reach a remote session through a tunnel or a proxy that ends TLS".into()));
343        }
344        let (mut ws, _) = tungstenite::connect(url.as_str()).map_err(|e| Error::Connection(format!("{url}: {e}")))?;
345        let tungstenite::stream::MaybeTlsStream::Plain(stream) = ws.get_ref() else {
346            return Err(Error::Connection("not a plain TCP stream".into()));
347        };
348        stream.set_nodelay(true).ok();
349        stream.set_read_timeout(Some(Duration::from_millis(50))).map_err(|e| Error::Connection(e.to_string()))?;
350        let role = match options.role {
351            Role::Control => "control",
352            Role::View => "view",
353        };
354        let hello = serde_json::json!({"t": "hello", "v": PROTOCOL, "token": token, "role": role, "w": options.width, "h": options.height, "dpr": options.density});
355        ws.send(Message::Text(hello.to_string())).map_err(|e| Error::Connection(e.to_string()))?;
356        let start = Instant::now();
357        let welcome: serde_json::Value = loop {
358            if start.elapsed() > options.timeout {
359                return Err(Error::Timeout("no welcome from the server".into()));
360            }
361            match ws.read() {
362                Ok(Message::Text(t)) => break serde_json::from_str(&t).map_err(|e| Error::Connection(e.to_string()))?,
363                Ok(Message::Close(_)) => return Err(Error::Connection("the server closed the connection".into())),
364                Ok(_) => {}
365                Err(tungstenite::Error::Io(e)) if would_block(&e) => {}
366                Err(e) => return Err(Error::Connection(e.to_string())),
367            }
368        };
369        if welcome["t"] == "error" {
370            return Err(Error::Refused { code: welcome["code"].as_str().unwrap_or("").into(), message: welcome["msg"].as_str().unwrap_or("").into() });
371        }
372        if welcome["t"] != "welcome" {
373            return Err(Error::Connection(format!("expected a welcome, got {welcome}")));
374        }
375        if let tungstenite::stream::MaybeTlsStream::Plain(stream) = ws.get_ref() {
376            stream.set_read_timeout(Some(IO_POLL)).map_err(|e| Error::Connection(e.to_string()))?;
377        }
378        let role = if welcome["role"] == "control" { Role::Control } else { Role::View };
379        let shared = Arc::new(Shared {
380            frame: Mutex::new(Frame::default()),
381            dirty: Mutex::new(None),
382            events: Mutex::new(VecDeque::new()),
383            role: Mutex::new(role),
384            closed: Mutex::new(None),
385            changed: Condvar::new(),
386            waker: Mutex::new(None),
387            size: Mutex::new((options.width, options.height, options.density)),
388        });
389        let (out_tx, out_rx) = mpsc::channel::<String>();
390        let (frame_tx, frame_rx) = mpsc::channel::<Vec<u8>>();
391        // Frames decode on their own thread, so a large keyframe never holds
392        // the input waiting behind it.
393        {
394            let shared = shared.clone();
395            let out = out_tx.clone();
396            std::thread::Builder::new()
397                .name("brep-stream-decode".into())
398                .spawn(move || decode_loop(frame_rx, &shared, &out))
399                .map_err(|e| Error::Connection(e.to_string()))?;
400        }
401        let dropped = Arc::new(std::sync::atomic::AtomicBool::new(false));
402        {
403            let (shared, dropped) = (shared.clone(), dropped.clone());
404            std::thread::Builder::new()
405                .name("brep-stream-io".into())
406                .spawn(move || io_loop(ws, out_rx, frame_tx, &shared, &dropped))
407                .map_err(|e| Error::Connection(e.to_string()))?;
408        }
409        Ok(Client { out: out_tx, shared, session: welcome["session"].as_str().unwrap_or("").to_string(), dropped })
410    }
411
412    /// The server's session id.
413    pub fn session_id(&self) -> &str {
414        &self.session
415    }
416
417    /// Send one input. Applies only while this client controls the session.
418    pub fn send(&self, input: Input) {
419        let _ = self.out.send(input.message().to_string());
420    }
421
422    /// Ask for the session at this size (logical pixels) and density. The
423    /// next frames arrive at `width * density` by `height * density` pixels.
424    pub fn resize(&self, width: f32, height: f32, density: f32) {
425        *self.shared.size.lock().unwrap() = (width, height, density);
426        let _ = self.out.send(serde_json::json!({"t": "resize", "w": width, "h": height, "dpr": density}).to_string());
427    }
428
429    /// Become the controlling client (the current one becomes a viewer).
430    pub fn take_control(&self) {
431        let _ = self.out.send(serde_json::json!({"t": "take_control"}).to_string());
432    }
433
434    /// JPEG quality (10-95) of the 3D view's tiles while it moves.
435    pub fn set_quality(&self, jpeg: u8) {
436        let _ = self.out.send(serde_json::json!({"t": "quality", "jpeg": jpeg}).to_string());
437    }
438
439    pub fn role(&self) -> Role {
440        *self.shared.role.lock().unwrap()
441    }
442
443    /// Why the connection ended, once it has.
444    pub fn closed(&self) -> Option<String> {
445        self.shared.closed.lock().unwrap().clone()
446    }
447
448    /// Called (on the connection's threads) whenever a frame or an event
449    /// arrives: a GUI host asks itself to repaint here.
450    pub fn set_waker(&self, waker: impl Fn() + Send + Sync + 'static) {
451        *self.shared.waker.lock().unwrap() = Some(Box::new(waker));
452    }
453
454    /// The current picture. Hold the guard briefly: frames wait for it.
455    pub fn frame(&self) -> MutexGuard<'_, Frame> {
456        self.shared.frame.lock().unwrap()
457    }
458
459    /// What changed since the last call (`None`: nothing).
460    pub fn take_update(&self) -> Option<Update> {
461        self.shared.dirty.lock().unwrap().take()
462    }
463
464    /// The events that arrived since the last call.
465    pub fn poll_events(&self) -> Vec<Event> {
466        self.shared.events.lock().unwrap().drain(..).collect()
467    }
468
469    /// Wait until a frame newer than the one held now arrives.
470    pub fn wait_frame(&self, timeout: Duration) -> Result<(), Error> {
471        let start = Instant::now();
472        let mut frame = self.shared.frame.lock().unwrap();
473        let seen = frame.frames;
474        while frame.frames == seen {
475            if let Some(why) = self.closed() {
476                return Err(Error::Connection(why));
477            }
478            let left = timeout.checked_sub(start.elapsed()).ok_or_else(|| Error::Timeout("no frame".into()))?;
479            frame = self.shared.changed.wait_timeout(frame, left.min(Duration::from_millis(200))).unwrap().0;
480        }
481        Ok(())
482    }
483
484    /// Wait until no frame has arrived for `quiet` (the picture is still), or
485    /// fail after `timeout`.
486    pub fn wait_still(&self, quiet: Duration, timeout: Duration) -> Result<(), Error> {
487        let start = Instant::now();
488        loop {
489            let frames = self.frame().frames;
490            std::thread::sleep(quiet);
491            if self.frame().frames == frames && frames > 0 {
492                return Ok(());
493            }
494            if let Some(why) = self.closed() {
495                return Err(Error::Connection(why));
496            }
497            if start.elapsed() > timeout {
498                return Err(Error::Timeout("the picture never went still".into()));
499            }
500        }
501    }
502}
503
504fn would_block(e: &std::io::Error) -> bool {
505    matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut)
506}
507
508fn io_loop(
509    mut ws: tungstenite::WebSocket<tungstenite::stream::MaybeTlsStream<TcpStream>>,
510    out: Receiver<String>,
511    frames: Sender<Vec<u8>>,
512    shared: &Shared,
513    dropped: &std::sync::atomic::AtomicBool,
514) {
515    let why = loop {
516        if dropped.load(std::sync::atomic::Ordering::SeqCst) {
517            // The client was dropped: close, so the session frees its place
518            // (a dropped controller would otherwise keep control).
519            let _ = ws.close(None);
520            let _ = ws.flush();
521            return;
522        }
523        // Everything queued goes first: input never waits for a frame.
524        let mut gone = false;
525        loop {
526            match out.try_recv() {
527                Ok(text) => {
528                    if ws.write(Message::Text(text)).is_err() {
529                        gone = true;
530                        break;
531                    }
532                }
533                Err(mpsc::TryRecvError::Empty) => break,
534                // The client was dropped.
535                Err(mpsc::TryRecvError::Disconnected) => {
536                    let _ = ws.close(None);
537                    let _ = ws.flush();
538                    return;
539                }
540            }
541        }
542        if gone || ws.flush().is_err() {
543            break "the connection broke".to_string();
544        }
545        match ws.read() {
546            Ok(Message::Binary(m)) => {
547                if frames.send(m).is_err() {
548                    break "closed".to_string();
549                }
550            }
551            Ok(Message::Text(t)) => {
552                if let Ok(v) = serde_json::from_str::<serde_json::Value>(&t) {
553                    if v["t"] == "role" && v["role"] == "control" {
554                        // Control came to this client: its size applies now.
555                        let (w, h, dpr) = *shared.size.lock().unwrap();
556                        let _ = ws.write(Message::Text(serde_json::json!({"t": "resize", "w": w, "h": h, "dpr": dpr}).to_string()));
557                    }
558                    control(&v, shared);
559                }
560            }
561            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()),
562            Ok(_) => {}
563            Err(tungstenite::Error::Io(e)) if would_block(&e) => {}
564            Err(e) => break e.to_string(),
565        }
566    };
567    *shared.closed.lock().unwrap() = Some(why.clone());
568    shared.event(Event::Closed(why));
569}
570
571fn control(v: &serde_json::Value, shared: &Shared) {
572    let s = |k: &str| v[k].as_str().unwrap_or("").to_string();
573    let event = match v["t"].as_str().unwrap_or("") {
574        "cursor" => Event::Cursor(s("css")),
575        "clipboard" => Event::Clipboard(s("s")),
576        "open_url" => Event::OpenUrl { url: s("url"), new_tab: v["new_tab"].as_bool().unwrap_or(true) },
577        "role" => {
578            let role = if v["role"] == "control" { Role::Control } else { Role::View };
579            *shared.role.lock().unwrap() = role;
580            Event::Role(role)
581        }
582        "ime_area" => {
583            let f = |k: &str| v[k].as_f64().map(|x| x as f32);
584            Event::ImeArea(match (f("x"), f("y"), f("w"), f("h")) {
585                (Some(x), Some(y), Some(w), Some(h)) => Some([x, y, w, h]),
586                _ => None,
587            })
588        }
589        _ => Event::Other(v.clone()),
590    };
591    shared.event(event);
592}
593
594fn decode_loop(frames: Receiver<Vec<u8>>, shared: &Shared, out: &Sender<String>) {
595    while let Ok(m) = frames.recv() {
596        match apply(&m, shared) {
597            Ok(seq) => {
598                let _ = out.send(serde_json::json!({"t": "ack", "seq": seq}).to_string());
599                shared.wake();
600            }
601            Err(e) => shared.event(Event::Other(serde_json::json!({"t": "decode_error", "msg": e}))),
602        }
603    }
604}
605
606/// Apply one frame message (protocol v1 ยง3.2) to the shared picture.
607fn apply(m: &[u8], shared: &Shared) -> Result<u32, String> {
608    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()) };
609    if m.len() < 12 || m[0] != 1 {
610        return Err("not a frame".into());
611    }
612    let n = u16_at(2)? as usize;
613    let seq = u32::from_le_bytes([m[4], m[5], m[6], m[7]]);
614    let (w, h) = (u16_at(8)?, u16_at(10)?);
615    // Decode every tile before touching the picture: a frame lands whole.
616    let mut tiles = Vec::with_capacity(n);
617    let mut off = 12;
618    for _ in 0..n {
619        let (x, y, tw, th) = (u16_at(off)?, u16_at(off + 2)?, u16_at(off + 4)?, u16_at(off + 6)?);
620        let codec = *m.get(off + 8).ok_or("short frame")?;
621        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")?;
622        off += 14;
623        let bytes = m.get(off..off + len).ok_or("short frame")?;
624        off += len;
625        let format = if codec == 2 { image::ImageFormat::Jpeg } else { image::ImageFormat::Png };
626        let tile = image::load_from_memory_with_format(bytes, format).map_err(|e| e.to_string())?.to_rgba8();
627        if (tile.width(), tile.height()) != (tw, th) || x + tw > w || y + th > h {
628            return Err("a tile does not fit the frame".into());
629        }
630        tiles.push((x, y, tile));
631    }
632    let mut frame = shared.frame.lock().unwrap();
633    let resized = (frame.width, frame.height) != (w, h);
634    if resized {
635        *frame = Frame { width: w, height: h, rgba: vec![0; (w * h * 4) as usize], seq: frame.seq, frames: frame.frames };
636    }
637    let mut dirty: Option<Rect> = None;
638    for (x, y, tile) in &tiles {
639        let (tw, th) = (tile.width(), tile.height());
640        for row in 0..th {
641            let dst = (((y + row) * w + x) * 4) as usize;
642            let src = (row * tw * 4) as usize;
643            frame.rgba[dst..dst + (tw * 4) as usize].copy_from_slice(&tile.as_raw()[src..src + (tw * 4) as usize]);
644        }
645        let r = Rect { x: *x, y: *y, width: tw, height: th };
646        dirty = Some(dirty.map_or(r, |d| d.union(r)));
647    }
648    frame.seq = seq;
649    frame.frames += 1;
650    drop(frame);
651    let mut held = shared.dirty.lock().unwrap();
652    let full = Rect { x: 0, y: 0, width: w, height: h };
653    *held = match (*held, resized, dirty) {
654        (_, true, _) => Some(Update { resized: true, dirty: full }),
655        (Some(u), false, Some(d)) => Some(Update { resized: u.resized, dirty: if u.resized { full } else { u.dirty.union(d) } }),
656        (None, false, Some(d)) => Some(Update { resized: false, dirty: d }),
657        (held, false, None) => held,
658    };
659    Ok(seq)
660}
661
662/// Starts `brep-app --stream` as a child process and connects to it.
663pub struct Launcher {
664    command: Command,
665    options: ConnectOptions,
666    ready_timeout: Duration,
667}
668
669impl Launcher {
670    /// Run `program` (`"brep-app"` on the `PATH`, or a path to it).
671    pub fn new(program: impl AsRef<std::ffi::OsStr>) -> Launcher {
672        Launcher::from_command(Command::new(program))
673    }
674
675    /// Run this command, with its own arguments (a document to open, `--mcp`
676    /// for an AI agent beside you), environment and working directory. The
677    /// launcher adds the `--stream` switches and takes its stdin and stdout.
678    pub fn from_command(command: Command) -> Launcher {
679        Launcher { command, options: ConnectOptions::default(), ready_timeout: Duration::from_secs(120) }
680    }
681
682    /// The session's size in logical pixels and its density.
683    pub fn size(mut self, width: f32, height: f32, density: f32) -> Launcher {
684        (self.options.width, self.options.height, self.options.density) = (width, height, density);
685        self
686    }
687
688    /// How long the app may take to start (default two minutes).
689    pub fn ready_timeout(mut self, timeout: Duration) -> Launcher {
690        self.ready_timeout = timeout;
691        self
692    }
693
694    /// Start the app and connect as the controlling client.
695    pub fn launch(mut self) -> Result<Session, Error> {
696        let token_file = std::env::temp_dir().join(format!(
697            "brep-stream-{}-{}.token",
698            std::process::id(),
699            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0)
700        ));
701        self.command
702            .args(["--stream", "127.0.0.1:0", "--stream-until-stdin-closes", "--stream-token-file"])
703            .arg(&token_file)
704            .stdin(Stdio::piped())
705            .stdout(Stdio::piped());
706        let mut child = self.command.spawn().map_err(|e| Error::Launch(format!("{:?}: {e}", self.command.get_program())))?;
707        let stdin = child.stdin.take();
708        let stdout = child.stdout.take().ok_or_else(|| Error::Launch("no stdout".into()))?;
709        // Read the ready line on a thread (a read cannot time out), then keep
710        // draining what the app prints, so a full pipe never blocks it.
711        let (ready_tx, ready_rx) = mpsc::channel::<Result<serde_json::Value, String>>();
712        std::thread::Builder::new()
713            .name("brep-stream-stdout".into())
714            .spawn(move || {
715                let mut ready = Some(ready_tx);
716                for line in BufReader::new(stdout).lines() {
717                    let Ok(line) = line else { break };
718                    if let (Some(rest), Some(tx)) = (line.strip_prefix(READY_PREFIX), ready.as_ref()) {
719                        let _ = tx.send(serde_json::from_str(rest).map_err(|e| e.to_string()));
720                        ready = None;
721                    }
722                }
723                if let Some(tx) = ready {
724                    let _ = tx.send(Err("the app ended before it was ready".into()));
725                }
726            })
727            .map_err(|e| Error::Launch(e.to_string()))?;
728        let mut session = Session { child: Some(child), stdin, client: None, token_file: token_file.clone(), url: String::new(), token: String::new() };
729        let ready = match ready_rx.recv_timeout(self.ready_timeout) {
730            Ok(Ok(ready)) => ready,
731            Ok(Err(why)) => return Err(Error::Launch(format!("{why} ({})", session.exit_note()))),
732            Err(RecvTimeoutError::Timeout) => return Err(Error::Timeout(format!("the app was not ready in {} s", self.ready_timeout.as_secs()))),
733            Err(RecvTimeoutError::Disconnected) => return Err(Error::Launch("the app's output closed".into())),
734        };
735        let ws = ready["ws"].as_str().ok_or_else(|| Error::Launch(format!("a ready line without `ws`: {ready}")))?.to_string();
736        let token = std::fs::read_to_string(&token_file).map_err(|e| Error::Launch(format!("token file {}: {e}", token_file.display())))?;
737        let _ = std::fs::remove_file(&token_file);
738        session.client = Some(Client::connect(&ws, token.trim(), self.options)?);
739        (session.url, session.token) = (ws, token.trim().to_string());
740        Ok(session)
741    }
742}
743
744/// A launched app and the connection to it. Derefs to [`Client`]. Dropping it
745/// ends the app (it closes the app's stdin; the app exits as when its window
746/// closes) and waits for it, briefly.
747pub struct Session {
748    child: Option<Child>,
749    stdin: Option<ChildStdin>,
750    client: Option<Client>,
751    token_file: PathBuf,
752    url: String,
753    token: String,
754}
755
756impl Session {
757    /// The session's WebSocket, for more clients ([`Client::connect`]): a
758    /// second view of the same session, or a browser page (`/stream/` beside it).
759    pub fn url(&self) -> &str {
760        &self.url
761    }
762
763    /// The session's token, for more clients.
764    pub fn token(&self) -> &str {
765        &self.token
766    }
767
768    /// The app's process id.
769    pub fn pid(&self) -> Option<u32> {
770        self.child.as_ref().map(Child::id)
771    }
772
773    /// End the app and wait for it, up to `timeout`; kill it after that.
774    pub fn shutdown(mut self, timeout: Duration) -> std::io::Result<ExitStatus> {
775        self.end(timeout)
776    }
777
778    fn end(&mut self, timeout: Duration) -> std::io::Result<ExitStatus> {
779        self.client = None;
780        drop(self.stdin.take());
781        let Some(mut child) = self.child.take() else {
782            return Err(std::io::Error::other("already ended"));
783        };
784        let start = Instant::now();
785        loop {
786            if let Some(status) = child.try_wait()? {
787                return Ok(status);
788            }
789            if start.elapsed() > timeout {
790                child.kill()?;
791                return child.wait();
792            }
793            std::thread::sleep(Duration::from_millis(20));
794        }
795    }
796
797    fn exit_note(&mut self) -> String {
798        match self.child.as_mut().map(Child::try_wait) {
799            Some(Ok(Some(status))) => format!("it exited: {status}"),
800            _ => "it is still running".into(),
801        }
802    }
803}
804
805impl std::ops::Deref for Session {
806    type Target = Client;
807    fn deref(&self) -> &Client {
808        self.client.as_ref().expect("a launched session is connected")
809    }
810}
811
812impl Drop for Session {
813    fn drop(&mut self) {
814        let _ = self.end(Duration::from_secs(15));
815        let _ = std::fs::remove_file(&self.token_file);
816    }
817}
818