BREP_stream_client 0.1.0

Embed the next.BREP.io CAD application in a Rust program: launch `brep-app --stream` headless (or connect to one), receive its whole window as RGBA frames and drive it with pointer, keyboard and touch input. No browser and no GUI toolkit required.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
//! Embed the next.BREP.io CAD application in a Rust program.
//!
//! `brep-app --stream` runs the CAD application with no window and no display
//! and serves its whole user interface over a WebSocket: every frame it draws,
//! as tiles, and every input it should take. This crate is the native end of
//! that connection, so a Rust program can show the CAD session inside its own
//! window (any toolkit: it hands you RGBA pixels) and drive it, with no browser.
//!
//! ```no_run
//! use brep_stream_client::{Input, Launcher, Mods, PointerButton};
//! # fn main() -> Result<(), brep_stream_client::Error> {
//! // Start the app (it must be installed: `cargo install BREP_app`, or the
//! // desktop download) at 1280 x 800 logical pixels, density 1.
//! let session = Launcher::new("brep-app").size(1280.0, 800.0, 1.0).launch()?;
//! session.wait_frame(std::time::Duration::from_secs(120))?;
//! {
//!     let frame = session.frame();
//!     println!("{} x {} pixels", frame.width, frame.height);
//! }
//! // Click the File menu.
//! session.send(Input::Button { x: 148.0, y: 19.0, button: PointerButton::Primary, down: true, mods: Mods::NONE });
//! session.send(Input::Button { x: 148.0, y: 19.0, button: PointerButton::Primary, down: false, mods: Mods::NONE });
//! # Ok(()) }
//! ```
//!
//! Coordinates are logical pixels (egui points, CSS pixels) from the top-left
//! of the session; frames are physical pixels, `density` times as many.
//! [`Launcher`] starts `brep-app` as a child process that ends when the
//! [`Session`] is dropped; [`Client::connect`] attaches to one already running
//! (`brep-app --stream ADDR`), given its address and session token.
//!
//! The protocol is version 1 of the stream. Plain `ws://` only: put TLS
//! in front of a remote session with a reverse proxy, or reach it over
//! an SSH tunnel.
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;

/// The stream protocol version this crate speaks.
pub const PROTOCOL: u32 = 1;
/// The line `brep-app --stream` prints when the session accepts connections.
pub const READY_PREFIX: &str = "BREP-STREAM-READY ";

/// What went wrong.
#[derive(Debug)]
pub enum Error {
    /// Starting the app, or reading what it printed.
    Launch(String),
    /// The connection: refused, closed, or not a stream server.
    Connection(String),
    /// The server refused the session (`auth`: wrong token; `version`).
    Refused { code: String, message: String },
    /// Nothing arrived in time.
    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 {}

/// Modifier keys held with an input. `meta` is Cmd on a Mac keyboard; the
/// session treats it, like Ctrl, as the command key.
#[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,
        }
    }
}

/// What a wheel delta counts.
#[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,
}

/// One input for the session. Positions are logical pixels from the session's
/// top-left corner.
#[derive(Debug, Clone, PartialEq)]
pub enum Input {
    PointerMove { x: f32, y: f32 },
    Button { x: f32, y: f32, button: PointerButton, down: bool, mods: Mods },
    /// The pointer left the session's area.
    PointerLeave,
    /// A wheel turn, as a browser reports it: positive `dy` scrolls the page
    /// down (moves the content up).
    Wheel { dx: f32, dy: f32, unit: WheelUnit, mods: Mods },
    /// A key, named as egui or a browser's `KeyboardEvent.key` names it:
    /// `"A"`, `"Enter"`, `"Escape"`, `"ArrowUp"`, `"F2"`, `"Delete"`.
    /// Ctrl/Cmd + C and X copy and cut (the copied text arrives as
    /// [`Event::Clipboard`]); paste with [`Input::Paste`].
    Key { key: String, down: bool, repeat: bool, mods: Mods },
    /// Typed text (what a key press types, or an input method's result).
    Text(String),
    /// Paste this text where the session's keyboard focus is.
    Paste(String),
    /// An input method's composition in progress (empty: dismissed).
    ImePreedit(String),
    /// An input method's final text.
    ImeCommit(String),
    Touch { id: u64, phase: TouchPhase, x: f32, y: f32, force: Option<f32> },
    /// The host window gained or lost keyboard focus.
    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}),
        }
    }
}

/// This client's part in the session: one client controls it (its input and
/// size apply); the others watch.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Role {
    Control,
    View,
}

/// A pixel rectangle `x, y, width, height`.
#[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 }
    }
}

/// Something the session told this client.
#[derive(Debug, Clone, PartialEq)]
pub enum Event {
    /// The pointer's cursor over the session, as a CSS cursor name
    /// (`default`, `pointer`, `text`, `grab`, `ew-resize`, ...).
    Cursor(String),
    /// Text the session copied: put it on the host's clipboard.
    Clipboard(String),
    /// The session asked to open a link.
    OpenUrl { url: String, new_tab: bool },
    /// This client's role changed.
    Role(Role),
    /// Where a text cursor is (logical pixels), for placing an input method's
    /// window; `None` when no text field has focus.
    ImeArea(Option<[f32; 4]>),
    /// The connection ended.
    Closed(String),
    /// Any other message, as sent.
    Other(serde_json::Value),
}

/// The session's picture as this client holds it.
#[derive(Debug, Clone, Default)]
pub struct Frame {
    /// Physical pixels.
    pub width: u32,
    pub height: u32,
    /// Straight RGBA, row-major, `width * height * 4` bytes.
    pub rgba: Vec<u8>,
    /// The server's sequence number of the last frame applied.
    pub seq: u32,
    /// How many frames have been applied.
    pub frames: u64,
}

/// What changed since the last [`Client::take_update`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Update {
    /// The size changed (re-create a texture rather than patch it).
    pub resized: bool,
    /// The changed area (all of it after a resize).
    pub dirty: Rect,
}

/// How [`Client::connect`] introduces itself.
#[derive(Debug, Clone)]
pub struct ConnectOptions {
    pub role: Role,
    /// The session's size in logical pixels, and the density (physical pixels
    /// per logical pixel). Only a controlling client's size applies.
    pub width: f32,
    pub height: f32,
    pub density: f32,
    /// How long to wait for the server's welcome.
    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>>,
    /// The size last asked for (logical width, height, density): sent again
    /// when this client becomes the controller.
    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();
    }
}

/// A connection to a streamed session. Cheap to share by reference; every
/// method takes `&self`. Its threads end when it is dropped.
pub struct Client {
    out: Sender<String>,
    shared: Arc<Shared>,
    session: String,
    /// Set when the client is dropped: the connection's thread closes it.
    /// (The decode thread holds a sender of its own for acks, so the channel
    /// alone never says the client is gone.)
    dropped: Arc<std::sync::atomic::AtomicBool>,
}

impl Drop for Client {
    fn drop(&mut self) {
        self.dropped.store(true, std::sync::atomic::Ordering::SeqCst);
    }
}

/// How often the connection's thread looks for input to send while it waits
/// for the server: the most an input waits before it leaves.
const IO_POLL: Duration = Duration::from_millis(2);

impl Client {
    /// Connect to a running `brep-app --stream`: `url` is its WebSocket
    /// (`ws://127.0.0.1:8770/stream/ws`) or its address (`127.0.0.1:8770`),
    /// `token` the session token from its token file.
    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>>();
        // Frames decode on their own thread, so a large keyframe never holds
        // the input waiting behind it.
        {
            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 })
    }

    /// The server's session id.
    pub fn session_id(&self) -> &str {
        &self.session
    }

    /// Send one input. Applies only while this client controls the session.
    pub fn send(&self, input: Input) {
        let _ = self.out.send(input.message().to_string());
    }

    /// Ask for the session at this size (logical pixels) and density. The
    /// next frames arrive at `width * density` by `height * density` pixels.
    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());
    }

    /// Become the controlling client (the current one becomes a viewer).
    pub fn take_control(&self) {
        let _ = self.out.send(serde_json::json!({"t": "take_control"}).to_string());
    }

    /// JPEG quality (10-95) of the 3D view's tiles while it moves.
    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()
    }

    /// Why the connection ended, once it has.
    pub fn closed(&self) -> Option<String> {
        self.shared.closed.lock().unwrap().clone()
    }

    /// Called (on the connection's threads) whenever a frame or an event
    /// arrives: a GUI host asks itself to repaint here.
    pub fn set_waker(&self, waker: impl Fn() + Send + Sync + 'static) {
        *self.shared.waker.lock().unwrap() = Some(Box::new(waker));
    }

    /// The current picture. Hold the guard briefly: frames wait for it.
    pub fn frame(&self) -> MutexGuard<'_, Frame> {
        self.shared.frame.lock().unwrap()
    }

    /// What changed since the last call (`None`: nothing).
    pub fn take_update(&self) -> Option<Update> {
        self.shared.dirty.lock().unwrap().take()
    }

    /// The events that arrived since the last call.
    pub fn poll_events(&self) -> Vec<Event> {
        self.shared.events.lock().unwrap().drain(..).collect()
    }

    /// Wait until a frame newer than the one held now arrives.
    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(())
    }

    /// Wait until no frame has arrived for `quiet` (the picture is still), or
    /// fail after `timeout`.
    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) {
            // The client was dropped: close, so the session frees its place
            // (a dropped controller would otherwise keep control).
            let _ = ws.close(None);
            let _ = ws.flush();
            return;
        }
        // Everything queued goes first: input never waits for a frame.
        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,
                // The client was dropped.
                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" {
                        // Control came to this client: its size applies now.
                        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}))),
        }
    }
}

/// Apply one frame message (protocol v1 §3.2) to the shared picture.
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)?);
    // Decode every tile before touching the picture: a frame lands whole.
    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)
}

/// Starts `brep-app --stream` as a child process and connects to it.
pub struct Launcher {
    command: Command,
    options: ConnectOptions,
    ready_timeout: Duration,
}

impl Launcher {
    /// Run `program` (`"brep-app"` on the `PATH`, or a path to it).
    pub fn new(program: impl AsRef<std::ffi::OsStr>) -> Launcher {
        Launcher::from_command(Command::new(program))
    }

    /// Run this command, with its own arguments (a document to open, `--mcp`
    /// for an AI agent beside you), environment and working directory. The
    /// launcher adds the `--stream` switches and takes its stdin and stdout.
    pub fn from_command(command: Command) -> Launcher {
        Launcher { command, options: ConnectOptions::default(), ready_timeout: Duration::from_secs(120) }
    }

    /// The session's size in logical pixels and its density.
    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
    }

    /// How long the app may take to start (default two minutes).
    pub fn ready_timeout(mut self, timeout: Duration) -> Launcher {
        self.ready_timeout = timeout;
        self
    }

    /// Start the app and connect as the controlling client.
    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()))?;
        // Read the ready line on a thread (a read cannot time out), then keep
        // draining what the app prints, so a full pipe never blocks it.
        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)
    }
}

/// A launched app and the connection to it. Derefs to [`Client`]. Dropping it
/// ends the app (it closes the app's stdin; the app exits as when its window
/// closes) and waits for it, briefly.
pub struct Session {
    child: Option<Child>,
    stdin: Option<ChildStdin>,
    client: Option<Client>,
    token_file: PathBuf,
    url: String,
    token: String,
}

impl Session {
    /// The session's WebSocket, for more clients ([`Client::connect`]): a
    /// second view of the same session, or a browser page (`/stream/` beside it).
    pub fn url(&self) -> &str {
        &self.url
    }

    /// The session's token, for more clients.
    pub fn token(&self) -> &str {
        &self.token
    }

    /// The app's process id.
    pub fn pid(&self) -> Option<u32> {
        self.child.as_ref().map(Child::id)
    }

    /// End the app and wait for it, up to `timeout`; kill it after that.
    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);
    }
}