Skip to main content

brep_app/automation/
pointer.rs

1//! The stateful virtual pointer and keyboard (§6): position, held buttons and
2//! modifiers persist across frames; each input command becomes one or more
3//! `egui::Event`s pushed into the frame's `RawInput`.
4use serde::{Deserialize, Serialize};
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
7#[serde(rename_all = "snake_case")]
8pub enum Button {
9    Primary,
10    Secondary,
11    Middle,
12    Extra1,
13    Extra2,
14}
15
16impl Button {
17    pub fn egui(self) -> egui::PointerButton {
18        match self {
19            Button::Primary => egui::PointerButton::Primary,
20            Button::Secondary => egui::PointerButton::Secondary,
21            Button::Middle => egui::PointerButton::Middle,
22            Button::Extra1 => egui::PointerButton::Extra1,
23            Button::Extra2 => egui::PointerButton::Extra2,
24        }
25    }
26    fn index(self) -> usize {
27        self as usize
28    }
29}
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
32#[serde(rename_all = "snake_case")]
33pub enum WheelUnit {
34    Point,
35    Line,
36    Page,
37}
38
39#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
40#[serde(deny_unknown_fields)]
41pub struct Modifiers {
42    #[serde(default)]
43    pub ctrl: bool,
44    #[serde(default)]
45    pub shift: bool,
46    #[serde(default)]
47    pub alt: bool,
48    /// Cmd on macOS; treated as Ctrl elsewhere.
49    #[serde(default)]
50    pub command: bool,
51}
52
53impl Modifiers {
54    /// The egui modifiers off macOS: `ctrl` and `command` are one key.
55    pub fn egui(self) -> egui::Modifiers {
56        self.egui_for(false)
57    }
58
59    /// The egui modifiers as the platform's runner reports them. On macOS
60    /// (`mac`, see `platform_set`) Ctrl and Cmd are two keys: `ctrl` is
61    /// Control alone, `command` is Cmd (`mac_cmd` and egui's `command`), as
62    /// egui-winit reports them there.
63    pub fn egui_for(self, mac: bool) -> egui::Modifiers {
64        if mac {
65            egui::Modifiers {
66                alt: self.alt,
67                ctrl: self.ctrl,
68                shift: self.shift,
69                mac_cmd: self.command,
70                command: self.command,
71            }
72        } else {
73            egui::Modifiers {
74                alt: self.alt,
75                ctrl: self.ctrl || self.command,
76                shift: self.shift,
77                mac_cmd: self.command,
78                command: self.ctrl || self.command,
79            }
80        }
81    }
82}
83
84/// The operating system `platform_set` emulates.
85#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
86#[serde(rename_all = "snake_case")]
87pub enum Platform {
88    Mac,
89    Windows,
90    Linux,
91}
92
93impl Platform {
94    pub fn os(self) -> egui::os::OperatingSystem {
95        match self {
96            Self::Mac => egui::os::OperatingSystem::Mac,
97            Self::Windows => egui::os::OperatingSystem::Windows,
98            Self::Linux => egui::os::OperatingSystem::Nix,
99        }
100    }
101}
102
103fn touch_event(device: u64, id: u64, phase: egui::TouchPhase, pos: egui::Pos2) -> egui::Event {
104    egui::Event::Touch { device_id: egui::TouchDeviceId(device), id: egui::TouchId(id), phase, pos, force: None }
105}
106
107/// The pointer as reported to callers.
108#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
109pub struct PointerState {
110    /// Position in egui points, `null` when the pointer is not over the surface.
111    pub pos: Option<[f32; 2]>,
112    pub buttons: Vec<Button>,
113    pub modifiers: Modifiers,
114}
115
116/// egui's multi-click window: a release less than this after the last click,
117/// within `max_click_dist` of it, is a double click, and one less than TWICE
118/// this after the click before that is a triple (`InputOptions` default,
119/// `egui::input_state::PointerState::begin_pass`). The app keeps the default;
120/// `the_multi_click_window_is_egui_s` pins the copy.
121pub const MULTI_CLICK_WINDOW: f64 = 0.3;
122
123/// egui's click limits (`InputOptions` defaults): a release is a click only
124/// if the pointer stayed within this many points of the press ...
125pub const CLICK_DIST: f32 = 6.0;
126/// ... and the button was down no longer than this.
127pub const CLICK_DURATION: f64 = 0.8;
128
129#[derive(Debug, Clone, Default)]
130pub struct Pointer {
131    pub pos: Option<egui::Pos2>,
132    pub buttons: [bool; 5],
133    pub modifiers: Modifiers,
134    /// The emulated OS (`platform_set`); `None` keeps the host's. Applied to
135    /// egui (`Context::set_os`) by `drain_input`, and it decides how
136    /// [`Modifiers`] map to egui's.
137    pub platform: Option<Platform>,
138    /// Whether the last pass's `raw.modifiers` were this pointer's (see
139    /// `drain_input`): the user's own modifiers apply otherwise.
140    pub modifiers_applied: bool,
141    /// egui's clock for the frame being drained, set by
142    /// [`drain_input`](crate::automation::queue::AutomationQueue::drain_input)
143    /// before the frame's commands run.
144    pub now: f64,
145    /// Set by [`click_gap`](Self::click_gap): the queue replaces egui's
146    /// `PointerState` with a fresh one after this frame's commands.
147    pub reset_clicks: bool,
148    /// egui time of the last injected release that egui counts as a CLICK.
149    /// A drag's release is not one, and must not make the next click wait.
150    released: Option<f64>,
151    /// Where and when the held button went down, and whether the pointer has
152    /// since left [`CLICK_DIST`] of it: egui's own test for a click.
153    press: Option<(egui::Pos2, f64)>,
154    moved_far: bool,
155    /// The 3D viewport rect of the last frame, set by `drain_input` before
156    /// the frame's commands run: `touch` maps viewport-relative points
157    /// through it.
158    pub view: Option<egui::Rect>,
159    /// The touch contacts held down (`touch`), in the order they started,
160    /// at their last position in egui points.
161    touches: Vec<TouchContact>,
162}
163
164/// One finger the virtual touch screen holds down.
165#[derive(Debug, Clone, Copy, PartialEq)]
166struct TouchContact {
167    device: u64,
168    id: u64,
169    pos: egui::Pos2,
170}
171
172/// A touch contact's phase, as the platform reports it.
173#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
174#[serde(rename_all = "snake_case")]
175pub enum TouchPhase {
176    /// The finger touches down: a new contact id on its device.
177    Start,
178    /// A held contact moves.
179    Move,
180    /// The finger lifts.
181    End,
182    /// The platform takes the contact away (a system gesture, a lost
183    /// focus): no click and no release action follows.
184    Cancel,
185}
186
187/// Which space a touch point is in.
188#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
189#[serde(rename_all = "snake_case")]
190pub enum TouchSpace {
191    /// Points from the 3D viewport's top-left corner (the `viewport`
192    /// screenshot region): what a client that shows only that capture sees.
193    #[default]
194    Viewport,
195    /// egui points from the app surface's top-left, as `pointer_move` takes.
196    Surface,
197}
198
199/// One contact's change in a touch batch.
200#[derive(Debug, Clone, Copy, Deserialize, schemars::JsonSchema)]
201#[serde(deny_unknown_fields)]
202pub struct TouchPoint {
203    /// The contact id: stable from `start` to `end`/`cancel`, unique among
204    /// the device's held contacts. A host forwards the platform's own
205    /// (a browser `Touch.identifier`, a UITouch's).
206    pub id: u64,
207    pub phase: TouchPhase,
208    pub x: f32,
209    pub y: f32,
210}
211
212/// A held contact, as `touch` reports it.
213#[derive(Debug, Clone, Copy, Serialize, schemars::JsonSchema)]
214pub struct HeldTouch {
215    pub device: u64,
216    pub id: u64,
217    /// Its position in the batch's space.
218    pub x: f32,
219    pub y: f32,
220}
221
222const ALL_BUTTONS: [Button; 5] = [Button::Primary, Button::Secondary, Button::Middle, Button::Extra1, Button::Extra2];
223
224impl Pointer {
225    pub fn state(&self) -> PointerState {
226        PointerState {
227            pos: self.pos.map(|p| [p.x, p.y]),
228            buttons: ALL_BUTTONS.iter().copied().filter(|b| self.buttons[b.index()]).collect(),
229            modifiers: self.modifiers,
230        }
231    }
232
233    pub fn moved(&mut self, x: f32, y: f32, out: &mut Vec<egui::Event>) {
234        let pos = egui::pos2(x, y);
235        self.pos = Some(pos);
236        if let Some((origin, _)) = self.press {
237            self.moved_far |= origin.distance(pos) > CLICK_DIST;
238        }
239        out.push(egui::Event::PointerMoved(pos));
240    }
241
242    pub fn button(&mut self, button: Button, pressed: bool, out: &mut Vec<egui::Event>) -> Result<(), String> {
243        let pos = self.pos.ok_or("the pointer has no position yet: move it first")?;
244        self.buttons[button.index()] = pressed;
245        let now = self.now;
246        if pressed {
247            self.press = Some((pos, now));
248            self.moved_far = false;
249        } else if let Some((_, down)) = self.press.take() {
250            if !self.moved_far && now - down <= CLICK_DURATION {
251                self.released = Some(now);
252            }
253        }
254        out.push(egui::Event::PointerButton { pos, button: button.egui(), pressed, modifiers: self.egui_modifiers() });
255        Ok(())
256    }
257
258    /// Start a NEW click sequence: forget egui's click history when an
259    /// injected click is still inside its multi-click window. Returns whether
260    /// it did.
261    ///
262    /// egui counts clicks by time, and checks the place only against the LAST
263    /// click, so a click on one widget a few frames (1/60 s each headless)
264    /// before a double click on another makes the double a TRIPLE, and a
265    /// widget clicked twice by two scripted single clicks reads the second as
266    /// a double (ecad-kicad-dialog-folders-2026-09-23).
267    ///
268    /// The history is egui's `PointerState`, whose click times are private;
269    /// the queue swaps in `PointerState::default()` (its options are refreshed
270    /// every pass). egui's CLOCK is not touched: the first version jumped it
271    /// past the window instead, and the app's own timers saw the jump, so a
272    /// toast aged 0.6 s per click (ecad-mcp-click-count-export-wording).
273    /// The window is the TRIPLE one, twice the double's: the second click of
274    /// a new double looks two clicks back. Nothing is reset while a button is
275    /// held (a drag in progress lives in the same state), or when the last
276    /// click is already outside the window.
277    pub fn click_gap(&mut self) -> bool {
278        let recent = self.released.is_some_and(|t| self.now - t < 2.0 * MULTI_CLICK_WINDOW);
279        if !recent || self.buttons.iter().any(|&b| b) {
280            return false;
281        }
282        self.released = None;
283        self.reset_clicks = true;
284        true
285    }
286
287    pub fn gone(&mut self, out: &mut Vec<egui::Event>) {
288        self.pos = None;
289        self.buttons = [false; 5];
290        out.push(egui::Event::PointerGone);
291    }
292
293    pub fn wheel(&mut self, dx: f32, dy: f32, unit: WheelUnit, out: &mut Vec<egui::Event>) {
294        let unit = match unit {
295            WheelUnit::Point => egui::MouseWheelUnit::Point,
296            WheelUnit::Line => egui::MouseWheelUnit::Line,
297            WheelUnit::Page => egui::MouseWheelUnit::Page,
298        };
299        out.push(egui::Event::MouseWheel {
300            unit,
301            delta: egui::vec2(dx, dy),
302            phase: egui::TouchPhase::Move,
303            modifiers: self.egui_modifiers(),
304        });
305    }
306
307    /// The held modifiers as this pointer's platform reports them.
308    pub fn egui_modifiers(&self) -> egui::Modifiers {
309        self.modifiers.egui_for(self.platform == Some(Platform::Mac))
310    }
311
312    pub fn set_modifiers(&mut self, m: Modifiers) {
313        self.modifiers = m;
314    }
315
316    pub fn key(&mut self, name: &str, pressed: bool, repeat: bool, out: &mut Vec<egui::Event>) -> Result<(), String> {
317        let key = egui::Key::from_name(name).ok_or_else(|| format!("unknown key `{name}` (egui key names: A..Z, 0..9, Enter, Escape, Tab, Space, Backspace, Delete, ArrowLeft/Right/Up/Down, Home, End, PageUp/Down, F1..F12, Minus, Plus, …)"))?;
318        out.push(egui::Event::Key { key, physical_key: None, pressed, repeat, modifiers: self.egui_modifiers() });
319        Ok(())
320    }
321
322    /// One touch batch: every contact change of one platform touch event,
323    /// delivered in ONE frame as egui `Event::Touch`es on touch device
324    /// `device` (contact ids are unique per device).
325    /// The whole batch is checked first and nothing is sent if any change
326    /// is invalid: a `start` of a held id, a `move`/`end`/`cancel` of an id
327    /// not held, a non-finite point, or viewport space with no viewport
328    /// drawn. `cancel_all` cancels every contact still held on the device
329    /// after the batch's own changes. Returns the device's held contacts in
330    /// the batch's space.
331    pub fn touch(&mut self, device: u64, space: TouchSpace, points: &[TouchPoint], cancel_all: bool, out: &mut Vec<egui::Event>) -> Result<Vec<HeldTouch>, String> {
332        let origin = match space {
333            TouchSpace::Surface => egui::Vec2::ZERO,
334            TouchSpace::Viewport => self.view.ok_or("no viewport rect: the 3D view was not drawn last frame (open a document, or send `space: \"surface\"`)")?.min.to_vec2(),
335        };
336        let mut held = self.touches.clone();
337        let mut events = Vec::with_capacity(points.len());
338        for (i, p) in points.iter().enumerate() {
339            if !(p.x.is_finite() && p.y.is_finite()) {
340                return Err(format!("touch {i} (id {}): the point is not finite", p.id));
341            }
342            let pos = egui::pos2(p.x, p.y) + origin;
343            let index = held.iter().position(|c| c.device == device && c.id == p.id);
344            let phase = match (p.phase, index) {
345                (TouchPhase::Start, Some(_)) => return Err(format!("touch {i}: contact {} is already down on device {device} (end or cancel it first)", p.id)),
346                (TouchPhase::Start, None) => {
347                    held.push(TouchContact { device, id: p.id, pos });
348                    egui::TouchPhase::Start
349                }
350                (_, None) => return Err(format!("touch {i}: contact {} is not down on device {device} (`start` it first)", p.id)),
351                (TouchPhase::Move, Some(k)) => {
352                    held[k].pos = pos;
353                    egui::TouchPhase::Move
354                }
355                (TouchPhase::End | TouchPhase::Cancel, Some(k)) => {
356                    held.remove(k);
357                    if p.phase == TouchPhase::End { egui::TouchPhase::End } else { egui::TouchPhase::Cancel }
358                }
359            };
360            events.push(touch_event(device, p.id, phase, pos));
361        }
362        if cancel_all {
363            held.retain(|c| {
364                let mine = c.device == device;
365                if mine {
366                    events.push(touch_event(device, c.id, egui::TouchPhase::Cancel, c.pos));
367                }
368                !mine
369            });
370        }
371        self.touches = held;
372        out.extend(events);
373        Ok(self
374            .touches
375            .iter()
376            .filter(|c| c.device == device)
377            .map(|c| HeldTouch { device, id: c.id, x: c.pos.x - origin.x, y: c.pos.y - origin.y })
378            .collect())
379    }
380
381    pub fn text(&mut self, text: &str, out: &mut Vec<egui::Event>) {
382        if !text.is_empty() {
383            out.push(egui::Event::Text(text.to_string()));
384        }
385    }
386}