+use std::cell::RefCell;
+use sdl2::haptic::Haptic;
+use sdl2::HapticSubsystem;
+use sdl2::GameControllerSubsystem;
+use sdl2::event::Event;
+use sdl2::controller::GameController;
+use std::rc::Rc;
+
+//#[derive(Debug)]
+pub struct ControllerManager {
+ ctrl: GameControllerSubsystem,
+ haptic: Rc<HapticSubsystem>,
+ pub controllers: Vec<Rc<Controller>>,
+}
+
+//#[derive(Debug)]
+pub struct Controller {
+ id: u32,
+ pub ctrl: GameController,
+ haptic: Option<Rc<RefCell<Haptic>>>,
+}
+
+impl ControllerManager {
+ pub fn new(ctrl: GameControllerSubsystem, haptic: HapticSubsystem) -> Self {
+ ControllerManager {
+ ctrl,
+ haptic: Rc::new(haptic),
+ controllers: vec![],
+ }
+ }
+
+ pub fn handle_event(&mut self, event: &Event) {
+ match event {
+ Event::ControllerDeviceAdded { which: id, .. } => { self.add_device(*id) }
+ Event::ControllerDeviceRemoved { which: id, .. } => { self.remove_device(*id) }
+ Event::ControllerDeviceRemapped { which: id, .. } => { println!("device remapped ({})!", *id) }
+ Event::ControllerButtonDown { button: btn, .. } => { println!("button {} down!", btn.string()) }
+ Event::ControllerButtonUp { button: btn, .. } => { println!("button {} up!", btn.string()) }
+ Event::ControllerAxisMotion { axis: ax, .. } => { println!("axis motion {}!", ax.string()) }
+ _ => {}
+ }
+ }
+
+ pub fn add_device(&mut self, id: u32) {
+ println!("device added ({})!", id);
+ let mut ctrl = self.ctrl.open(id).unwrap();
+ println!("opened {}", ctrl.name());
+ let haptic = match ctrl.set_rumble(500, 1000, 500) {
+ Ok(_) => self.haptic.open_from_joystick_id(id).ok(),
+ Err(_) => None
+ };
+
+ let c = Rc::new(Controller {id, ctrl, haptic: haptic.map(|h| Rc::new(RefCell::new(h)))});
+ c.rumble(0.5, 300);
+ self.controllers.push(c);
+ }
+
+ pub fn remove_device(&mut self, id: i32) {
+ println!("device removed ({})!", id);
+ }
+}
+
+impl Controller {
+ /// strength [0 - 1]
+ pub fn rumble(&self, strength: f32, duration_ms: u32) {
+ if let Some(h) = &self.haptic {
+ h.borrow_mut().rumble_play(strength, duration_ms);
+ }
+ }
+}