1use 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 #[serde(default)]
50 pub command: bool,
51}
52
53impl Modifiers {
54 pub fn egui(self) -> egui::Modifiers {
56 self.egui_for(false)
57 }
58
59 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#[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#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
109pub struct PointerState {
110 pub pos: Option<[f32; 2]>,
112 pub buttons: Vec<Button>,
113 pub modifiers: Modifiers,
114}
115
116pub const MULTI_CLICK_WINDOW: f64 = 0.3;
122
123pub const CLICK_DIST: f32 = 6.0;
126pub 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 pub platform: Option<Platform>,
138 pub modifiers_applied: bool,
141 pub now: f64,
145 pub reset_clicks: bool,
148 released: Option<f64>,
151 press: Option<(egui::Pos2, f64)>,
154 moved_far: bool,
155 pub view: Option<egui::Rect>,
159 touches: Vec<TouchContact>,
162}
163
164#[derive(Debug, Clone, Copy, PartialEq)]
166struct TouchContact {
167 device: u64,
168 id: u64,
169 pos: egui::Pos2,
170}
171
172#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
174#[serde(rename_all = "snake_case")]
175pub enum TouchPhase {
176 Start,
178 Move,
180 End,
182 Cancel,
185}
186
187#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
189#[serde(rename_all = "snake_case")]
190pub enum TouchSpace {
191 #[default]
194 Viewport,
195 Surface,
197}
198
199#[derive(Debug, Clone, Copy, Deserialize, schemars::JsonSchema)]
201#[serde(deny_unknown_fields)]
202pub struct TouchPoint {
203 pub id: u64,
207 pub phase: TouchPhase,
208 pub x: f32,
209 pub y: f32,
210}
211
212#[derive(Debug, Clone, Copy, Serialize, schemars::JsonSchema)]
214pub struct HeldTouch {
215 pub device: u64,
216 pub id: u64,
217 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 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 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 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}