BREP_app 0.36.1

The next.BREP.io CAD application on the Rust B-rep kernel: an eframe (egui + wgpu) host that draws the brep-render 3D engine into an egui frame, native + wasm from one codebase.
Documentation
//! Protocol v1 client messages and their translation into the `egui::Event`s of
//! the next pass.
use serde::Deserialize;

/// Modifier keys as the page reports them (`c` ctrl, `s` shift, `a` alt,
/// `m` meta: Cmd on a Mac, the Windows key elsewhere).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
pub struct Mods {
    #[serde(default)]
    pub c: bool,
    #[serde(default)]
    pub s: bool,
    #[serde(default)]
    pub a: bool,
    #[serde(default)]
    pub m: bool,
}

impl Mods {
    /// The session runs as Linux: Ctrl and the page's Meta (Cmd) are both
    /// egui's `command`, as `automation::pointer::Modifiers` maps them.
    pub fn egui(self) -> egui::Modifiers {
        crate::automation::pointer::Modifiers { ctrl: self.c, shift: self.s, alt: self.a, command: self.m }.egui()
    }
}

/// One message from the page.
#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "t", rename_all = "snake_case")]
pub enum ClientMsg {
    Hello {
        v: u32,
        token: String,
        #[serde(default)]
        role: Option<String>,
        #[serde(default)]
        w: Option<f32>,
        #[serde(default)]
        h: Option<f32>,
        #[serde(default)]
        dpr: Option<f32>,
    },
    Resize { w: f32, h: f32, dpr: f32 },
    Pm { x: f32, y: f32 },
    Pb {
        x: f32,
        y: f32,
        b: u8,
        down: bool,
        #[serde(default)]
        mods: Mods,
    },
    Leave,
    Wheel {
        dx: f32,
        dy: f32,
        #[serde(default)]
        mode: u8,
        #[serde(default)]
        mods: Mods,
    },
    Key {
        key: String,
        #[serde(default)]
        code: String,
        down: bool,
        #[serde(default)]
        repeat: bool,
        #[serde(default)]
        mods: Mods,
    },
    Text { s: String },
    Ime {
        phase: String,
        #[serde(default)]
        s: String,
    },
    Paste { s: String },
    Touch {
        id: u64,
        phase: String,
        x: f32,
        y: f32,
        #[serde(default)]
        force: Option<f32>,
    },
    Focus { on: bool },
    Ack { seq: u32 },
    TakeControl,
    /// The controller wants to upload a file: answered with an `upload`
    /// message carrying the id its bytes are POSTed to
    /// (`/stream/uploads/<id>`), so file bytes never queue the input socket.
    Drop { name: String, size: u64 },
    Quality {
        #[serde(default)]
        jpeg: Option<u8>,
    },
}

/// The controller's input state across messages: the modifiers last seen and
/// which touch drives the emulated pointer (as egui-winit does: the first
/// finger down also moves and presses the pointer, so a tap clicks).
#[derive(Debug, Default)]
pub struct InputState {
    pub mods: egui::Modifiers,
    pub(crate) primary_touch: Option<u64>,
    pub focused: bool,
}

/// `name` from `KeyboardEvent.code` ("KeyA", "Digit1", "ArrowUp", ...).
fn physical(code: &str) -> Option<egui::Key> {
    let name = code.strip_prefix("Key").or_else(|| code.strip_prefix("Digit")).unwrap_or(code);
    egui::Key::from_name(name)
}

fn button(b: u8) -> Option<egui::PointerButton> {
    Some(match b {
        0 => egui::PointerButton::Primary,
        1 => egui::PointerButton::Secondary,
        2 => egui::PointerButton::Middle,
        3 => egui::PointerButton::Extra1,
        4 => egui::PointerButton::Extra2,
        _ => return None,
    })
}

fn touch_phase(phase: &str) -> Option<egui::TouchPhase> {
    Some(match phase {
        "start" => egui::TouchPhase::Start,
        "move" => egui::TouchPhase::Move,
        "end" => egui::TouchPhase::End,
        "cancel" => egui::TouchPhase::Cancel,
        _ => return None,
    })
}

impl InputState {
    /// The events `msg` becomes. `zoom` is egui's zoom factor: page
    /// coordinates are CSS pixels, which are points at zoom 1.
    pub fn events(&mut self, msg: &ClientMsg, zoom: f32, out: &mut Vec<egui::Event>) {
        let pos = |x: f32, y: f32| egui::pos2(x / zoom, y / zoom);
        match msg {
            ClientMsg::Pm { x, y } => out.push(egui::Event::PointerMoved(pos(*x, *y))),
            ClientMsg::Pb { x, y, b, down, mods } => {
                self.mods = mods.egui();
                if let Some(button) = button(*b) {
                    out.push(egui::Event::PointerMoved(pos(*x, *y)));
                    out.push(egui::Event::PointerButton { pos: pos(*x, *y), button, pressed: *down, modifiers: self.mods });
                }
            }
            ClientMsg::Leave => out.push(egui::Event::PointerGone),
            ClientMsg::Wheel { dx, dy, mode, mods } => {
                self.mods = mods.egui();
                let unit = match mode {
                    1 => egui::MouseWheelUnit::Line,
                    2 => egui::MouseWheelUnit::Page,
                    _ => egui::MouseWheelUnit::Point,
                };
                // DOM deltas say where the page scrolls; egui's say where
                // the content moves (egui-winit and eframe web negate too).
                let mut delta = egui::vec2(-dx, -dy);
                if unit == egui::MouseWheelUnit::Point {
                    delta /= zoom;
                }
                out.push(egui::Event::MouseWheel { unit, delta, phase: egui::TouchPhase::Move, modifiers: self.mods });
            }
            ClientMsg::Key { key, code, down, repeat, mods } => {
                self.mods = mods.egui();
                let logical = egui::Key::from_name(key).or_else(|| physical(code));
                let Some(logical) = logical else { return };
                if *down && self.mods.command && !self.mods.alt {
                    // The clipboard keys are egui events of their own, as
                    // egui-winit sends them; the paste text comes with the
                    // page's own `paste` event.
                    match logical {
                        egui::Key::C => return out.push(egui::Event::Copy),
                        egui::Key::X => return out.push(egui::Event::Cut),
                        egui::Key::V => return,
                        _ => {}
                    }
                }
                out.push(egui::Event::Key { key: logical, physical_key: physical(code), pressed: *down, repeat: *repeat, modifiers: self.mods });
            }
            ClientMsg::Text { s } => {
                if !s.is_empty() && !s.chars().any(char::is_control) {
                    out.push(egui::Event::Text(s.clone()));
                }
            }
            ClientMsg::Ime { phase, s } => match phase.as_str() {
                "update" => out.push(egui::Event::Ime(egui::ImeEvent::Preedit { text: s.clone(), active_range_chars: None })),
                "commit" => out.push(egui::Event::Ime(egui::ImeEvent::Commit(s.clone()))),
                "end" => out.push(egui::Event::Ime(egui::ImeEvent::Preedit { text: String::new(), active_range_chars: None })),
                _ => {}
            },
            ClientMsg::Paste { s } => out.push(egui::Event::Paste(s.clone())),
            ClientMsg::Touch { id, phase, x, y, force } => {
                let Some(phase) = touch_phase(phase) else { return };
                let p = pos(*x, *y);
                out.push(egui::Event::Touch { device_id: egui::TouchDeviceId(1), id: egui::TouchId(*id), phase, pos: p, force: *force });
                // The first finger is also the pointer.
                match phase {
                    egui::TouchPhase::Start if self.primary_touch.is_none() => {
                        self.primary_touch = Some(*id);
                        out.push(egui::Event::PointerMoved(p));
                        out.push(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: true, modifiers: self.mods });
                    }
                    egui::TouchPhase::Move if self.primary_touch == Some(*id) => out.push(egui::Event::PointerMoved(p)),
                    egui::TouchPhase::End | egui::TouchPhase::Cancel if self.primary_touch == Some(*id) => {
                        self.primary_touch = None;
                        out.push(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: false, modifiers: self.mods });
                        out.push(egui::Event::PointerGone);
                    }
                    _ => {}
                }
            }
            ClientMsg::Focus { on } => {
                self.focused = *on;
                out.push(egui::Event::WindowFocused(*on));
            }
            ClientMsg::Hello { .. } | ClientMsg::Resize { .. } | ClientMsg::Ack { .. } | ClientMsg::TakeControl | ClientMsg::Quality { .. } | ClientMsg::Drop { .. } => {}
        }
    }
}

/// The CSS cursor for egui's.
pub fn css_cursor(icon: egui::CursorIcon) -> &'static str {
    use egui::CursorIcon as C;
    match icon {
        C::Default => "default",
        C::None => "none",
        C::ContextMenu => "context-menu",
        C::Help => "help",
        C::PointingHand => "pointer",
        C::Progress => "progress",
        C::Wait => "wait",
        C::Cell => "cell",
        C::Crosshair => "crosshair",
        C::Text => "text",
        C::VerticalText => "vertical-text",
        C::Alias => "alias",
        C::Copy => "copy",
        C::Move => "move",
        C::NoDrop => "no-drop",
        C::NotAllowed => "not-allowed",
        C::Grab => "grab",
        C::Grabbing => "grabbing",
        C::AllScroll => "all-scroll",
        C::ResizeHorizontal => "ew-resize",
        C::ResizeNeSw => "nesw-resize",
        C::ResizeNwSe => "nwse-resize",
        C::ResizeVertical => "ns-resize",
        C::ResizeEast => "e-resize",
        C::ResizeSouthEast => "se-resize",
        C::ResizeSouth => "s-resize",
        C::ResizeSouthWest => "sw-resize",
        C::ResizeWest => "w-resize",
        C::ResizeNorthWest => "nw-resize",
        C::ResizeNorth => "n-resize",
        C::ResizeNorthEast => "ne-resize",
        C::ResizeColumn => "col-resize",
        C::ResizeRow => "row-resize",
        C::ZoomIn => "zoom-in",
        C::ZoomOut => "zoom-out",
    }
}