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
//! The stateful virtual pointer and keyboard (§6): position, held buttons and
//! modifiers persist across frames; each input command becomes one or more
//! `egui::Event`s pushed into the frame's `RawInput`.
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum Button {
Primary,
Secondary,
Middle,
Extra1,
Extra2,
}
impl Button {
pub fn egui(self) -> egui::PointerButton {
match self {
Button::Primary => egui::PointerButton::Primary,
Button::Secondary => egui::PointerButton::Secondary,
Button::Middle => egui::PointerButton::Middle,
Button::Extra1 => egui::PointerButton::Extra1,
Button::Extra2 => egui::PointerButton::Extra2,
}
}
fn index(self) -> usize {
self as usize
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum WheelUnit {
Point,
Line,
Page,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Modifiers {
#[serde(default)]
pub ctrl: bool,
#[serde(default)]
pub shift: bool,
#[serde(default)]
pub alt: bool,
/// Cmd on macOS; treated as Ctrl elsewhere.
#[serde(default)]
pub command: bool,
}
impl Modifiers {
/// The egui modifiers off macOS: `ctrl` and `command` are one key.
pub fn egui(self) -> egui::Modifiers {
self.egui_for(false)
}
/// The egui modifiers as the platform's runner reports them. On macOS
/// (`mac`, see `platform_set`) Ctrl and Cmd are two keys: `ctrl` is
/// Control alone, `command` is Cmd (`mac_cmd` and egui's `command`), as
/// egui-winit reports them there.
pub fn egui_for(self, mac: bool) -> egui::Modifiers {
if mac {
egui::Modifiers {
alt: self.alt,
ctrl: self.ctrl,
shift: self.shift,
mac_cmd: self.command,
command: self.command,
}
} else {
egui::Modifiers {
alt: self.alt,
ctrl: self.ctrl || self.command,
shift: self.shift,
mac_cmd: self.command,
command: self.ctrl || self.command,
}
}
}
}
/// The operating system `platform_set` emulates.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum Platform {
Mac,
Windows,
Linux,
}
impl Platform {
pub fn os(self) -> egui::os::OperatingSystem {
match self {
Self::Mac => egui::os::OperatingSystem::Mac,
Self::Windows => egui::os::OperatingSystem::Windows,
Self::Linux => egui::os::OperatingSystem::Nix,
}
}
}
fn touch_event(device: u64, id: u64, phase: egui::TouchPhase, pos: egui::Pos2) -> egui::Event {
egui::Event::Touch { device_id: egui::TouchDeviceId(device), id: egui::TouchId(id), phase, pos, force: None }
}
/// The pointer as reported to callers.
#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
pub struct PointerState {
/// Position in egui points, `null` when the pointer is not over the surface.
pub pos: Option<[f32; 2]>,
pub buttons: Vec<Button>,
pub modifiers: Modifiers,
}
/// egui's multi-click window: a release less than this after the last click,
/// within `max_click_dist` of it, is a double click, and one less than TWICE
/// this after the click before that is a triple (`InputOptions` default,
/// `egui::input_state::PointerState::begin_pass`). The app keeps the default;
/// `the_multi_click_window_is_egui_s` pins the copy.
pub const MULTI_CLICK_WINDOW: f64 = 0.3;
/// egui's click limits (`InputOptions` defaults): a release is a click only
/// if the pointer stayed within this many points of the press ...
pub const CLICK_DIST: f32 = 6.0;
/// ... and the button was down no longer than this.
pub const CLICK_DURATION: f64 = 0.8;
#[derive(Debug, Clone, Default)]
pub struct Pointer {
pub pos: Option<egui::Pos2>,
pub buttons: [bool; 5],
pub modifiers: Modifiers,
/// The emulated OS (`platform_set`); `None` keeps the host's. Applied to
/// egui (`Context::set_os`) by `drain_input`, and it decides how
/// [`Modifiers`] map to egui's.
pub platform: Option<Platform>,
/// Whether the last pass's `raw.modifiers` were this pointer's (see
/// `drain_input`): the user's own modifiers apply otherwise.
pub modifiers_applied: bool,
/// egui's clock for the frame being drained, set by
/// [`drain_input`](crate::automation::queue::AutomationQueue::drain_input)
/// before the frame's commands run.
pub now: f64,
/// Set by [`click_gap`](Self::click_gap): the queue replaces egui's
/// `PointerState` with a fresh one after this frame's commands.
pub reset_clicks: bool,
/// egui time of the last injected release that egui counts as a CLICK.
/// A drag's release is not one, and must not make the next click wait.
released: Option<f64>,
/// Where and when the held button went down, and whether the pointer has
/// since left [`CLICK_DIST`] of it: egui's own test for a click.
press: Option<(egui::Pos2, f64)>,
moved_far: bool,
/// The 3D viewport rect of the last frame, set by `drain_input` before
/// the frame's commands run: `touch` maps viewport-relative points
/// through it.
pub view: Option<egui::Rect>,
/// The touch contacts held down (`touch`), in the order they started,
/// at their last position in egui points.
touches: Vec<TouchContact>,
}
/// One finger the virtual touch screen holds down.
#[derive(Debug, Clone, Copy, PartialEq)]
struct TouchContact {
device: u64,
id: u64,
pos: egui::Pos2,
}
/// A touch contact's phase, as the platform reports it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum TouchPhase {
/// The finger touches down: a new contact id on its device.
Start,
/// A held contact moves.
Move,
/// The finger lifts.
End,
/// The platform takes the contact away (a system gesture, a lost
/// focus): no click and no release action follows.
Cancel,
}
/// Which space a touch point is in.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum TouchSpace {
/// Points from the 3D viewport's top-left corner (the `viewport`
/// screenshot region): what a client that shows only that capture sees.
#[default]
Viewport,
/// egui points from the app surface's top-left, as `pointer_move` takes.
Surface,
}
/// One contact's change in a touch batch.
#[derive(Debug, Clone, Copy, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct TouchPoint {
/// The contact id: stable from `start` to `end`/`cancel`, unique among
/// the device's held contacts. A host forwards the platform's own
/// (a browser `Touch.identifier`, a UITouch's).
pub id: u64,
pub phase: TouchPhase,
pub x: f32,
pub y: f32,
}
/// A held contact, as `touch` reports it.
#[derive(Debug, Clone, Copy, Serialize, schemars::JsonSchema)]
pub struct HeldTouch {
pub device: u64,
pub id: u64,
/// Its position in the batch's space.
pub x: f32,
pub y: f32,
}
const ALL_BUTTONS: [Button; 5] = [Button::Primary, Button::Secondary, Button::Middle, Button::Extra1, Button::Extra2];
impl Pointer {
pub fn state(&self) -> PointerState {
PointerState {
pos: self.pos.map(|p| [p.x, p.y]),
buttons: ALL_BUTTONS.iter().copied().filter(|b| self.buttons[b.index()]).collect(),
modifiers: self.modifiers,
}
}
pub fn moved(&mut self, x: f32, y: f32, out: &mut Vec<egui::Event>) {
let pos = egui::pos2(x, y);
self.pos = Some(pos);
if let Some((origin, _)) = self.press {
self.moved_far |= origin.distance(pos) > CLICK_DIST;
}
out.push(egui::Event::PointerMoved(pos));
}
pub fn button(&mut self, button: Button, pressed: bool, out: &mut Vec<egui::Event>) -> Result<(), String> {
let pos = self.pos.ok_or("the pointer has no position yet: move it first")?;
self.buttons[button.index()] = pressed;
let now = self.now;
if pressed {
self.press = Some((pos, now));
self.moved_far = false;
} else if let Some((_, down)) = self.press.take() {
if !self.moved_far && now - down <= CLICK_DURATION {
self.released = Some(now);
}
}
out.push(egui::Event::PointerButton { pos, button: button.egui(), pressed, modifiers: self.egui_modifiers() });
Ok(())
}
/// Start a NEW click sequence: forget egui's click history when an
/// injected click is still inside its multi-click window. Returns whether
/// it did.
///
/// egui counts clicks by time, and checks the place only against the LAST
/// click, so a click on one widget a few frames (1/60 s each headless)
/// before a double click on another makes the double a TRIPLE, and a
/// widget clicked twice by two scripted single clicks reads the second as
/// a double (ecad-kicad-dialog-folders-2026-09-23).
///
/// The history is egui's `PointerState`, whose click times are private;
/// the queue swaps in `PointerState::default()` (its options are refreshed
/// every pass). egui's CLOCK is not touched: the first version jumped it
/// past the window instead, and the app's own timers saw the jump, so a
/// toast aged 0.6 s per click (ecad-mcp-click-count-export-wording).
/// The window is the TRIPLE one, twice the double's: the second click of
/// a new double looks two clicks back. Nothing is reset while a button is
/// held (a drag in progress lives in the same state), or when the last
/// click is already outside the window.
pub fn click_gap(&mut self) -> bool {
let recent = self.released.is_some_and(|t| self.now - t < 2.0 * MULTI_CLICK_WINDOW);
if !recent || self.buttons.iter().any(|&b| b) {
return false;
}
self.released = None;
self.reset_clicks = true;
true
}
pub fn gone(&mut self, out: &mut Vec<egui::Event>) {
self.pos = None;
self.buttons = [false; 5];
out.push(egui::Event::PointerGone);
}
pub fn wheel(&mut self, dx: f32, dy: f32, unit: WheelUnit, out: &mut Vec<egui::Event>) {
let unit = match unit {
WheelUnit::Point => egui::MouseWheelUnit::Point,
WheelUnit::Line => egui::MouseWheelUnit::Line,
WheelUnit::Page => egui::MouseWheelUnit::Page,
};
out.push(egui::Event::MouseWheel {
unit,
delta: egui::vec2(dx, dy),
phase: egui::TouchPhase::Move,
modifiers: self.egui_modifiers(),
});
}
/// The held modifiers as this pointer's platform reports them.
pub fn egui_modifiers(&self) -> egui::Modifiers {
self.modifiers.egui_for(self.platform == Some(Platform::Mac))
}
pub fn set_modifiers(&mut self, m: Modifiers) {
self.modifiers = m;
}
pub fn key(&mut self, name: &str, pressed: bool, repeat: bool, out: &mut Vec<egui::Event>) -> Result<(), String> {
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, …)"))?;
out.push(egui::Event::Key { key, physical_key: None, pressed, repeat, modifiers: self.egui_modifiers() });
Ok(())
}
/// One touch batch: every contact change of one platform touch event,
/// delivered in ONE frame as egui `Event::Touch`es on touch device
/// `device` (contact ids are unique per device).
/// The whole batch is checked first and nothing is sent if any change
/// is invalid: a `start` of a held id, a `move`/`end`/`cancel` of an id
/// not held, a non-finite point, or viewport space with no viewport
/// drawn. `cancel_all` cancels every contact still held on the device
/// after the batch's own changes. Returns the device's held contacts in
/// the batch's space.
pub fn touch(&mut self, device: u64, space: TouchSpace, points: &[TouchPoint], cancel_all: bool, out: &mut Vec<egui::Event>) -> Result<Vec<HeldTouch>, String> {
let origin = match space {
TouchSpace::Surface => egui::Vec2::ZERO,
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(),
};
let mut held = self.touches.clone();
let mut events = Vec::with_capacity(points.len());
for (i, p) in points.iter().enumerate() {
if !(p.x.is_finite() && p.y.is_finite()) {
return Err(format!("touch {i} (id {}): the point is not finite", p.id));
}
let pos = egui::pos2(p.x, p.y) + origin;
let index = held.iter().position(|c| c.device == device && c.id == p.id);
let phase = match (p.phase, index) {
(TouchPhase::Start, Some(_)) => return Err(format!("touch {i}: contact {} is already down on device {device} (end or cancel it first)", p.id)),
(TouchPhase::Start, None) => {
held.push(TouchContact { device, id: p.id, pos });
egui::TouchPhase::Start
}
(_, None) => return Err(format!("touch {i}: contact {} is not down on device {device} (`start` it first)", p.id)),
(TouchPhase::Move, Some(k)) => {
held[k].pos = pos;
egui::TouchPhase::Move
}
(TouchPhase::End | TouchPhase::Cancel, Some(k)) => {
held.remove(k);
if p.phase == TouchPhase::End { egui::TouchPhase::End } else { egui::TouchPhase::Cancel }
}
};
events.push(touch_event(device, p.id, phase, pos));
}
if cancel_all {
held.retain(|c| {
let mine = c.device == device;
if mine {
events.push(touch_event(device, c.id, egui::TouchPhase::Cancel, c.pos));
}
!mine
});
}
self.touches = held;
out.extend(events);
Ok(self
.touches
.iter()
.filter(|c| c.device == device)
.map(|c| HeldTouch { device, id: c.id, x: c.pos.x - origin.x, y: c.pos.y - origin.y })
.collect())
}
pub fn text(&mut self, text: &str, out: &mut Vec<egui::Event>) {
if !text.is_empty() {
out.push(egui::Event::Text(text.to_string()));
}
}
}