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      | "CapsLock"
119      | "ContextMenu"
120      | "Control"
121      | "Delete"
122      | "End"
123      | "Enter"
124      | "Esc"
125      | "Escape"
126      | "GroupNext" // https://github.com/emilk/egui/issues/510
127      | "Help"
128      | "Home"
129      | "Insert"
130      | "Meta"
131      | "NumLock"
132      | "PageDown"
133      | "PageUp"
134      | "Pause"
135      | "ScrollLock"
136      | "Shift"
137      | "Tab"
138    );
139
140    if is_control_key {
141        return None;
142    }
143
144    Some(key)
145}
146
147/// Web sends all keys as strings, so it is up to us to figure out if it is
148/// a real text input or the name of a key.
149pub fn translate_key(key: &str) -> Option<egui::Key> {
150    egui::Key::from_name(key)
151}
152
153pub fn modifiers_from_kb_event(event: &web_sys::KeyboardEvent) -> egui::Modifiers {
154    egui::Modifiers {
155        alt: event.alt_key(),
156        ctrl: event.ctrl_key(),
157        shift: event.shift_key(),
158
159        // Ideally we should know if we are running or mac or not,
160        // but this works good enough for now.
161        mac_cmd: event.meta_key(),
162
163        // Ideally we should know if we are running or mac or not,
164        // but this works good enough for now.
165        command: event.ctrl_key() || event.meta_key(),
166    }
167}
168
169pub fn modifiers_from_mouse_event(event: &web_sys::MouseEvent) -> egui::Modifiers {
170    egui::Modifiers {
171        alt: event.alt_key(),
172        ctrl: event.ctrl_key(),
173        shift: event.shift_key(),
174
175        // Ideally we should know if we are running or mac or not,
176        // but this works good enough for now.
177        mac_cmd: event.meta_key(),
178
179        // Ideally we should know if we are running or mac or not,
180        // but this works good enough for now.
181        command: event.ctrl_key() || event.meta_key(),
182    }
183}
184
185pub fn modifiers_from_wheel_event(event: &web_sys::WheelEvent) -> egui::Modifiers {
186    egui::Modifiers {
187        alt: event.alt_key(),
188        ctrl: event.ctrl_key(),
189        shift: event.shift_key(),
190
191        // Ideally we should know if we are running or mac or not,
192        // but this works good enough for now.
193        mac_cmd: event.meta_key(),
194
195        // Ideally we should know if we are running or mac or not,
196        // but this works good enough for now.
197        command: event.ctrl_key() || event.meta_key(),
198    }
199}