Skip to main content

repose_platform/
runner_common.rs

1//! Shared runner helpers extracted from duplicated desktop/web/android `App` impls.
2
3use repose_app::{ReposeRuntime, TouchGestureState};
4use repose_core::Vec2;
5use repose_core::input::PointerButton;
6use repose_core::shortcuts::{Action, Gesture};
7use winit::event::{ElementState, MouseScrollDelta, Touch};
8use winit::keyboard::{KeyCode, PhysicalKey};
9
10use crate::common::{map_key, winit_key_to_repose};
11
12/// Update `Modifiers` from winit state - shared.
13pub fn on_modifiers_changed(rt: &mut ReposeRuntime, state: &winit::keyboard::ModifiersState) {
14    crate::common::update_modifiers(&mut rt.modifiers, state);
15}
16
17/// CursorMoved helper - returns cursor + whether inspector hover updated.
18pub fn on_cursor_moved(
19    rt: &mut ReposeRuntime,
20    pos: Vec2,
21    inspector: &mut Option<repose_devtools::Inspector>,
22) -> Option<repose_core::CursorIcon> {
23    let result = rt.handle_pointer_move(pos);
24    if let (Some(inspector), Some(f)) = (inspector, &rt.frame_cache)
25        && inspector.hud.inspector_enabled
26    {
27        let hit = f.hit_regions.iter().find(|h| h.rect.contains(pos));
28        let hover_rect = hit.map(|h| h.rect);
29        let hover_info = hit.and_then(|h| {
30            f.semantics_nodes
31                .iter()
32                .find(|s| s.id == h.id)
33                .map(|s| repose_devtools::HoveredInfo {
34                    id: s.id,
35                    role: format!("{:?}", s.role),
36                    label: s.label.clone(),
37                })
38        });
39        inspector.hud.set_hovered(hover_rect, hover_info);
40    }
41    result.cursor
42}
43
44/// MouseWheel helper - converts delta to px and dispatches.
45pub fn on_mouse_wheel(rt: &mut ReposeRuntime, delta: MouseScrollDelta, scale: f32) -> bool {
46    let (dx_px, dy_px) = match delta {
47        MouseScrollDelta::LineDelta(x, y) => {
48            let _ = scale;
49            let unit_px = repose_core::Dp(60.0).to_px().0;
50            (-(x * unit_px), -(y * unit_px))
51        }
52        MouseScrollDelta::PixelDelta(p) => (-(p.x as f32), -(p.y as f32)),
53    };
54    rt.handle_scroll(Vec2 { x: dx_px, y: dy_px })
55}
56
57/// Map winit MouseButton -> PointerButton.
58pub fn map_mouse_button(btn: winit::event::MouseButton) -> Option<PointerButton> {
59    match btn {
60        winit::event::MouseButton::Left => Some(PointerButton::Primary),
61        winit::event::MouseButton::Right => Some(PointerButton::Secondary),
62        winit::event::MouseButton::Middle => Some(PointerButton::Tertiary),
63        _ => None,
64    }
65}
66
67/// Raw touch result without dispatch - caller handles `dispatch_action` to avoid double-borrow.
68pub struct TouchResult {
69    pub dirty: bool,
70    pub pinch: Option<(f32, Vec2)>,
71    pub pan: Option<(Vec2, Vec2)>,
72    pub rotation: Option<(f32, Vec2)>,
73    pub swipe_right: Option<bool>,
74    /// Press result of a tap dispatched on `Ended`. `None` when no press ran
75    /// (scroll/pinch release); `Some` carries the press's focused id, with
76    /// `None` inside meaning the tap explicitly defocused.
77    pub press: Option<Option<u64>>,
78}
79
80pub fn handle_touch_raw(
81    rt: &mut ReposeRuntime,
82    touch_gestures: &mut TouchGestureState,
83    t: &Touch,
84    scale: f32,
85) -> TouchResult {
86    let pos_px = (t.location.x as f32, t.location.y as f32);
87    let tid = t.id;
88    match t.phase {
89        winit::event::TouchPhase::Started => {
90            // Sync before the gesture layer: `touch_started` reads
91            // the table for multi-finger detection (`len() >= 2`
92            // cancels the pending primary instead of dispatching a
93            // press), so the second finger must already be present.
94            touch_gestures.contact_down(tid, pos_px);
95            touch_gestures.touch_started(rt, tid, pos_px);
96            sync_touch_points(rt, touch_gestures);
97            TouchResult {
98                dirty: true,
99                pinch: None,
100                pan: None,
101                rotation: None,
102                swipe_right: None,
103                press: None,
104            }
105        }
106        winit::event::TouchPhase::Moved => {
107            touch_gestures.contact_down(tid, pos_px);
108            let (dirty, pinch, pan, rotation) = touch_gestures.touch_moved(rt, tid, pos_px, scale);
109            sync_touch_points(rt, touch_gestures);
110            TouchResult {
111                dirty,
112                pinch,
113                pan,
114                rotation,
115                swipe_right: None,
116                press: None,
117            }
118        }
119        winit::event::TouchPhase::Ended | winit::event::TouchPhase::Cancelled => {
120            let cancelled = t.phase == winit::event::TouchPhase::Cancelled;
121            // Sync before the gesture layer: `touch_ended` derives
122            // tap-vs-multi from the table (`was_multi`), so the lifted
123            // finger must still be present.
124            let ended = touch_gestures.touch_ended(rt, tid, pos_px, cancelled);
125            touch_gestures.contact_up(tid);
126            sync_touch_points(rt, touch_gestures);
127            TouchResult {
128                dirty: false,
129                pinch: None,
130                pan: None,
131                rotation: None,
132                swipe_right: ended.swipe_right,
133                press: ended.press,
134            }
135        }
136    }
137}
138
139/// Publish the live contact table into `sched.touch_points` (single
140/// sync point: every runner funnels raw touch through
141/// `handle_touch_raw`). Games snapshot it each frame, so held fingers
142/// stay visible across frames (unlike the press edge, which fires
143/// once and is gone). GML `device_mouse_*` parity: stable per-finger
144/// ids, physical-px positions sampled every tick while held.
145fn sync_touch_points(rt: &mut ReposeRuntime, touch_gestures: &TouchGestureState) {
146    rt.sched.touch_points.clear();
147    rt.sched
148        .touch_points
149        .extend(touch_gestures.active_touches().iter().map(|(id, (x, y))| (*id, *x, *y)));
150}
151
152/// HACK: Legacy wrapper that dispatches gestures inline (use `handle_touch_raw` when caller
153/// needs to avoid double-borrow of `self` containing `rt`).
154pub fn on_touch(
155    rt: &mut ReposeRuntime,
156    touch_gestures: &mut TouchGestureState,
157    t: &Touch,
158    scale: f32,
159    mut dispatch: impl FnMut(Action) -> bool,
160) -> bool {
161    let r = handle_touch_raw(rt, touch_gestures, t, scale);
162    let mut dirty = r.dirty;
163    if let Some((delta_scale, center)) = r.pinch
164        && dispatch(Action::Gesture(Gesture::PinchWithCenter {
165            delta_scale,
166            center,
167        }))
168    {
169        dirty = true;
170    }
171    if let Some((delta, center)) = r.pan
172        && dispatch(Action::Gesture(Gesture::Pan { delta, center }))
173    {
174        dirty = true;
175    }
176    if let Some((delta_rotation, center)) = r.rotation
177        && dispatch(Action::Gesture(Gesture::Rotate {
178            delta_rotation,
179            center,
180        }))
181    {
182        dirty = true;
183    }
184    if let Some(right) = r.swipe_right {
185        let g = if right {
186            Gesture::SwipeRight
187        } else {
188            Gesture::SwipeLeft
189        };
190        if dispatch(Action::Gesture(g)) {
191            dirty = true;
192        }
193    }
194    dirty
195}
196
197/// Touch handler that also syncs IME for focused textfields (web/android).
198/// Returns whether a redraw is needed. Probably shared for desktop once winit unifies touch.
199pub fn on_touch_with_ime(
200    rt: &mut ReposeRuntime,
201    touch_gestures: &mut TouchGestureState,
202    t: &Touch,
203    scale: f32,
204    window: &winit::window::Window,
205    dispatch: impl FnMut(Action) -> bool,
206) -> bool {
207    let pos_px = (t.location.x as f32, t.location.y as f32);
208    let tid = t.id;
209    if t.phase == winit::event::TouchPhase::Started {
210        let focused = touch_gestures.touch_started(rt, tid, pos_px);
211        if let Some(fid) = focused {
212            if rt.is_textfield(fid) {
213                let (purpose, ac, cap) = rt.focused_keyboard_hints();
214                crate::common::set_ime_for_textfield_ex(window, true, purpose, ac, cap);
215            } else {
216                crate::common::set_ime_for_textfield(window, false);
217            }
218        } else {
219            crate::common::set_ime_for_textfield(window, false);
220        }
221        return true;
222    }
223    on_touch(rt, touch_gestures, t, scale, dispatch)
224}
225
226/// Shared inspector toggle + runtime dispatch.
227/// Reports the raw physical transition to the polled `held_keys` set
228/// first (games read held keys GML-style without depending on focus),
229/// then dispatches the focus-routed key event as before.
230/// Returns true if event consumed / needs redraw.
231pub fn on_keyboard_input(
232    rt: &mut ReposeRuntime,
233    key_event: &winit::event::KeyEvent,
234    inspector: &mut Option<repose_devtools::Inspector>,
235) -> bool {
236    rt.set_physical_key(
237        &physical_key_name(key_event.physical_key),
238        key_event.state == ElementState::Pressed,
239    );
240    // Mirror into the scheduler's polled snapshot too: games read
241    // `sched.held_keys` + mouse levels directly (no runtime handle),
242    // so the platform publishes hardware levels where composition can
243    // see them. Focus dispatch below is unchanged.
244    {
245        let key = map_physical_key(key_event.physical_key);
246        let sched = &mut rt.sched;
247        if key_event.state == ElementState::Pressed {
248            sched.held_keys.insert(key);
249        } else {
250            sched.held_keys.remove(&key);
251        }
252    }
253    if key_event.state == ElementState::Pressed
254        && !key_event.repeat
255        && rt.modifiers.ctrl
256        && rt.modifiers.shift
257        && key_event.physical_key == PhysicalKey::Code(KeyCode::KeyI)
258        && let Some(inspector) = inspector
259    {
260        inspector.hud.toggle_inspector();
261        return true;
262    }
263    let mapped = map_key(key_event.physical_key, &rt.modifiers);
264    let ke = winit_key_to_repose(key_event, &mapped, &rt.modifiers);
265    rt.handle_key_with_text(&ke, key_event.text.as_deref())
266}
267
268/// Stable debug name for a physical key (`KeyW`, `Digit1`, `Space`,
269/// ...), matching `KeyCode`'s variant names. Layout-independent:
270/// AZERTY/QWERTZ report the same physical names, so games bind by
271/// position the way GML's `ord("W")` binds the US position.
272pub fn physical_key_name(key: PhysicalKey) -> String {
273    match key {
274        PhysicalKey::Code(code) => format!("{code:?}"),
275        PhysicalKey::Unidentified(native) => format!("Unidentified({native:?})"),
276    }
277}
278
279/// Typed physical position for a winit key (`None` wraps to
280/// [`repose_core::input::PhysicalKey::Unidentified`], never `None`:
281/// every physical press has a position). Backs both the `KeyEvent`
282/// field and the `Scheduler::held_keys` snapshot.
283pub fn map_physical_key(key: PhysicalKey) -> repose_core::input::PhysicalKey {
284    repose_core::input::PhysicalKey::from_name(&physical_key_name(key))
285}
286
287/// Ime dispatch helper.
288pub fn on_ime(rt: &mut ReposeRuntime, ime: &winit::event::Ime) {
289    use winit::event::Ime;
290    let ev = match ime {
291        Ime::Enabled => repose_core::input::ImeEvent::Start,
292        Ime::Preedit(text, cursor) => repose_core::input::ImeEvent::Update {
293            text: text.clone(),
294            cursor: cursor.map(|(a, b)| (a, b)),
295        },
296        Ime::Commit(text) => repose_core::input::ImeEvent::Commit(text.clone()),
297        Ime::Disabled => repose_core::input::ImeEvent::Cancel,
298    };
299    rt.handle_ime(&ev);
300}