Skip to main content

brep_app/stream/
input.rs

1//! Protocol v1 client messages and their translation into the `egui::Event`s of
2//! the next pass.
3use serde::Deserialize;
4
5/// Modifier keys as the page reports them (`c` ctrl, `s` shift, `a` alt,
6/// `m` meta: Cmd on a Mac, the Windows key elsewhere).
7#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
8pub struct Mods {
9    #[serde(default)]
10    pub c: bool,
11    #[serde(default)]
12    pub s: bool,
13    #[serde(default)]
14    pub a: bool,
15    #[serde(default)]
16    pub m: bool,
17}
18
19impl Mods {
20    /// The session runs as Linux: Ctrl and the page's Meta (Cmd) are both
21    /// egui's `command`, as `automation::pointer::Modifiers` maps them.
22    pub fn egui(self) -> egui::Modifiers {
23        crate::automation::pointer::Modifiers { ctrl: self.c, shift: self.s, alt: self.a, command: self.m }.egui()
24    }
25}
26
27/// One message from the page.
28#[derive(Debug, Clone, Deserialize)]
29#[serde(tag = "t", rename_all = "snake_case")]
30pub enum ClientMsg {
31    Hello {
32        v: u32,
33        token: String,
34        #[serde(default)]
35        role: Option<String>,
36        #[serde(default)]
37        w: Option<f32>,
38        #[serde(default)]
39        h: Option<f32>,
40        #[serde(default)]
41        dpr: Option<f32>,
42    },
43    Resize { w: f32, h: f32, dpr: f32 },
44    Pm { x: f32, y: f32 },
45    Pb {
46        x: f32,
47        y: f32,
48        b: u8,
49        down: bool,
50        #[serde(default)]
51        mods: Mods,
52    },
53    Leave,
54    Wheel {
55        dx: f32,
56        dy: f32,
57        #[serde(default)]
58        mode: u8,
59        #[serde(default)]
60        mods: Mods,
61    },
62    Key {
63        key: String,
64        #[serde(default)]
65        code: String,
66        down: bool,
67        #[serde(default)]
68        repeat: bool,
69        #[serde(default)]
70        mods: Mods,
71    },
72    Text { s: String },
73    Ime {
74        phase: String,
75        #[serde(default)]
76        s: String,
77    },
78    Paste { s: String },
79    Touch {
80        id: u64,
81        phase: String,
82        x: f32,
83        y: f32,
84        #[serde(default)]
85        force: Option<f32>,
86    },
87    Focus { on: bool },
88    Ack { seq: u32 },
89    TakeControl,
90    /// The controller wants to upload a file: answered with an `upload`
91    /// message carrying the id its bytes are POSTed to
92    /// (`/stream/uploads/<id>`), so file bytes never queue the input socket.
93    Drop { name: String, size: u64 },
94    Quality {
95        #[serde(default)]
96        jpeg: Option<u8>,
97    },
98}
99
100/// The controller's input state across messages: the modifiers last seen and
101/// which touch drives the emulated pointer (as egui-winit does: the first
102/// finger down also moves and presses the pointer, so a tap clicks).
103#[derive(Debug, Default)]
104pub struct InputState {
105    pub mods: egui::Modifiers,
106    pub(crate) primary_touch: Option<u64>,
107    pub focused: bool,
108}
109
110/// `name` from `KeyboardEvent.code` ("KeyA", "Digit1", "ArrowUp", ...).
111fn physical(code: &str) -> Option<egui::Key> {
112    let name = code.strip_prefix("Key").or_else(|| code.strip_prefix("Digit")).unwrap_or(code);
113    egui::Key::from_name(name)
114}
115
116fn button(b: u8) -> Option<egui::PointerButton> {
117    Some(match b {
118        0 => egui::PointerButton::Primary,
119        1 => egui::PointerButton::Secondary,
120        2 => egui::PointerButton::Middle,
121        3 => egui::PointerButton::Extra1,
122        4 => egui::PointerButton::Extra2,
123        _ => return None,
124    })
125}
126
127fn touch_phase(phase: &str) -> Option<egui::TouchPhase> {
128    Some(match phase {
129        "start" => egui::TouchPhase::Start,
130        "move" => egui::TouchPhase::Move,
131        "end" => egui::TouchPhase::End,
132        "cancel" => egui::TouchPhase::Cancel,
133        _ => return None,
134    })
135}
136
137impl InputState {
138    /// The events `msg` becomes. `zoom` is egui's zoom factor: page
139    /// coordinates are CSS pixels, which are points at zoom 1.
140    pub fn events(&mut self, msg: &ClientMsg, zoom: f32, out: &mut Vec<egui::Event>) {
141        let pos = |x: f32, y: f32| egui::pos2(x / zoom, y / zoom);
142        match msg {
143            ClientMsg::Pm { x, y } => out.push(egui::Event::PointerMoved(pos(*x, *y))),
144            ClientMsg::Pb { x, y, b, down, mods } => {
145                self.mods = mods.egui();
146                if let Some(button) = button(*b) {
147                    out.push(egui::Event::PointerMoved(pos(*x, *y)));
148                    out.push(egui::Event::PointerButton { pos: pos(*x, *y), button, pressed: *down, modifiers: self.mods });
149                }
150            }
151            ClientMsg::Leave => out.push(egui::Event::PointerGone),
152            ClientMsg::Wheel { dx, dy, mode, mods } => {
153                self.mods = mods.egui();
154                let unit = match mode {
155                    1 => egui::MouseWheelUnit::Line,
156                    2 => egui::MouseWheelUnit::Page,
157                    _ => egui::MouseWheelUnit::Point,
158                };
159                // DOM deltas say where the page scrolls; egui's say where
160                // the content moves (egui-winit and eframe web negate too).
161                let mut delta = egui::vec2(-dx, -dy);
162                if unit == egui::MouseWheelUnit::Point {
163                    delta /= zoom;
164                }
165                out.push(egui::Event::MouseWheel { unit, delta, phase: egui::TouchPhase::Move, modifiers: self.mods });
166            }
167            ClientMsg::Key { key, code, down, repeat, mods } => {
168                self.mods = mods.egui();
169                let logical = egui::Key::from_name(key).or_else(|| physical(code));
170                let Some(logical) = logical else { return };
171                if *down && self.mods.command && !self.mods.alt {
172                    // The clipboard keys are egui events of their own, as
173                    // egui-winit sends them; the paste text comes with the
174                    // page's own `paste` event.
175                    match logical {
176                        egui::Key::C => return out.push(egui::Event::Copy),
177                        egui::Key::X => return out.push(egui::Event::Cut),
178                        egui::Key::V => return,
179                        _ => {}
180                    }
181                }
182                out.push(egui::Event::Key { key: logical, physical_key: physical(code), pressed: *down, repeat: *repeat, modifiers: self.mods });
183            }
184            ClientMsg::Text { s } => {
185                if !s.is_empty() && !s.chars().any(char::is_control) {
186                    out.push(egui::Event::Text(s.clone()));
187                }
188            }
189            ClientMsg::Ime { phase, s } => match phase.as_str() {
190                "update" => out.push(egui::Event::Ime(egui::ImeEvent::Preedit { text: s.clone(), active_range_chars: None })),
191                "commit" => out.push(egui::Event::Ime(egui::ImeEvent::Commit(s.clone()))),
192                "end" => out.push(egui::Event::Ime(egui::ImeEvent::Preedit { text: String::new(), active_range_chars: None })),
193                _ => {}
194            },
195            ClientMsg::Paste { s } => out.push(egui::Event::Paste(s.clone())),
196            ClientMsg::Touch { id, phase, x, y, force } => {
197                let Some(phase) = touch_phase(phase) else { return };
198                let p = pos(*x, *y);
199                out.push(egui::Event::Touch { device_id: egui::TouchDeviceId(1), id: egui::TouchId(*id), phase, pos: p, force: *force });
200                // The first finger is also the pointer.
201                match phase {
202                    egui::TouchPhase::Start if self.primary_touch.is_none() => {
203                        self.primary_touch = Some(*id);
204                        out.push(egui::Event::PointerMoved(p));
205                        out.push(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: true, modifiers: self.mods });
206                    }
207                    egui::TouchPhase::Move if self.primary_touch == Some(*id) => out.push(egui::Event::PointerMoved(p)),
208                    egui::TouchPhase::End | egui::TouchPhase::Cancel if self.primary_touch == Some(*id) => {
209                        self.primary_touch = None;
210                        out.push(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: false, modifiers: self.mods });
211                        out.push(egui::Event::PointerGone);
212                    }
213                    _ => {}
214                }
215            }
216            ClientMsg::Focus { on } => {
217                self.focused = *on;
218                out.push(egui::Event::WindowFocused(*on));
219            }
220            ClientMsg::Hello { .. } | ClientMsg::Resize { .. } | ClientMsg::Ack { .. } | ClientMsg::TakeControl | ClientMsg::Quality { .. } | ClientMsg::Drop { .. } => {}
221        }
222    }
223}
224
225/// The CSS cursor for egui's.
226pub fn css_cursor(icon: egui::CursorIcon) -> &'static str {
227    use egui::CursorIcon as C;
228    match icon {
229        C::Default => "default",
230        C::None => "none",
231        C::ContextMenu => "context-menu",
232        C::Help => "help",
233        C::PointingHand => "pointer",
234        C::Progress => "progress",
235        C::Wait => "wait",
236        C::Cell => "cell",
237        C::Crosshair => "crosshair",
238        C::Text => "text",
239        C::VerticalText => "vertical-text",
240        C::Alias => "alias",
241        C::Copy => "copy",
242        C::Move => "move",
243        C::NoDrop => "no-drop",
244        C::NotAllowed => "not-allowed",
245        C::Grab => "grab",
246        C::Grabbing => "grabbing",
247        C::AllScroll => "all-scroll",
248        C::ResizeHorizontal => "ew-resize",
249        C::ResizeNeSw => "nesw-resize",
250        C::ResizeNwSe => "nwse-resize",
251        C::ResizeVertical => "ns-resize",
252        C::ResizeEast => "e-resize",
253        C::ResizeSouthEast => "se-resize",
254        C::ResizeSouth => "s-resize",
255        C::ResizeSouthWest => "sw-resize",
256        C::ResizeWest => "w-resize",
257        C::ResizeNorthWest => "nw-resize",
258        C::ResizeNorth => "n-resize",
259        C::ResizeNorthEast => "ne-resize",
260        C::ResizeColumn => "col-resize",
261        C::ResizeRow => "row-resize",
262        C::ZoomIn => "zoom-in",
263        C::ZoomOut => "zoom-out",
264    }
265}
266