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
//! The module for all things related to the
//! [XInput](https://docs.microsoft.com/en-us/windows/desktop/xinput/getting-started-with-xinput)
//! sub-system.

use super::*;

use winapi::um::libloaderapi::*;
use winapi::um::xinput::*;

unsafe impl ZeroSafe for XINPUT_BATTERY_INFORMATION {}
unsafe impl ZeroSafe for XINPUT_CAPABILITIES {}
unsafe impl ZeroSafe for XINPUT_KEYSTROKE {}
unsafe impl ZeroSafe for XINPUT_STATE {}

type XInputEnableFn = unsafe extern "system" fn(BOOL);
type XInputGetAudioDeviceIdsFn =
  unsafe extern "system" fn(DWORD, LPWSTR, *mut UINT, LPWSTR, *mut UINT) -> DWORD;
type XInputGetBatteryInformationFn =
  unsafe extern "system" fn(DWORD, BYTE, *mut XINPUT_BATTERY_INFORMATION) -> DWORD;
type XInputGetCapabilitiesFn =
  unsafe extern "system" fn(DWORD, DWORD, *mut XINPUT_CAPABILITIES) -> DWORD;
type XInputGetDSoundAudioDeviceGuidsFn =
  unsafe extern "system" fn(DWORD, *mut GUID, *mut GUID) -> DWORD;
type XInputGetKeystrokeFn = unsafe extern "system" fn(DWORD, DWORD, PXINPUT_KEYSTROKE) -> DWORD;
type XInputGetStateFn = unsafe extern "system" fn(DWORD, *mut XINPUT_STATE) -> DWORD;
type XInputSetStateFn = unsafe extern "system" fn(DWORD, *mut XINPUT_VIBRATION) -> DWORD;

const XINPUT_DLL_NAME_LIST: &[&str] = &[
  "xinput1_4.dll",
  "xinput1_3.dll",
  "xinput1_2.dll",
  "xinput1_1.dll",
  "xinput9_1_0.dll",
];
const ENABLE_NAME: &[u8] = b"XInputEnable\0";
const GET_AUDIO_DEVICE_IDS_NAME: &[u8] = b"XInputGetAudioDeviceIds\0";
const GET_BATTERY_INFORMATION_NAME: &[u8] = b"XInputGetBatteryInformation\0";
const GET_CAPABILITIES_NAME: &[u8] = b"XInputGetCapabilities\0";
const GET_DSOUND_AUDIO_DEVICE_GUIDS_NAME: &[u8] = b"XInputGetDSoundAudioDeviceGuids\0";
const GET_KEYSTROKE_NAME: &[u8] = b"XInputGetKeystroke\0";
const GET_STATE_NAME: &[u8] = b"XInputGetState\0";
const SET_STATE_NAME: &[u8] = b"XInputSetState\0";

/// A handle to a dynamically loaded XInput DLL.
///
/// Several versions of XInput exist
/// ([MSDN](https://docs.microsoft.com/en-us/windows/desktop/xinput/xinput-versions)),
/// and XInput might not even be installed on the user's machine at all. To
/// compensate for this, we dynamically load the user's XInput DLL at runtime,
/// and then call the XInput functions though that.
///
/// If the version of XInput that you end up loading doesn't possess a
/// particular function you will simply get `Err(DEVICE_NOT_CONNECTED)` when
/// calling said function. For every function `foo` there's also a `has_foo`
/// method if you want to specifically confirm that the function is loaded.
pub struct XInput {
  dll_name: &'static str,
  dll: HMODULE,
  enable: Option<XInputEnableFn>,
  get_audio_device_ids: Option<XInputGetAudioDeviceIdsFn>,
  get_battery_information: Option<XInputGetBatteryInformationFn>,
  get_capabilities: Option<XInputGetCapabilitiesFn>,
  get_dsound_audio_device_guids: Option<XInputGetDSoundAudioDeviceGuidsFn>,
  get_keystroke: Option<XInputGetKeystrokeFn>,
  get_state: Option<XInputGetStateFn>,
  set_state: Option<XInputSetStateFn>,
}
impl core::ops::Drop for XInput {
  fn drop(&mut self) {
    if !self.dll.is_null() {
      unsafe { FreeLibrary(self.dll) };
    }
  }
}
impl std::fmt::Debug for XInput {
  fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
    let yesno = |b| if b { "yes" } else { "no" };
    write!(f, "XInput {{ dll_name: {:?}, enable: {}, get_audio_device_ids: {}, get_battery_information: {}, get_capabilities: {}, get_dsound_audio_device_guids: {}, get_keystroke: {}, get_state: {}, set_state: {} }}",
      self.dll_name,
      yesno(self.enable.is_some()),
      yesno(self.get_audio_device_ids.is_some()),
      yesno(self.get_battery_information.is_some()),
      yesno(self.get_capabilities.is_some()),
      yesno(self.get_dsound_audio_device_guids.is_some()),
      yesno(self.get_keystroke.is_some()),
      yesno(self.get_state.is_some()),
      yesno(self.set_state.is_some()),
    )
  }
}
impl XInput {
  /// Loads in an XInput DLL, if possible.
  ///
  /// ## Failure
  ///
  /// If no XInput DLL can be loaded this returns an `Err` value with an empty
  /// `XInput` instance. You can still call methods on it, they'll just all
  /// always give `Err(DEVICE_NOT_CONNECTED)`.
  #[rustfmt::skip]
  pub fn load() -> Result<Self, Self> {
    unsafe {
      for &dll_name in XINPUT_DLL_NAME_LIST {
        let wide_name = wide_null(dll_name);
        let dll = LoadLibraryW(wide_name.as_ptr());
        if !dll.is_null() {
          use core::intrinsics::transmute;
          let enable: Option<XInputEnableFn> = transmute(GetProcAddress(dll, ENABLE_NAME.as_ptr() as *const i8));
          let get_audio_device_ids: Option<XInputGetAudioDeviceIdsFn> = transmute(GetProcAddress(dll, GET_AUDIO_DEVICE_IDS_NAME.as_ptr() as *const i8));
          let get_battery_information: Option<XInputGetBatteryInformationFn> = transmute(GetProcAddress(dll, GET_BATTERY_INFORMATION_NAME.as_ptr() as *const i8));
          let get_capabilities: Option<XInputGetCapabilitiesFn> = transmute(GetProcAddress(dll, GET_CAPABILITIES_NAME.as_ptr() as *const i8));
          let get_dsound_audio_device_guids: Option<XInputGetDSoundAudioDeviceGuidsFn> = transmute(GetProcAddress(dll, GET_DSOUND_AUDIO_DEVICE_GUIDS_NAME.as_ptr() as *const i8));
          let get_keystroke: Option<XInputGetKeystrokeFn> = transmute(GetProcAddress(dll, GET_KEYSTROKE_NAME.as_ptr() as *const i8));
          let get_state: Option<XInputGetStateFn> = transmute(GetProcAddress(dll, GET_STATE_NAME.as_ptr() as *const i8));
          let set_state: Option<XInputSetStateFn> = transmute(GetProcAddress(dll, SET_STATE_NAME.as_ptr() as *const i8));
          return Ok(Self {
            dll_name,
            dll,
            enable,
            get_audio_device_ids,
            get_battery_information,
            get_capabilities,
            get_dsound_audio_device_guids,
            get_keystroke,
            get_state,
            set_state,
          });
        }
      }
      Err(Self {
        dll_name: "None",
        dll: null_mut(),
        enable: None,
        get_audio_device_ids: None,
        get_battery_information: None,
        get_capabilities: None,
        get_dsound_audio_device_guids: None,
        get_keystroke: None,
        get_state: None,
        set_state: None,
      })
    }
  }

  /// The name of the DLL that this has loaded.
  pub fn dll_name(&self) -> &'static str {
    &self.dll_name
  }

  /// Allows you to enable and disable the whole XInput sub-system.
  ///
  /// Not available in older versions of XInput.
  ///
  /// [MSDN](https://docs.microsoft.com/en-us/windows/desktop/api/xinput/nf-xinput-xinputenable)
  pub fn enable(&self, enabled: bool) -> Result<(), DWORD> {
    self
      .enable
      .map(|f| unsafe { f(if enabled { TRUE } else { FALSE }) })
      .ok_or(ERROR_DEVICE_NOT_CONNECTED)
  }

  /// Is `enable` loaded.
  pub fn has_enable(&self) -> bool {
    self.enable.is_some()
  }

  /// Get audio device IDs for the controller.
  ///
  /// Not available in older versions of XInput.
  ///
  /// [MSDN](https://docs.microsoft.com/en-us/windows/desktop/api/xinput/nf-xinput-xinputgetaudiodeviceids)
  pub fn get_audio_device_ids(&self, controller: Controller) -> Result<AudioDeviceIDs, DWORD> {
    match self.get_audio_device_ids {
      Some(f) => unsafe {
        // Note(Lokathor): the capacity is an arbitrary "large" value so the
        // system has enough space to write in.
        let mut render_id = Vec::with_capacity(MAX_PATH);
        let mut capture_id = Vec::with_capacity(MAX_PATH);
        let mut render_count = 0;
        let mut capture_count = 0;
        let out = f(
          controller as DWORD,
          render_id.as_mut_ptr(),
          &mut render_count,
          capture_id.as_mut_ptr(),
          &mut capture_count,
        );
        if out == ERROR_SUCCESS {
          render_id.set_len(render_count as usize);
          capture_id.set_len(capture_count as usize);
          Ok(AudioDeviceIDs {
            render_id,
            capture_id,
          })
        } else {
          Err(out)
        }
      },
      None => Err(ERROR_DEVICE_NOT_CONNECTED),
    }
  }

  /// Is `get_audio_device_ids` loaded.
  pub fn has_get_audio_device_ids(&self) -> bool {
    self.get_audio_device_ids.is_some()
  }

  /// Attempts to get battery info for the controller.
  ///
  /// Not available in older versions of XInput.
  ///
  /// [MSDN](https://docs.microsoft.com/en-us/windows/desktop/api/xinput/nf-xinput-xinputgetbatteryinformation)
  pub fn get_battery_information(
    &self,
    controller: Controller,
    battery: BatteryDeviceType,
  ) -> Result<XINPUT_BATTERY_INFORMATION, DWORD> {
    match self.get_battery_information {
      Some(f) => unsafe {
        let mut battery_info = XINPUT_BATTERY_INFORMATION::zeroed();
        let out = f(controller as DWORD, battery as BYTE, &mut battery_info);
        if out == ERROR_SUCCESS {
          Ok(battery_info)
        } else {
          Err(out)
        }
      },
      None => Err(ERROR_DEVICE_NOT_CONNECTED),
    }
  }

  /// Is `get_battery_information` loaded.
  pub fn has_get_battery_information(&self) -> bool {
    self.get_battery_information.is_some()
  }

  /// Query the capabilities of the controller.
  ///
  /// The legacy "xinput9_1_0.dll" DLL will always return a fixed set of
  /// capabilities, regardless of the device's actual capabilities.
  ///
  /// [MSDN](https://docs.microsoft.com/en-us/windows/desktop/api/xinput/nf-xinput-xinputgetcapabilities)
  pub fn get_capabilities(
    &self,
    controller: Controller,
    gamepad: bool,
  ) -> Result<XINPUT_CAPABILITIES, DWORD> {
    match self.get_capabilities {
      Some(f) => unsafe {
        let mut capabilities = XINPUT_CAPABILITIES::zeroed();
        let flags = if gamepad { XINPUT_FLAG_GAMEPAD } else { 0 };
        let out = f(controller as DWORD, flags, &mut capabilities);
        if out == ERROR_SUCCESS {
          Ok(capabilities)
        } else {
          Err(out)
        }
      },
      None => Err(ERROR_DEVICE_NOT_CONNECTED),
    }
  }

  /// Is `get_capabilities` loaded.
  pub fn has_get_capabilities(&self) -> bool {
    self.get_capabilities.is_some()
  }

  /// Gets the DirectSound GUIDs for the controller.
  ///
  /// Note that if there is a controller connected but no headset with that
  /// controller you'll get `Ok(GUID_NULL)`.
  ///
  /// Not available in older versions of XInput.
  ///
  /// [MSDN](https://docs.microsoft.com/en-us/windows/desktop/api/xinput/nf-xinput-xinputgetdsoundaudiodeviceguids)
  pub fn get_dsound_audio_device_guids(&self, controller: Controller) -> Result<DSoundIDs, DWORD> {
    match self.get_dsound_audio_device_guids {
      Some(f) => unsafe {
        let mut ids: DSoundIDs = core::mem::zeroed();
        let out = f(
          controller as DWORD,
          &mut ids.render_guid,
          &mut ids.capture_guid,
        );
        if out == ERROR_SUCCESS {
          Ok(ids)
        } else {
          Err(out)
        }
      },
      None => Err(ERROR_DEVICE_NOT_CONNECTED),
    }
  }

  /// Is `get_dsound_audio_device_guids` loaded.
  pub fn has_get_dsound_audio_device_guids(&self) -> bool {
    self.get_dsound_audio_device_guids.is_some()
  }

  /// Gets a "keystroke" from the controller specified.
  ///
  /// If no controller is specified it gets the input from any connected
  /// controller.
  ///
  /// [MSDN](https://docs.microsoft.com/en-us/windows/desktop/api/xinput/nf-xinput-xinputgetkeystroke)
  pub fn get_keystroke(
    &self,
    opt_controller: Option<Controller>,
  ) -> Result<XINPUT_KEYSTROKE, DWORD> {
    match self.get_keystroke {
      Some(f) => unsafe {
        let mut keystroke = XINPUT_KEYSTROKE::zeroed();
        let out = f(
          opt_controller
            .map(|c| c as DWORD)
            .unwrap_or(XUSER_INDEX_ANY),
          0,
          &mut keystroke,
        );
        if out == ERROR_SUCCESS {
          Ok(keystroke)
        } else {
          Err(out)
        }
      },
      None => Err(ERROR_DEVICE_NOT_CONNECTED),
    }
  }

  /// Is `get_keystroke` loaded.
  pub fn has_get_keystroke(&self) -> bool {
    self.get_keystroke.is_some()
  }

  /// Gets the state of a controller.
  ///
  /// [MSDN](https://docs.microsoft.com/en-us/windows/desktop/api/xinput/nf-xinput-xinputgetstate)
  pub fn get_state(&self, controller: Controller) -> Result<XINPUT_STATE, DWORD> {
    match self.get_state {
      Some(f) => unsafe {
        let mut state = XINPUT_STATE::zeroed();
        let out = f(controller as DWORD, &mut state);
        if out == ERROR_SUCCESS {
          Ok(state)
        } else {
          Err(out)
        }
      },
      None => Err(ERROR_DEVICE_NOT_CONNECTED),
    }
  }

  /// Is `get_state` loaded.
  pub fn has_get_state(&self) -> bool {
    self.get_state.is_some()
  }

  /// Sets the vibration state of a controller.
  ///
  /// [MSDN](https://docs.microsoft.com/en-us/windows/desktop/api/xinput/nf-xinput-xinputsetstate)
  pub fn set_state(&self, controller: Controller, left: u16, right: u16) -> Result<(), DWORD> {
    match self.set_state {
      Some(f) => unsafe {
        let mut vibration = XINPUT_VIBRATION {
          wLeftMotorSpeed: left,
          wRightMotorSpeed: right,
        };
        let out = f(controller as DWORD, &mut vibration);
        if out == ERROR_SUCCESS {
          Ok(())
        } else {
          Err(out)
        }
      },
      None => Err(ERROR_DEVICE_NOT_CONNECTED),
    }
  }

  /// Is `set_state` loaded.
  pub fn has_set_state(&self) -> bool {
    self.set_state.is_some()
  }
}

/// You get one of these from [get_audio_device_ids](XInput::get_audio_device_ids)
#[derive(Debug, Clone)]
#[allow(missing_docs)]
pub struct AudioDeviceIDs {
  pub render_id: Vec<u16>,
  pub capture_id: Vec<u16>,
}

/// You get one of these from [get_dsound_audio_device_guids](XInput::get_dsound_audio_device_guids)
#[derive(Debug, Clone, Copy)]
#[allow(missing_docs)]
pub struct DSoundIDs {
  pub render_guid: GUID,
  pub capture_guid: GUID,
}
unsafe impl ZeroSafe for DSoundIDs {}

/// You use this with [get_battery_information](XInput::get_battery_information)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
#[allow(missing_docs)]
pub enum BatteryDeviceType {
  Gamepad = BATTERY_DEVTYPE_GAMEPAD,
  Headset = BATTERY_DEVTYPE_HEADSET,
}

/// The four controller identifiers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u32)]
#[allow(missing_docs)]
pub enum Controller {
  One = 0,
  Two = 1,
  Three = 2,
  Four = 3,
}
impl Controller {
  /// An array of all four controllers, in order.
  pub fn all() -> [Controller; 4] {
    [
      Controller::One,
      Controller::Two,
      Controller::Three,
      Controller::Four,
    ]
  }
}