use gilrs::ConnectedGamepadsIterator;
use std::fmt;
pub use gilrs::{self, Event, Gamepad, Gilrs};
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct GamepadId(pub(crate) gilrs::GamepadId);
use crate::context::Context;
use crate::error::GameResult;
pub trait GamepadContext {
fn next_event(&mut self) -> Option<Event>;
fn gamepad(&self, id: GamepadId) -> Gamepad;
fn gamepads(&self) -> GamepadsIterator;
}
pub struct GilrsGamepadContext {
pub(crate) gilrs: Gilrs,
}
impl fmt::Debug for GilrsGamepadContext {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "<GilrsGamepadContext: {:p}>", self)
}
}
impl GilrsGamepadContext {
pub(crate) fn new() -> GameResult<Self> {
let gilrs = Gilrs::new()?;
Ok(GilrsGamepadContext { gilrs })
}
}
impl From<Gilrs> for GilrsGamepadContext {
fn from(gilrs: Gilrs) -> Self {
Self { gilrs }
}
}
impl GamepadContext for GilrsGamepadContext {
fn next_event(&mut self) -> Option<Event> {
self.gilrs.next_event()
}
fn gamepad(&self, id: GamepadId) -> Gamepad {
self.gilrs.gamepad(id.0)
}
fn gamepads(&self) -> GamepadsIterator {
GamepadsIterator {
wrapped: self.gilrs.gamepads(),
}
}
}
pub struct GamepadsIterator<'a> {
wrapped: ConnectedGamepadsIterator<'a>,
}
impl<'a> fmt::Debug for GamepadsIterator<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "<GamepadsIterator: {:p}>", self)
}
}
impl<'a> Iterator for GamepadsIterator<'a> {
type Item = (GamepadId, Gamepad<'a>);
fn next(&mut self) -> Option<(GamepadId, Gamepad<'a>)> {
self.wrapped.next().map(|(id, gp)| (GamepadId(id), gp))
}
}
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct NullGamepadContext {}
impl GamepadContext for NullGamepadContext {
fn next_event(&mut self) -> Option<Event> {
None
}
fn gamepad(&self, _id: GamepadId) -> Gamepad {
panic!("Gamepad module disabled")
}
fn gamepads(&self) -> GamepadsIterator {
panic!("Gamepad module disabled")
}
}
pub fn gamepad(ctx: &Context, id: GamepadId) -> Gamepad {
ctx.gamepad_context.gamepad(id)
}
pub fn gamepads(ctx: &Context) -> GamepadsIterator {
ctx.gamepad_context.gamepads()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn gilrs_init() {
assert!(GilrsGamepadContext::new().is_ok());
}
}