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
103/// The pointer as reported to callers.
104#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
105pub struct PointerState {
106    /// Position in egui points, `null` when the pointer is not over the surface.
107    pub pos: Option<[f32; 2]>,
108    pub buttons: Vec<Button>,
109    pub modifiers: Modifiers,
110}
111
112/// egui's multi-click window: a release less than this after the last click,
113/// within `max_click_dist` of it, is a double click, and one less than TWICE
114/// this after the click before that is a triple (`InputOptions` default,
115/// `egui::input_state::PointerState::begin_pass`). The app keeps the default;
116/// `the_multi_click_window_is_egui_s` pins the copy.
117pub const MULTI_CLICK_WINDOW: f64 = 0.3;
118
119/// egui's click limits (`InputOptions` defaults): a release is a click only
120/// if the pointer stayed within this many points of the press ...
121pub const CLICK_DIST: f32 = 6.0;
122/// ... and the button was down no longer than this.
123pub const CLICK_DURATION: f64 = 0.8;
124
125#[derive(Debug, Clone, Default)]
126pub struct Pointer {
127    pub pos: Option<egui::Pos2>,
128    pub buttons: [bool; 5],
129    pub modifiers: Modifiers,
130    /// The emulated OS (`platform_set`); `None` keeps the host's. Applied to
131    /// egui (`Context::set_os`) by `drain_input`, and it decides how
132    /// [`Modifiers`] map to egui's.
133    pub platform: Option<Platform>,
134    /// Whether the last pass's `raw.modifiers` were this pointer's (see
135    /// `drain_input`): the user's own modifiers apply otherwise.
136    pub modifiers_applied: bool,
137    /// egui's clock for the frame being drained, set by
138    /// [`drain_input`](crate::automation::queue::AutomationQueue::drain_input)
139    /// before the frame's commands run.
140    pub now: f64,
141    /// Set by [`click_gap`](Self::click_gap): the queue replaces egui's
142    /// `PointerState` with a fresh one after this frame's commands.
143    pub reset_clicks: bool,
144    /// egui time of the last injected release that egui counts as a CLICK.
145    /// A drag's release is not one, and must not make the next click wait.
146    released: Option<f64>,
147    /// Where and when the held button went down, and whether the pointer has
148    /// since left [`CLICK_DIST`] of it: egui's own test for a click.
149    press: Option<(egui::Pos2, f64)>,
150    moved_far: bool,
151}
152
153const ALL_BUTTONS: [Button; 5] = [Button::Primary, Button::Secondary, Button::Middle, Button::Extra1, Button::Extra2];
154
155impl Pointer {
156    pub fn state(&self) -> PointerState {
157        PointerState {
158            pos: self.pos.map(|p| [p.x, p.y]),
159            buttons: ALL_BUTTONS.iter().copied().filter(|b| self.buttons[b.index()]).collect(),
160            modifiers: self.modifiers,
161        }
162    }
163
164    pub fn moved(&mut self, x: f32, y: f32, out: &mut Vec<egui::Event>) {
165        let pos = egui::pos2(x, y);
166        self.pos = Some(pos);
167        if let Some((origin, _)) = self.press {
168            self.moved_far |= origin.distance(pos) > CLICK_DIST;
169        }
170        out.push(egui::Event::PointerMoved(pos));
171    }
172
173    pub fn button(&mut self, button: Button, pressed: bool, out: &mut Vec<egui::Event>) -> Result<(), String> {
174        let pos = self.pos.ok_or("the pointer has no position yet: move it first")?;
175        self.buttons[button.index()] = pressed;
176        let now = self.now;
177        if pressed {
178            self.press = Some((pos, now));
179            self.moved_far = false;
180        } else if let Some((_, down)) = self.press.take() {
181            if !self.moved_far && now - down <= CLICK_DURATION {
182                self.released = Some(now);
183            }
184        }
185        out.push(egui::Event::PointerButton { pos, button: button.egui(), pressed, modifiers: self.egui_modifiers() });
186        Ok(())
187    }
188
189    /// Start a NEW click sequence: forget egui's click history when an
190    /// injected click is still inside its multi-click window. Returns whether
191    /// it did.
192    ///
193    /// egui counts clicks by time, and checks the place only against the LAST
194    /// click, so a click on one widget a few frames (1/60 s each headless)
195    /// before a double click on another makes the double a TRIPLE, and a
196    /// widget clicked twice by two scripted single clicks reads the second as
197    /// a double (ecad-kicad-dialog-folders-2026-09-23).
198    ///
199    /// The history is egui's `PointerState`, whose click times are private;
200    /// the queue swaps in `PointerState::default()` (its options are refreshed
201    /// every pass). egui's CLOCK is not touched: the first version jumped it
202    /// past the window instead, and the app's own timers saw the jump, so a
203    /// toast aged 0.6 s per click (ecad-mcp-click-count-export-wording).
204    /// The window is the TRIPLE one, twice the double's: the second click of
205    /// a new double looks two clicks back. Nothing is reset while a button is
206    /// held (a drag in progress lives in the same state), or when the last
207    /// click is already outside the window.
208    pub fn click_gap(&mut self) -> bool {
209        let recent = self.released.is_some_and(|t| self.now - t < 2.0 * MULTI_CLICK_WINDOW);
210        if !recent || self.buttons.iter().any(|&b| b) {
211            return false;
212        }
213        self.released = None;
214        self.reset_clicks = true;
215        true
216    }
217
218    pub fn gone(&mut self, out: &mut Vec<egui::Event>) {
219        self.pos = None;
220        self.buttons = [false; 5];
221        out.push(egui::Event::PointerGone);
222    }
223
224    pub fn wheel(&mut self, dx: f32, dy: f32, unit: WheelUnit, out: &mut Vec<egui::Event>) {
225        let unit = match unit {
226            WheelUnit::Point => egui::MouseWheelUnit::Point,
227            WheelUnit::Line => egui::MouseWheelUnit::Line,
228            WheelUnit::Page => egui::MouseWheelUnit::Page,
229        };
230        out.push(egui::Event::MouseWheel {
231            unit,
232            delta: egui::vec2(dx, dy),
233            phase: egui::TouchPhase::Move,
234            modifiers: self.egui_modifiers(),
235        });
236    }
237
238    /// The held modifiers as this pointer's platform reports them.
239    pub fn egui_modifiers(&self) -> egui::Modifiers {
240        self.modifiers.egui_for(self.platform == Some(Platform::Mac))
241    }
242
243    pub fn set_modifiers(&mut self, m: Modifiers) {
244        self.modifiers = m;
245    }
246
247    pub fn key(&mut self, name: &str, pressed: bool, repeat: bool, out: &mut Vec<egui::Event>) -> Result<(), String> {
248        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, …)"))?;
249        out.push(egui::Event::Key { key, physical_key: None, pressed, repeat, modifiers: self.egui_modifiers() });
250        Ok(())
251    }
252
253    pub fn text(&mut self, text: &str, out: &mut Vec<egui::Event>) {
254        if !text.is_empty() {
255            out.push(egui::Event::Text(text.to_string()));
256        }
257    }
258}