mirror of
https://github.com/makecindy/cindy.git
synced 2026-12-02 07:49:49 +08:00
fix(desktop): read Windows Xbox controllers through XInput
Signed-off-by: Alan Z <3347202+A1aZ@users.noreply.github.com>
This commit is contained in:
@@ -6,7 +6,7 @@ license = "Apache-2.0"
|
||||
|
||||
[dependencies]
|
||||
serde_json = "1"
|
||||
windows = { version = "0.61", features = ["Gaming_Input", "Win32_System_WinRT"] }
|
||||
windows = { version = "0.61", features = ["Gaming_Input", "Win32_System_WinRT", "Win32_UI_Input_XboxController"] }
|
||||
|
||||
[profile.release]
|
||||
panic = "abort"
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
use super::*;
|
||||
#[test]
|
||||
fn lifecycle_messages_match_the_host_controller_contract_fixture() {
|
||||
#[derive(Clone)]
|
||||
struct FixtureDevice {
|
||||
handle: String,
|
||||
id: String,
|
||||
name: String,
|
||||
triggers: mapping::TriggerState,
|
||||
}
|
||||
let mut fixture: Value = serde_json::from_str(include_str!(
|
||||
"../../../../src/main/xbox-gamepad/__tests__/fixtures/windowsLifecycle.json"
|
||||
))
|
||||
.unwrap();
|
||||
// JavaScript JSON has one number type; native axes/triggers are f64.
|
||||
// Normalize only these declared numeric fields, not arbitrary payloads.
|
||||
for frame in fixture["frames"].as_object_mut().unwrap().values_mut() {
|
||||
for group in ["axes", "triggers"] {
|
||||
for number in frame[group].as_object_mut().unwrap().values_mut() {
|
||||
*number = json!(number.as_f64().unwrap());
|
||||
}
|
||||
}
|
||||
}
|
||||
for scenario in fixture["scenarios"].as_array().unwrap() {
|
||||
let mut current: BTreeMap<&'static str, FixtureDevice> = BTreeMap::new();
|
||||
for step in scenario["steps"].as_array().unwrap() {
|
||||
for _ in 0..step["repeat"].as_u64().unwrap_or(1) {
|
||||
let messages = match step["kind"].as_str().unwrap() {
|
||||
"snapshot" => {
|
||||
let preferred = current
|
||||
.iter()
|
||||
.map(|(&family, device)| (family, device.id.clone()))
|
||||
.collect();
|
||||
let candidates = step["devices"].as_array().unwrap().iter().map(|record| {
|
||||
let handle = record["handle"].as_str().unwrap();
|
||||
let existing = current
|
||||
.iter()
|
||||
.find(|(_, device)| device.handle == handle)
|
||||
.map(|(&family, device)| (family, device));
|
||||
reuse_live_device(existing, || {
|
||||
if record["metadataOk"] == false {
|
||||
return Err("metadata unavailable");
|
||||
}
|
||||
Ok((
|
||||
"xbox",
|
||||
FixtureDevice {
|
||||
handle: handle.into(),
|
||||
id: record["id"].as_str().unwrap().into(),
|
||||
name: record["name"].as_str().unwrap().into(),
|
||||
triggers: mapping::TriggerState::default(),
|
||||
},
|
||||
))
|
||||
})
|
||||
});
|
||||
let next =
|
||||
select_devices(candidates, &preferred, |device| device.id.as_str());
|
||||
let messages = snapshot_messages(
|
||||
"xbox",
|
||||
current
|
||||
.get("xbox")
|
||||
.map(|d| (d.id.as_str(), d.name.as_str())),
|
||||
next.get("xbox").map(|d| (d.id.as_str(), d.name.as_str())),
|
||||
step["force"].as_bool().unwrap_or(false),
|
||||
);
|
||||
current = next;
|
||||
messages
|
||||
}
|
||||
"frame" => {
|
||||
let reading = &fixture["readings"][step["frame"].as_str().unwrap()];
|
||||
let reading = windows::Gaming::Input::GamepadReading {
|
||||
LeftTrigger: reading["lt"].as_f64().unwrap(),
|
||||
RightThumbstickY: reading["ry"].as_f64().unwrap(),
|
||||
..Default::default()
|
||||
};
|
||||
vec![mapping::frame(
|
||||
"xbox",
|
||||
&reading,
|
||||
&mut current.get_mut("xbox").unwrap().triggers,
|
||||
)]
|
||||
}
|
||||
"read-error" => {
|
||||
current.remove("xbox");
|
||||
vec![presence_message("xbox", None)]
|
||||
}
|
||||
other => panic!("unknown fixture step {other}"),
|
||||
};
|
||||
let expected: Vec<Value> = step["messages"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|m| match m.as_str() {
|
||||
Some(key) => fixture["frames"][key].clone(),
|
||||
None => m.clone(),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
messages, expected,
|
||||
"scenario: {}, step: {}",
|
||||
scenario["name"], step["kind"]
|
||||
);
|
||||
assert_eq!(
|
||||
current.get("xbox").map(|d| d.name.as_str()),
|
||||
step["expect"]["name"].as_str()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn a_selected_live_handle_does_not_depend_on_fallible_metadata_refresh() {
|
||||
let old = "selected".to_string();
|
||||
let candidate = reuse_live_device(Some(("xbox", &old)), || Err("transient metadata error"));
|
||||
let selected = select_devices(
|
||||
[Ok(("xbox", "other".to_string())), candidate],
|
||||
&BTreeMap::from([("xbox", old.clone())]),
|
||||
|id| id.as_str(),
|
||||
);
|
||||
assert_eq!(selected.get("xbox"), Some(&old));
|
||||
}
|
||||
#[test]
|
||||
fn disappeared_handles_are_not_retained_by_cached_metadata() {
|
||||
let preferred = BTreeMap::from([("xbox", "removed".to_string())]);
|
||||
let candidate: std::result::Result<_, &str> =
|
||||
reuse_live_device(None, || Ok(("xbox", "replacement".to_string())));
|
||||
let selected = select_devices([candidate], &preferred, |id| id.as_str());
|
||||
assert_eq!(
|
||||
selected.get("xbox").map(String::as_str),
|
||||
Some("replacement")
|
||||
);
|
||||
let absent: Vec<std::result::Result<(&'static str, String), &str>> = Vec::new();
|
||||
assert!(select_devices(absent, &preferred, |id| id.as_str()).is_empty());
|
||||
}
|
||||
#[test]
|
||||
fn a_failed_device_probe_does_not_drop_healthy_devices() {
|
||||
let candidates = [
|
||||
Err("conversion failed"),
|
||||
Ok(("xbox", "first".to_string())),
|
||||
Err("property read failed"),
|
||||
Ok(("xbox", "selected".to_string())),
|
||||
Ok(("generic", "other".to_string())),
|
||||
];
|
||||
let preferred = BTreeMap::from([("xbox", "selected".to_string())]);
|
||||
let selected = select_devices(candidates, &preferred, |id| id.as_str());
|
||||
assert_eq!(
|
||||
selected,
|
||||
BTreeMap::from([
|
||||
("xbox", "selected".to_string()),
|
||||
("generic", "other".to_string())
|
||||
])
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn all_failed_probes_leave_an_empty_snapshot_without_terminating_the_host() {
|
||||
let candidates: [std::result::Result<(&'static str, String), &str>; 2] =
|
||||
[Err("removed"), Err("unreadable")];
|
||||
let selected = select_devices(candidates, &BTreeMap::new(), |id| id.as_str());
|
||||
assert!(selected.is_empty());
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
mod mapping;
|
||||
mod xinput;
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use std::{
|
||||
@@ -135,9 +136,11 @@ fn discover(
|
||||
))
|
||||
})
|
||||
});
|
||||
Ok(select_devices(candidates, &preferred, |device| {
|
||||
device.id.as_str()
|
||||
}))
|
||||
let mut selected = select_devices(candidates, &preferred, |device| device.id.as_str());
|
||||
// Xbox has one owner across USB/Bluetooth: XInput. Do not publish WGI's
|
||||
// enumerated-but-unreadable USB handle or mix its neutral frames into XInput.
|
||||
selected.remove("xbox");
|
||||
Ok(selected)
|
||||
}
|
||||
|
||||
/// Called only for a handle still present in the fresh Gamepads snapshot.
|
||||
@@ -174,167 +177,7 @@ fn select_devices<T, E>(
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod discovery_tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn lifecycle_messages_match_the_host_controller_contract_fixture() {
|
||||
#[derive(Clone)]
|
||||
struct FixtureDevice {
|
||||
handle: String,
|
||||
id: String,
|
||||
name: String,
|
||||
triggers: mapping::TriggerState,
|
||||
}
|
||||
let mut fixture: Value = serde_json::from_str(include_str!(
|
||||
"../../../../src/main/xbox-gamepad/__tests__/fixtures/windowsLifecycle.json"
|
||||
))
|
||||
.unwrap();
|
||||
// JavaScript JSON has one number type; native axes/triggers are f64.
|
||||
// Normalize only these declared numeric fields, not arbitrary payloads.
|
||||
for frame in fixture["frames"].as_object_mut().unwrap().values_mut() {
|
||||
for group in ["axes", "triggers"] {
|
||||
for number in frame[group].as_object_mut().unwrap().values_mut() {
|
||||
*number = json!(number.as_f64().unwrap());
|
||||
}
|
||||
}
|
||||
}
|
||||
for scenario in fixture["scenarios"].as_array().unwrap() {
|
||||
let mut current: BTreeMap<&'static str, FixtureDevice> = BTreeMap::new();
|
||||
for step in scenario["steps"].as_array().unwrap() {
|
||||
for _ in 0..step["repeat"].as_u64().unwrap_or(1) {
|
||||
let messages = match step["kind"].as_str().unwrap() {
|
||||
"snapshot" => {
|
||||
let preferred = current
|
||||
.iter()
|
||||
.map(|(&family, device)| (family, device.id.clone()))
|
||||
.collect();
|
||||
let candidates =
|
||||
step["devices"].as_array().unwrap().iter().map(|record| {
|
||||
let handle = record["handle"].as_str().unwrap();
|
||||
let existing = current
|
||||
.iter()
|
||||
.find(|(_, device)| device.handle == handle)
|
||||
.map(|(&family, device)| (family, device));
|
||||
reuse_live_device(existing, || {
|
||||
if record["metadataOk"] == false {
|
||||
return Err("metadata unavailable");
|
||||
}
|
||||
Ok((
|
||||
"xbox",
|
||||
FixtureDevice {
|
||||
handle: handle.into(),
|
||||
id: record["id"].as_str().unwrap().into(),
|
||||
name: record["name"].as_str().unwrap().into(),
|
||||
triggers: mapping::TriggerState::default(),
|
||||
},
|
||||
))
|
||||
})
|
||||
});
|
||||
let next =
|
||||
select_devices(candidates, &preferred, |device| device.id.as_str());
|
||||
let messages = snapshot_messages(
|
||||
"xbox",
|
||||
current
|
||||
.get("xbox")
|
||||
.map(|d| (d.id.as_str(), d.name.as_str())),
|
||||
next.get("xbox").map(|d| (d.id.as_str(), d.name.as_str())),
|
||||
step["force"].as_bool().unwrap_or(false),
|
||||
);
|
||||
current = next;
|
||||
messages
|
||||
}
|
||||
"frame" => {
|
||||
let reading = &fixture["readings"][step["frame"].as_str().unwrap()];
|
||||
let reading = windows::Gaming::Input::GamepadReading {
|
||||
LeftTrigger: reading["lt"].as_f64().unwrap(),
|
||||
RightThumbstickY: reading["ry"].as_f64().unwrap(),
|
||||
..Default::default()
|
||||
};
|
||||
vec![mapping::frame(
|
||||
"xbox",
|
||||
&reading,
|
||||
&mut current.get_mut("xbox").unwrap().triggers,
|
||||
)]
|
||||
}
|
||||
"read-error" => {
|
||||
current.remove("xbox");
|
||||
vec![presence_message("xbox", None)]
|
||||
}
|
||||
other => panic!("unknown fixture step {other}"),
|
||||
};
|
||||
let expected: Vec<Value> = step["messages"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|m| match m.as_str() {
|
||||
Some(key) => fixture["frames"][key].clone(),
|
||||
None => m.clone(),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
messages, expected,
|
||||
"scenario: {}, step: {}",
|
||||
scenario["name"], step["kind"]
|
||||
);
|
||||
assert_eq!(
|
||||
current.get("xbox").map(|d| d.name.as_str()),
|
||||
step["expect"]["name"].as_str()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn a_selected_live_handle_does_not_depend_on_fallible_metadata_refresh() {
|
||||
let old = "selected".to_string();
|
||||
let candidate = reuse_live_device(Some(("xbox", &old)), || Err("transient metadata error"));
|
||||
let selected = select_devices(
|
||||
[Ok(("xbox", "other".to_string())), candidate],
|
||||
&BTreeMap::from([("xbox", old.clone())]),
|
||||
|id| id.as_str(),
|
||||
);
|
||||
assert_eq!(selected.get("xbox"), Some(&old));
|
||||
}
|
||||
#[test]
|
||||
fn disappeared_handles_are_not_retained_by_cached_metadata() {
|
||||
let preferred = BTreeMap::from([("xbox", "removed".to_string())]);
|
||||
let candidate: std::result::Result<_, &str> =
|
||||
reuse_live_device(None, || Ok(("xbox", "replacement".to_string())));
|
||||
let selected = select_devices([candidate], &preferred, |id| id.as_str());
|
||||
assert_eq!(
|
||||
selected.get("xbox").map(String::as_str),
|
||||
Some("replacement")
|
||||
);
|
||||
let absent: Vec<std::result::Result<(&'static str, String), &str>> = Vec::new();
|
||||
assert!(select_devices(absent, &preferred, |id| id.as_str()).is_empty());
|
||||
}
|
||||
#[test]
|
||||
fn a_failed_device_probe_does_not_drop_healthy_devices() {
|
||||
let candidates = [
|
||||
Err("conversion failed"),
|
||||
Ok(("xbox", "first".to_string())),
|
||||
Err("property read failed"),
|
||||
Ok(("xbox", "selected".to_string())),
|
||||
Ok(("generic", "other".to_string())),
|
||||
];
|
||||
let preferred = BTreeMap::from([("xbox", "selected".to_string())]);
|
||||
let selected = select_devices(candidates, &preferred, |id| id.as_str());
|
||||
assert_eq!(
|
||||
selected,
|
||||
BTreeMap::from([
|
||||
("xbox", "selected".to_string()),
|
||||
("generic", "other".to_string())
|
||||
])
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn all_failed_probes_leave_an_empty_snapshot_without_terminating_the_host() {
|
||||
let candidates: [std::result::Result<(&'static str, String), &str>; 2] =
|
||||
[Err("removed"), Err("unreadable")];
|
||||
let selected = select_devices(candidates, &BTreeMap::new(), |id| id.as_str());
|
||||
assert!(selected.is_empty());
|
||||
}
|
||||
}
|
||||
mod discovery_tests;
|
||||
|
||||
fn run() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// SAFETY: initialize WinRT once on the polling thread, before constructing any WinRT objects.
|
||||
@@ -363,15 +206,27 @@ fn poll() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// Dropping the sender also stops on parent EOF/crash.
|
||||
});
|
||||
let mut devices = BTreeMap::<&'static str, Device>::new();
|
||||
let mut xbox = xinput::XboxInput::default();
|
||||
let mut refresh = true;
|
||||
let mut last_scan = Instant::now();
|
||||
let mut last_xinput_scan = Instant::now();
|
||||
loop {
|
||||
let scan_xinput = last_xinput_scan.elapsed() >= Duration::from_secs(1);
|
||||
if scan_xinput || refresh {
|
||||
last_xinput_scan = Instant::now();
|
||||
}
|
||||
for message in xbox.poll(refresh, scan_xinput, xinput::read) {
|
||||
emit(&message)?;
|
||||
}
|
||||
if dirty.swap(false, Ordering::Relaxed)
|
||||
|| refresh
|
||||
|| last_scan.elapsed() >= Duration::from_secs(1)
|
||||
{
|
||||
let mut next = discover(&devices)?;
|
||||
for family in FAMILIES {
|
||||
if family == "xbox" {
|
||||
continue;
|
||||
}
|
||||
let old = devices.get(family);
|
||||
let new = next.get_mut(family);
|
||||
let unchanged = match (old, new.as_deref()) {
|
||||
@@ -424,7 +279,7 @@ fn poll() -> Result<(), Box<dyn std::error::Error>> {
|
||||
for family in disconnected {
|
||||
devices.remove(family);
|
||||
}
|
||||
let interval = if devices.is_empty() {
|
||||
let interval = if devices.is_empty() && !xbox.connected() {
|
||||
Duration::from_millis(250)
|
||||
} else {
|
||||
Duration::from_millis(16)
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
use crate::mapping;
|
||||
use serde_json::{json, Value};
|
||||
use windows::Gaming::Input::{GamepadButtons, GamepadReading};
|
||||
use windows::Win32::UI::Input::XboxController::*;
|
||||
|
||||
/// One stable XInput slot owns the Xbox accessory; neutral input is not disconnect.
|
||||
#[derive(Default)]
|
||||
pub struct XboxInput {
|
||||
slot: Option<u32>,
|
||||
last_frame: Option<Value>,
|
||||
triggers: mapping::TriggerState,
|
||||
}
|
||||
|
||||
/// XInput 1.4 ships with supported Windows versions. No custom DLL loader or driver changes.
|
||||
pub fn read(slot: u32) -> Option<XINPUT_GAMEPAD> {
|
||||
let mut state = XINPUT_STATE::default();
|
||||
// SAFETY: state is initialized writable storage; slot is a bounded XInput user index.
|
||||
(unsafe { XInputGetState(slot, &mut state) } == 0).then_some(state.Gamepad)
|
||||
}
|
||||
|
||||
fn reading(pad: &XINPUT_GAMEPAD) -> GamepadReading {
|
||||
let mut buttons = GamepadButtons::None;
|
||||
for (native, mapped) in [
|
||||
(XINPUT_GAMEPAD_A, GamepadButtons::A),
|
||||
(XINPUT_GAMEPAD_B, GamepadButtons::B),
|
||||
(XINPUT_GAMEPAD_X, GamepadButtons::X),
|
||||
(XINPUT_GAMEPAD_Y, GamepadButtons::Y),
|
||||
(XINPUT_GAMEPAD_LEFT_SHOULDER, GamepadButtons::LeftShoulder),
|
||||
(XINPUT_GAMEPAD_RIGHT_SHOULDER, GamepadButtons::RightShoulder),
|
||||
(XINPUT_GAMEPAD_BACK, GamepadButtons::View),
|
||||
(XINPUT_GAMEPAD_START, GamepadButtons::Menu),
|
||||
(XINPUT_GAMEPAD_LEFT_THUMB, GamepadButtons::LeftThumbstick),
|
||||
(XINPUT_GAMEPAD_RIGHT_THUMB, GamepadButtons::RightThumbstick),
|
||||
(XINPUT_GAMEPAD_DPAD_UP, GamepadButtons::DPadUp),
|
||||
(XINPUT_GAMEPAD_DPAD_DOWN, GamepadButtons::DPadDown),
|
||||
(XINPUT_GAMEPAD_DPAD_LEFT, GamepadButtons::DPadLeft),
|
||||
(XINPUT_GAMEPAD_DPAD_RIGHT, GamepadButtons::DPadRight),
|
||||
] {
|
||||
if pad.wButtons.contains(native) {
|
||||
buttons |= mapped;
|
||||
}
|
||||
}
|
||||
// Signed sticks have asymmetric endpoints. Keep the existing positive-up convention
|
||||
// and leave action dead zones to the existing controller, just like WGI frames.
|
||||
let axis = |v: i16| f64::from(v) / if v < 0 { 32768.0 } else { 32767.0 };
|
||||
GamepadReading {
|
||||
Buttons: buttons,
|
||||
LeftTrigger: f64::from(pad.bLeftTrigger) / 255.0,
|
||||
RightTrigger: f64::from(pad.bRightTrigger) / 255.0,
|
||||
LeftThumbstickX: axis(pad.sThumbLX),
|
||||
LeftThumbstickY: axis(pad.sThumbLY),
|
||||
RightThumbstickX: axis(pad.sThumbRX),
|
||||
RightThumbstickY: axis(pad.sThumbRY),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn presence(slot: Option<u32>) -> Value {
|
||||
match slot {
|
||||
Some(slot) => json!({"kind":"presence", "family":"xbox", "present":true,
|
||||
"name":format!("Xbox Controller (XInput {})", slot + 1),
|
||||
"category":"XInput", "transport":"unknown"}),
|
||||
None => json!({"kind":"presence", "family":"xbox", "present":false}),
|
||||
}
|
||||
}
|
||||
|
||||
impl XboxInput {
|
||||
pub fn connected(&self) -> bool {
|
||||
self.slot.is_some()
|
||||
}
|
||||
|
||||
pub fn poll(
|
||||
&mut self,
|
||||
force: bool,
|
||||
scan: bool,
|
||||
mut read: impl FnMut(u32) -> Option<XINPUT_GAMEPAD>,
|
||||
) -> Vec<Value> {
|
||||
let old = self.slot;
|
||||
let mut messages = Vec::new();
|
||||
let mut sample = old.and_then(|slot| read(slot).map(|pad| (slot, pad)));
|
||||
let lost = old.is_some() && sample.is_none();
|
||||
if lost {
|
||||
messages.push(presence(None));
|
||||
self.slot = None;
|
||||
self.last_frame = None;
|
||||
self.triggers = mapping::TriggerState::default();
|
||||
}
|
||||
if sample.is_none() && (scan || force || lost) {
|
||||
sample = (0..4)
|
||||
.filter(|slot| Some(*slot) != old)
|
||||
.find_map(|slot| read(slot).map(|pad| (slot, pad)));
|
||||
}
|
||||
if let Some((slot, pad)) = sample {
|
||||
if self.slot != Some(slot) {
|
||||
self.slot = Some(slot);
|
||||
self.last_frame = None;
|
||||
self.triggers = mapping::TriggerState::default();
|
||||
messages.push(presence(self.slot));
|
||||
} else if force {
|
||||
messages.push(presence(self.slot));
|
||||
}
|
||||
let frame = mapping::frame("xbox", &reading(&pad), &mut self.triggers);
|
||||
if force || self.last_frame.as_ref() != Some(&frame) {
|
||||
messages.push(frame.clone());
|
||||
self.last_frame = Some(frame);
|
||||
}
|
||||
} else if force && !lost {
|
||||
messages.push(presence(None));
|
||||
}
|
||||
messages
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_xinput_button_maps_to_exactly_one_protocol_button() {
|
||||
for (button, key) in [
|
||||
(XINPUT_GAMEPAD_A, "a"),
|
||||
(XINPUT_GAMEPAD_B, "b"),
|
||||
(XINPUT_GAMEPAD_X, "x"),
|
||||
(XINPUT_GAMEPAD_Y, "y"),
|
||||
(XINPUT_GAMEPAD_LEFT_SHOULDER, "lb"),
|
||||
(XINPUT_GAMEPAD_RIGHT_SHOULDER, "rb"),
|
||||
(XINPUT_GAMEPAD_BACK, "view"),
|
||||
(XINPUT_GAMEPAD_START, "menu"),
|
||||
(XINPUT_GAMEPAD_LEFT_THUMB, "ls"),
|
||||
(XINPUT_GAMEPAD_RIGHT_THUMB, "rs"),
|
||||
(XINPUT_GAMEPAD_DPAD_UP, "dpadUp"),
|
||||
(XINPUT_GAMEPAD_DPAD_DOWN, "dpadDown"),
|
||||
(XINPUT_GAMEPAD_DPAD_LEFT, "dpadLeft"),
|
||||
(XINPUT_GAMEPAD_DPAD_RIGHT, "dpadRight"),
|
||||
] {
|
||||
let frame = mapping::frame(
|
||||
"xbox",
|
||||
&reading(&XINPUT_GAMEPAD {
|
||||
wButtons: button,
|
||||
..Default::default()
|
||||
}),
|
||||
&mut mapping::TriggerState::default(),
|
||||
);
|
||||
assert_eq!(frame["buttons"][key], true, "{key}");
|
||||
assert_eq!(
|
||||
frame["buttons"]
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.values()
|
||||
.filter(|v| **v == true)
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xinput_frames_match_the_shared_host_controller_lifecycle_fixture() {
|
||||
let fixture: Value = serde_json::from_str(include_str!(
|
||||
"../../../../src/main/xbox-gamepad/__tests__/fixtures/windowsLifecycle.json"
|
||||
))
|
||||
.unwrap();
|
||||
for (key, pad) in [
|
||||
("neutral", XINPUT_GAMEPAD::default()),
|
||||
(
|
||||
"held",
|
||||
XINPUT_GAMEPAD {
|
||||
bLeftTrigger: 255,
|
||||
sThumbRY: i16::MAX,
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
] {
|
||||
let mut expected = fixture["frames"][key].clone();
|
||||
for group in ["axes", "triggers"] {
|
||||
for value in expected[group].as_object_mut().unwrap().values_mut() {
|
||||
*value = json!(value.as_f64().unwrap());
|
||||
}
|
||||
}
|
||||
let mut xbox = XboxInput::default();
|
||||
let messages = xbox.poll(true, true, |_| Some(pad));
|
||||
assert_eq!(messages.last().unwrap(), &expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wired_input_and_neutral_release_use_xinput_without_wgi() {
|
||||
let mut xbox = XboxInput::default();
|
||||
let held = XINPUT_GAMEPAD {
|
||||
wButtons: XINPUT_GAMEPAD_A | XINPUT_GAMEPAD_DPAD_UP,
|
||||
bLeftTrigger: 255,
|
||||
bRightTrigger: 128,
|
||||
sThumbLX: i16::MIN,
|
||||
sThumbLY: i16::MAX,
|
||||
sThumbRX: i16::MAX,
|
||||
sThumbRY: i16::MIN,
|
||||
};
|
||||
let messages = xbox.poll(true, true, |slot| (slot == 0).then_some(held));
|
||||
assert_eq!(messages[0]["present"], true);
|
||||
let frame = messages.last().unwrap();
|
||||
assert_eq!(frame["buttons"]["a"], true);
|
||||
assert_eq!(frame["buttons"]["dpadUp"], true);
|
||||
assert_eq!(frame["buttons"]["lt"], true);
|
||||
assert_eq!(
|
||||
frame["axes"],
|
||||
serde_json::json!({"lx":-1.0,"ly":1.0,"rx":1.0,"ry":-1.0})
|
||||
);
|
||||
assert_eq!(frame["triggers"]["rt"], 128.0 / 255.0);
|
||||
let released = xbox.poll(false, false, |_| Some(XINPUT_GAMEPAD::default()));
|
||||
assert!(released[0]["buttons"]
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.values()
|
||||
.all(|v| v == false));
|
||||
assert!(xbox
|
||||
.poll(false, false, |_| Some(XINPUT_GAMEPAD::default()))
|
||||
.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_is_stable_and_removal_releases_before_replacement() {
|
||||
let mut xbox = XboxInput::default();
|
||||
xbox.poll(true, true, |slot| {
|
||||
(slot == 2).then_some(XINPUT_GAMEPAD::default())
|
||||
});
|
||||
let mut queried = Vec::new();
|
||||
let messages = xbox.poll(false, true, |slot| {
|
||||
queried.push(slot);
|
||||
Some(XINPUT_GAMEPAD::default())
|
||||
});
|
||||
assert_eq!(queried, vec![2]);
|
||||
assert!(messages.is_empty());
|
||||
let messages = xbox.poll(false, false, |slot| {
|
||||
(slot == 1).then_some(XINPUT_GAMEPAD::default())
|
||||
});
|
||||
assert_eq!(messages[0]["present"], false);
|
||||
assert_eq!(messages[1]["present"], true);
|
||||
assert_eq!(messages[2]["kind"], "frame");
|
||||
assert_eq!(
|
||||
xbox.poll(false, false, |_| None),
|
||||
vec![serde_json::json!({"kind":"presence","family":"xbox","present":false})]
|
||||
);
|
||||
let mut queried = Vec::new();
|
||||
assert!(xbox
|
||||
.poll(false, false, |slot| {
|
||||
queried.push(slot);
|
||||
None
|
||||
})
|
||||
.is_empty());
|
||||
assert!(
|
||||
queried.is_empty(),
|
||||
"empty slots must not be polled every frame"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn probes_preserve_trigger_hysteresis_and_force_a_fresh_frame() {
|
||||
let mut xbox = XboxInput::default();
|
||||
for (pressure, pressed) in [(153, true), (128, true), (102, false)] {
|
||||
let messages = xbox.poll(true, true, |_| {
|
||||
Some(XINPUT_GAMEPAD {
|
||||
bLeftTrigger: pressure,
|
||||
..Default::default()
|
||||
})
|
||||
});
|
||||
assert_eq!(messages.last().unwrap()["buttons"]["lt"], pressed);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -232,6 +232,34 @@ A pre-migration stash was retained as a recovery copy.
|
||||
trigger pressure and stick axes. This is evidence of a native reading-path gap,
|
||||
not proof of a cable fault or proof that a replacement backend is already fixed.
|
||||
|
||||
### Follow-up: USB Xbox input (Codex 3976765716)
|
||||
|
||||
- Xbox/XInput-compatible controllers now use XInput 1.4, not WGI readings, for
|
||||
both USB and Bluetooth. WGI no longer publishes the Xbox family, avoiding a
|
||||
second presence owner or stale neutral frames overwriting XInput input.
|
||||
- The selected XInput slot remains stable while readable; failure emits absence
|
||||
before a replacement's presence/frame, resets trigger state, and releases via
|
||||
the existing Host/controller protocol. Empty slots are scanned on a one-second
|
||||
cadence or explicit probe, not every frame. No idle-frame fallback heuristic.
|
||||
- XInput has slot identity rather than WGI device names: the accessory reports
|
||||
Xbox Controller (XInput N), category XInput, and unknown transport rather than
|
||||
pretending to infer a physical device name or USB/Bluetooth mapping. Native
|
||||
non-XInput PlayStation/Nintendo/generic controllers retain their WGI path;
|
||||
controllers exposed by external XInput emulators appear in the Xbox slot.
|
||||
- RED: three new tests failed at the missing XInput implementation. GREEN: all
|
||||
16 Rust tests and six shared Host/controller contract tests passed, including
|
||||
every supported button, axis endpoints, trigger normalization/hysteresis,
|
||||
stable multi-slot selection, actual read failure, and exactly ordered release.
|
||||
- Clippy --all-targets and release build passed. Existing discovery tests moved
|
||||
unchanged to a sibling test module to satisfy the all-targets Clippy check.
|
||||
- Live USB enumeration still succeeds. The new helper read a non-neutral D-pad
|
||||
state, but this unattended 30-second capture did not show a press/release
|
||||
sequence. Do NOT count it as complete physical input or UI acceptance; user
|
||||
retest and Bluetooth regression on the new backend remain required.
|
||||
- cargo-llvm-cov is not installed, so no numerical coverage claim is made.
|
||||
- Required submission gates passed: root related unit gate (Desktop 152.7 seconds),
|
||||
Desktop typecheck, Rust formatting and diff checks.
|
||||
|
||||
Accuracy 4/5: passing tests and actual native-load failure recorded; live input unverified.
|
||||
Completeness 4/5: bridge connection verified; physical input and full UI still need validation.
|
||||
Clarity 4/5: separates path discovery from functional support; findings span two different devices.
|
||||
|
||||
Reference in New Issue
Block a user