repose-platform 0.30.7

Platform runners (winit Desktop, Android and Web)
Documentation
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
//! Gamepad hardware backends.
//!
//! Platform-agnostic types live in [`repose_core::input`] (`GamepadEvent`,
//! `GamepadButton`, `GamepadAxis`); UI routing lives in
//! [`repose_app::ReposeRuntime::handle_gamepad`]. This module only feeds
//! hardware into events. Backends implement [`GamepadBackend`]:
//! - desktop (Linux/macOS/Windows) and web: gilrs driver (evdev / HID /
//!   XInput-WGI / Web Gamepad API), `gamepad` feature.
//! - android: [`AndroidBackend`] (non-joystick).

#[cfg(feature = "gamepad")]
use repose_core::input::{GamepadAxis, GamepadButton};
use repose_core::input::{GamepadEvent, GamepadId};

/// Hardware poller: drain pending events since the last call.
pub trait GamepadBackend {
    fn poll(&mut self) -> Vec<GamepadEvent>;
    /// Start rumble on `id`. Returns `true` when the backend accepted it
    /// (device connected + FF supported). Default: unsupported.
    fn set_rumble(
        &mut self,
        _id: GamepadId,
        _low_freq: f32,
        _high_freq: f32,
        _duration_ms: u32,
    ) -> bool {
        false
    }
    /// Stop any active rumble on `id`. Default: no-op.
    fn stop_rumble(&mut self, _id: GamepadId) {}
    /// Whether `id` currently supports rumble. Default: false.
    fn is_rumble_supported(&self, _id: GamepadId) -> bool {
        false
    }
}

/// Stick deadzone applied by all backends before emitting axis events.
#[cfg(any(all(feature = "gamepad", not(target_os = "android")), test))]
pub const STICK_DEADZONE: f32 = 0.2;

#[cfg(any(all(feature = "gamepad", not(target_os = "android")), test))]
pub(crate) fn apply_stick_deadzone(v: f32) -> f32 {
    if v.abs() < STICK_DEADZONE {
        0.0
    } else {
        v.signum() * (v.abs() - STICK_DEADZONE) / (1.0 - STICK_DEADZONE)
    }
}

/// Desktop backend driven by gilrs (its mapping database is the reference
/// implementation; repose owns the types and routing above it).
#[cfg(all(feature = "gamepad", not(target_os = "android")))]
pub struct GilrsBackend {
    gilrs: gilrs::Gilrs,
    ff_effects: std::collections::HashMap<u32, gilrs::ff::Effect>,
    /// Boot synthesis ran (see `poll`): pads already plugged in never
    /// produce gilrs `Connected` events, so the first poll reports them.
    boot_done: bool,
}

#[cfg(all(feature = "gamepad", not(target_os = "android")))]
impl GilrsBackend {
    pub fn new() -> Option<Self> {
        match gilrs::Gilrs::new() {
            Ok(gilrs) => Some(Self {
                gilrs,
                ff_effects: std::collections::HashMap::new(),
                boot_done: false,
            }),
            Err(e) => {
                log::warn!("gamepad: gilrs init failed ({e}); gamepad input disabled");
                None
            }
        }
    }

    fn map_button(b: gilrs::Button) -> Option<GamepadButton> {
        use gilrs::Button as G;
        Some(match b {
            G::South => GamepadButton::South,
            G::East => GamepadButton::East,
            G::West => GamepadButton::West,
            G::North => GamepadButton::North,
            G::Start => GamepadButton::Start,
            G::Select => GamepadButton::Select,
            G::LeftTrigger => GamepadButton::LeftShoulder,
            G::RightTrigger => GamepadButton::RightShoulder,
            G::LeftThumb => GamepadButton::LeftStick,
            G::RightThumb => GamepadButton::RightStick,
            G::DPadUp => GamepadButton::DPadUp,
            G::DPadDown => GamepadButton::DPadDown,
            G::DPadLeft => GamepadButton::DPadLeft,
            G::DPadRight => GamepadButton::DPadRight,
            _ => return None,
        })
    }

    fn map_axis(a: gilrs::Axis) -> Option<GamepadAxis> {
        use gilrs::Axis as G;
        Some(match a {
            G::LeftStickX => GamepadAxis::LeftStickX,
            G::LeftStickY => GamepadAxis::LeftStickY,
            G::RightStickX => GamepadAxis::RightStickX,
            G::RightStickY => GamepadAxis::RightStickY,
            _ => return None,
        })
    }
}

#[cfg(all(feature = "gamepad", not(target_os = "android")))]
impl GamepadBackend for GilrsBackend {
    fn poll(&mut self) -> Vec<GamepadEvent> {
        use gilrs::EventType as E;
        let mut out = Vec::new();
        while let Some(ev) = self.gilrs.next_event() {
            let id = GamepadId(usize::from(ev.id) as u32);
            match ev.event {
                E::Connected => {
                    let name = self.gilrs.gamepad(ev.id).name().to_string();
                    out.push(GamepadEvent::Connected { id, name });
                }
                E::Disconnected => out.push(GamepadEvent::Disconnected { id }),
                E::ButtonPressed(b, _) | E::ButtonRepeated(b, _) => {
                    if let Some(button) = Self::map_button(b) {
                        out.push(GamepadEvent::Button {
                            id,
                            button,
                            pressed: true,
                        });
                    }
                }
                E::ButtonReleased(b, _) => {
                    if let Some(button) = Self::map_button(b) {
                        out.push(GamepadEvent::Button {
                            id,
                            button,
                            pressed: false,
                        });
                    }
                }
                E::ButtonChanged(b, v, _) => {
                    let axis = match b {
                        gilrs::Button::LeftTrigger2 => Some(GamepadAxis::LeftTrigger),
                        gilrs::Button::RightTrigger2 => Some(GamepadAxis::RightTrigger),
                        _ => None,
                    };
                    if let Some(axis) = axis {
                        out.push(GamepadEvent::Axis {
                            id,
                            axis,
                            value: v.clamp(0.0, 1.0),
                        });
                    }
                }
                E::AxisChanged(a, v, _) => {
                    if let Some(axis) = Self::map_axis(a) {
                        out.push(GamepadEvent::Axis {
                            id,
                            axis,
                            value: apply_stick_deadzone(v),
                        });
                    }
                }
                E::Dropped | E::ForceFeedbackEffectCompleted => {}
                _ => {}
            }
        }
        if !self.boot_done {
            self.boot_done = true;
            let live: Vec<(GamepadId, String)> = self
                .gilrs
                .gamepads()
                .map(|(gid, pad)| (GamepadId(usize::from(gid) as u32), pad.name().to_string()))
                .collect();
            let mut synth = synthesize_boot(live.into_iter(), &out);
            synth.append(&mut out);
            out = synth;
        }
        out
    }

    fn is_rumble_supported(&self, id: GamepadId) -> bool {
        let want = id.0 as usize;
        self.gilrs
            .gamepads()
            .find(|(gid, _)| usize::from(*gid) == want)
            .map(|(_, pad)| pad.is_ff_supported())
            .unwrap_or(false)
    }

    fn set_rumble(
        &mut self,
        id: GamepadId,
        low_freq: f32,
        high_freq: f32,
        duration_ms: u32,
    ) -> bool {
        use gilrs::ff::{BaseEffect, BaseEffectType, EffectBuilder, Repeat, Replay, Ticks};
        let low = low_freq.clamp(0.0, 1.0);
        let high = high_freq.clamp(0.0, 1.0);
        if low <= 0.0 && high <= 0.0 {
            self.stop_rumble(id);
            return true;
        }
        let want = id.0 as usize;
        let gid = match self
            .gilrs
            .gamepads()
            .find(|(gid, _)| usize::from(*gid) == want)
            .map(|(gid, _)| gid)
        {
            Some(g) => g,
            None => return false,
        };
        if !self
            .gilrs
            .connected_gamepad(gid)
            .map(|p| p.is_ff_supported())
            .unwrap_or(false)
        {
            return false;
        }
        let duration = Ticks::from_ms(duration_ms.max(1));
        let mut builder = EffectBuilder::new();
        builder
            .add_effect(BaseEffect {
                kind: BaseEffectType::Strong {
                    magnitude: (low * u16::MAX as f32) as u16,
                },
                scheduling: Replay {
                    play_for: duration,
                    ..Default::default()
                },
                ..Default::default()
            })
            .add_effect(BaseEffect {
                kind: BaseEffectType::Weak {
                    magnitude: (high * u16::MAX as f32) as u16,
                },
                scheduling: Replay {
                    play_for: duration,
                    ..Default::default()
                },
                ..Default::default()
            })
            .repeat(Repeat::For(duration))
            .gamepads(&[gid]);
        match builder.finish(&mut self.gilrs) {
            Ok(effect) => {
                let _ = effect.play();
                self.ff_effects.insert(id.0, effect);
                true
            }
            Err(e) => {
                log::warn!("gamepad: rumble failed for pad {} ({e:?})", id.0);
                false
            }
        }
    }

    fn stop_rumble(&mut self, id: GamepadId) {
        if let Some(effect) = self.ff_effects.remove(&id.0) {
            let _ = effect.stop();
        }
    }
}

/// Create the platform backend, or `None` when the `gamepad` feature is off.
///
/// One labeled arm per target (see module docs for the gilrs-Android swap).
pub fn create_backend() -> Option<impl GamepadBackend> {
    // Android: native-keycode backend (buttons via winit key path).
    #[cfg(all(feature = "gamepad", target_os = "android"))]
    {
        AndroidBackend::new()
    }
    // Desktop + web: gilrs driver.
    #[cfg(all(feature = "gamepad", not(target_os = "android")))]
    {
        GilrsBackend::new()
    }
    #[cfg(not(feature = "gamepad"))]
    {
        None::<NoBackend>
    }
}

/// Android backend constructor with a concrete return type (for runners
/// that need [`AndroidBackend::key_button`], which is not on the trait).
#[cfg(all(feature = "gamepad", target_os = "android"))]
pub fn create_android_backend() -> Option<AndroidBackend> {
    AndroidBackend::new()
}

/// Android controller backend: buttons arrive as native keycodes through
/// winit (`Key::Unidentified(NativeKeyCode::Android(code))`  - winit maps
/// `AKEYCODE_BUTTON_*` there deliberately), so there is nothing to poll;
/// [`AndroidBackend::key_button`] translates at the key-event site.
/// Sticks/triggers need a future Paddleboat/JNI driver on this trait.
#[cfg(all(feature = "gamepad", target_os = "android"))]
pub struct AndroidBackend {
    connected: bool,
}

#[cfg(all(feature = "gamepad", target_os = "android"))]
impl AndroidBackend {
    pub fn new() -> Option<Self> {
        Some(Self { connected: false })
    }

    /// Translate a native Android keycode press/release into gamepad events.
    /// Emits a synthetic `Connected` (virtual pad id 0) on first sight.
    /// NOTE: Since Android offers no hotplug event through winit, it returns empty
    /// for non-controller codes so callers can fall through to keyboard.
    pub fn key_button(&mut self, code: u32, pressed: bool) -> Vec<GamepadEvent> {
        let Some(button) = android_code_to_button(code) else {
            return Vec::new();
        };
        let mut out = Vec::with_capacity(2);
        if !self.connected {
            self.connected = true;
            out.push(GamepadEvent::Connected {
                id: GamepadId(0),
                name: "Android controller".to_string(),
            });
        }
        out.push(GamepadEvent::Button {
            id: GamepadId(0),
            button,
            pressed,
        });
        out
    }
}

#[cfg(all(feature = "gamepad", target_os = "android"))]
impl GamepadBackend for AndroidBackend {
    fn poll(&mut self) -> Vec<GamepadEvent> {
        Vec::new()
    }
}

#[cfg(feature = "gamepad")]
pub fn android_code_to_button(code: u32) -> Option<GamepadButton> {
    Some(match code {
        19 => GamepadButton::DPadUp,
        20 => GamepadButton::DPadDown,
        21 => GamepadButton::DPadLeft,
        22 => GamepadButton::DPadRight,
        23 => GamepadButton::South,          // DPAD_CENTER
        96 => GamepadButton::South,          // BUTTON_A
        97 => GamepadButton::East,           // BUTTON_B
        99 => GamepadButton::West,           // BUTTON_X
        100 => GamepadButton::North,         // BUTTON_Y
        102 => GamepadButton::LeftShoulder,  // BUTTON_L1
        103 => GamepadButton::RightShoulder, // BUTTON_R1
        106 => GamepadButton::LeftStick,     // BUTTON_THUMBL
        107 => GamepadButton::RightStick,    // BUTTON_THUMBR
        108 => GamepadButton::Start,         // BUTTON_START
        109 => GamepadButton::Select,        // BUTTON_SELECT
        _ => return None,
    })
}

/// First-poll boot synthesis, pure for tests: `Connected` per live
/// device, skipping ids this poll already reported, enumeration order
/// kept so device 0 sorts first for "Press Start" flows.
#[cfg(all(feature = "gamepad", not(target_os = "android")))]
fn synthesize_boot(
    live: impl Iterator<Item = (GamepadId, String)>,
    reported: &[GamepadEvent],
) -> Vec<GamepadEvent> {
    live.filter(|(id, _)| {
        !reported
            .iter()
            .any(|ev| matches!(ev, GamepadEvent::Connected { id: eid, .. } if eid == id))
    })
    .map(|(id, name)| GamepadEvent::Connected { id, name })
    .collect()
}

/// Placeholder backend for targets without a driver yet.
pub struct NoBackend;

impl GamepadBackend for NoBackend {
    fn poll(&mut self) -> Vec<GamepadEvent> {
        Vec::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn stick_deadzone_snaps_and_rescales() {
        assert_eq!(apply_stick_deadzone(0.0), 0.0);
        assert_eq!(apply_stick_deadzone(0.19), 0.0);
        assert_eq!(apply_stick_deadzone(-0.19), 0.0);
        assert_eq!(apply_stick_deadzone(1.0), 1.0);
        assert_eq!(apply_stick_deadzone(-1.0), -1.0);
        let mid = apply_stick_deadzone(0.6);
        assert!((mid - 0.5).abs() < 1e-6);
    }

    #[test]
    fn rumble_unsupported_by_default() {
        let mut backend = NoBackend;
        assert!(!backend.is_rumble_supported(GamepadId(0)));
        assert!(!backend.set_rumble(GamepadId(0), 1.0, 1.0, 100));
        backend.stop_rumble(GamepadId(0));
    }

    #[cfg(feature = "gamepad")]
    #[test]
    fn android_codes_map_to_standard_layout() {
        assert_eq!(android_code_to_button(96), Some(GamepadButton::South));
        assert_eq!(android_code_to_button(97), Some(GamepadButton::East));
        assert_eq!(android_code_to_button(99), Some(GamepadButton::West));
        assert_eq!(android_code_to_button(100), Some(GamepadButton::North));
        assert_eq!(
            android_code_to_button(102),
            Some(GamepadButton::LeftShoulder)
        );
        assert_eq!(android_code_to_button(108), Some(GamepadButton::Start));
        assert_eq!(android_code_to_button(19), Some(GamepadButton::DPadUp));
        assert_eq!(android_code_to_button(23), Some(GamepadButton::South));
        // Non-controller codes fall through to keyboard.
        assert_eq!(android_code_to_button(29), None); // KEYCODE_A
        assert_eq!(android_code_to_button(98), None); // BUTTON_C
        assert_eq!(android_code_to_button(110), None); // BUTTON_MODE
    }

    #[cfg(all(feature = "gamepad", not(target_os = "android")))]
    #[test]
    fn boot_synthesis_reports_all_live_devices() {
        let live = vec![
            (GamepadId(0), "Pad A".to_string()),
            (GamepadId(1), "Pad B".to_string()),
        ];
        let synth = synthesize_boot(live.into_iter(), &[]);
        assert_eq!(synth.len(), 2);
        assert!(matches!(
            &synth[0],
            GamepadEvent::Connected { id, name }
            if *id == GamepadId(0) && name == "Pad A"
        ));
    }

    #[cfg(all(feature = "gamepad", not(target_os = "android")))]
    #[test]
    fn boot_synthesis_skips_self_reported_ids() {
        let live = vec![
            (GamepadId(0), "Pad A".to_string()),
            (GamepadId(1), "Pad B".to_string()),
        ];
        let reported = vec![GamepadEvent::Connected {
            id: GamepadId(1),
            name: "Pad B".to_string(),
        }];
        let synth = synthesize_boot(live.into_iter(), &reported);
        assert_eq!(synth.len(), 1);
        assert!(matches!(
            &synth[0],
            GamepadEvent::Connected { id, .. } if *id == GamepadId(0)
        ));
        let reported = vec![GamepadEvent::Button {
            id: GamepadId(0),
            button: GamepadButton::South,
            pressed: true,
        }];
        let live = vec![(GamepadId(0), "Pad A".to_string())];
        assert_eq!(synthesize_boot(live.into_iter(), &reported).len(), 1);
    }

    #[cfg(all(feature = "gamepad", not(target_os = "android")))]
    #[test]
    fn first_poll_is_empty_without_hardware() {
        if let Some(mut backend) = GilrsBackend::new() {
            assert!(backend.poll().is_empty());
            assert!(backend.poll().is_empty());
        }
    }
}