Skip to main content

eframe/web/
input.rs

1use super::{AppRunner, canvas_content_rect};
2
3pub fn pos_from_mouse_event(
4    canvas: &web_sys::HtmlCanvasElement,
5    event: &web_sys::MouseEvent,
6    ctx: &egui::Context,
7) -> egui::Pos2 {
8    let rect = canvas_content_rect(canvas);
9    let zoom_factor = ctx.zoom_factor();
10    egui::Pos2 {
11        x: (event.client_x() as f32 - rect.left()) / zoom_factor,
12        y: (event.client_y() as f32 - rect.top()) / zoom_factor,
13    }
14}
15
16pub fn button_from_mouse_event(event: &web_sys::MouseEvent) -> Option<egui::PointerButton> {
17    match event.button() {
18        0 => Some(egui::PointerButton::Primary),
19        1 => Some(egui::PointerButton::Middle),
20        2 => Some(egui::PointerButton::Secondary),
21        3 => Some(egui::PointerButton::Extra1),
22        4 => Some(egui::PointerButton::Extra2),
23        _ => None,
24    }
25}
26
27/// A single touch is translated to a pointer movement. When a second touch is added, the pointer
28/// should not jump to a different position. Therefore, we do not calculate the average position
29/// of all touches, but we keep using the same touch as long as it is available.
30pub fn primary_touch_pos(
31    runner: &mut AppRunner,
32    event: &web_sys::TouchEvent,
33) -> Option<(egui::Pos2, web_sys::Touch)> {
34    // On touchend we don't get anything in `touches`, but we still get `changed_touches`, so include those:
35    let all_touches: Vec<_> = core::iter::chain(
36        (0..event.touches().length()).filter_map(|i| event.touches().get(i)),
37        (0..event.changed_touches().length()).filter_map(|i| event.changed_touches().get(i)),
38    )
39    .collect();
40
41    if let Some(primary_touch) = runner.input.primary_touch {
42        // Is the primary touch is gone?
43        if !all_touches
44            .iter()
45            .any(|touch| primary_touch == egui::TouchId::from(touch.identifier()))
46        {
47            runner.input.primary_touch = None;
48        }
49    }
50
51    if runner.input.primary_touch.is_none() {
52        runner.input.primary_touch = all_touches
53            .first()
54            .map(|touch| egui::TouchId::from(touch.identifier()));
55    }
56
57    let primary_touch = runner.input.primary_touch;
58
59    if let Some(primary_touch) = primary_touch {
60        for touch in all_touches {
61            if primary_touch == egui::TouchId::from(touch.identifier()) {
62                let canvas_rect = canvas_content_rect(runner.canvas());
63                return Some((
64                    pos_from_touch(canvas_rect, &touch, runner.egui_ctx()),
65                    touch,
66                ));
67            }
68        }
69    }
70
71    None
72}
73
74fn pos_from_touch(
75    canvas_rect: egui::Rect,
76    touch: &web_sys::Touch,
77    egui_ctx: &egui::Context,
78) -> egui::Pos2 {
79    let zoom_factor = egui_ctx.zoom_factor();
80    egui::Pos2 {
81        x: (touch.client_x() as f32 - canvas_rect.left()) / zoom_factor,
82        y: (touch.client_y() as f32 - canvas_rect.top()) / zoom_factor,
83    }
84}
85
86pub fn push_touches(runner: &mut AppRunner, phase: egui::TouchPhase, event: &web_sys::TouchEvent) {
87    let canvas_rect = canvas_content_rect(runner.canvas());
88    for touch_idx in 0..event.changed_touches().length() {
89        if let Some(touch) = event.changed_touches().item(touch_idx) {
90            runner.input.raw.events.push(egui::Event::Touch {
91                device_id: egui::TouchDeviceId(0),
92                id: egui::TouchId::from(touch.identifier()),
93                phase,
94                pos: pos_from_touch(canvas_rect, &touch, runner.egui_ctx()),
95                force: Some(touch.force()),
96            });
97        }
98    }
99}
100
101/// The text input from a keyboard event (e.g. `X` when pressing the `X` key).
102pub fn text_from_keyboard_event(event: &web_sys::KeyboardEvent) -> Option<String> {
103    let key = event.key();
104
105    let is_function_key = key.starts_with('F') && key.len() > 1;
106    if is_function_key {
107        return None;
108    }
109
110    let is_control_key = matches!(
111        key.as_str(),
112        "Alt"
113      | "ArrowDown"
114      | "ArrowLeft"
115      | "ArrowRight"
116      | "ArrowUp"
117      | "Backspace"
118      | "BrowserBack"
119      | "BrowserFavorites"
120      | "BrowserForward"
121      | "BrowserHome"
122      | "BrowserRefresh"
123      | "BrowserSearch"
124      | "BrowserStop"
125      | "CapsLock"
126      | "Clear"
127      | "ContextMenu"
128      | "Control"
129      | "Delete"
130      | "Eject"
131      | "End"
132      | "Enter"
133      | "Esc"
134      | "Escape"
135      | "Fn"
136      | "GroupNext" // https://github.com/emilk/egui/issues/510
137      | "Help"
138      | "Home"
139      | "Insert"
140      | "LaunchApp1"
141      | "LaunchApp2"
142      | "LaunchMail"
143      | "MediaPlayPause"
144      | "MediaTrackNext"
145      | "MediaTrackPrevious"
146      | "MediaStop"
147      | "Meta"
148      | "NumLock"
149      | "PageDown"
150      | "PageUp"
151      | "Pause"
152      | "Power"
153      | "PrintScreen"
154      | "ScrollLock"
155      | "Shift"
156      | "Sleep"
157      | "Tab"
158      | "AudioVolumeDown"
159      | "AudioVolumeMute"
160      | "AudioVolumeUp"
161    );
162
163    if is_control_key {
164        return None;
165    }
166
167    Some(key)
168}
169
170/// Web sends all keys as strings, so it is up to us to figure out if it is
171/// a real text input or the name of a key.
172pub fn translate_key(key: &str) -> Option<egui::Key> {
173    egui::Key::from_name(key)
174}
175
176pub fn modifiers_from_kb_event(event: &web_sys::KeyboardEvent) -> egui::Modifiers {
177    egui::Modifiers {
178        alt: event.alt_key(),
179        ctrl: event.ctrl_key(),
180        shift: event.shift_key(),
181
182        // Ideally we should know if we are running or mac or not,
183        // but this works good enough for now.
184        mac_cmd: event.meta_key(),
185
186        // Ideally we should know if we are running or mac or not,
187        // but this works good enough for now.
188        command: event.ctrl_key() || event.meta_key(),
189    }
190}
191
192pub fn modifiers_from_mouse_event(event: &web_sys::MouseEvent) -> egui::Modifiers {
193    egui::Modifiers {
194        alt: event.alt_key(),
195        ctrl: event.ctrl_key(),
196        shift: event.shift_key(),
197
198        // Ideally we should know if we are running or mac or not,
199        // but this works good enough for now.
200        mac_cmd: event.meta_key(),
201
202        // Ideally we should know if we are running or mac or not,
203        // but this works good enough for now.
204        command: event.ctrl_key() || event.meta_key(),
205    }
206}
207
208pub fn modifiers_from_wheel_event(event: &web_sys::WheelEvent) -> egui::Modifiers {
209    egui::Modifiers {
210        alt: event.alt_key(),
211        ctrl: event.ctrl_key(),
212        shift: event.shift_key(),
213
214        // Ideally we should know if we are running or mac or not,
215        // but this works good enough for now.
216        mac_cmd: event.meta_key(),
217
218        // Ideally we should know if we are running or mac or not,
219        // but this works good enough for now.
220        command: event.ctrl_key() || event.meta_key(),
221    }
222}