Repository navigation
Implement XInput user index resolution in device view - #434
Conversation
|
No actionable comments were generated in the recent review. ð âđïļ Recent review infoâïļ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: ð Files selected for processing (1)
ð§ Files skipped from review as they are similar to previous changes (1)
ð WalkthroughWalkthroughAdded Cfgmgr32 P/Invoke declarations for device-interface enumeration; implemented an XInput slot resolver that maps DsHidMini devices to XInput user indices via interface enumeration and IOCTL; surfaced XInput slot properties in the Device view model and views; invalidate resolver cache on device/config updates. Changes
Sequence Diagram(s)sequenceDiagram
participant UI as DeviceViewModel (UI)
participant Resolver as XInputSlotResolver
participant SetupAPI as Cfgmgr32 / SetupAPI
participant Kernel as Kernel (CreateFile / DeviceIoControl)
UI->>Resolver: TryGetXInputUserIndex(dshmDevice)
Resolver->>SetupAPI: CM_Get_Device_Interface_List_SizeW / CM_Get_Device_Interface_ListW
SetupAPI-->>Resolver: interface symlink list
loop per symlink
Resolver->>SetupAPI: resolve interface -> device instance / base container ID
alt base container matches
Resolver->>Kernel: CreateFile(symlink)
Kernel-->>Resolver: handle
Resolver->>Kernel: DeviceIoControl(IOCTL_XUSB_GET_LED_STATE)
Kernel-->>Resolver: LED state byte
Resolver-->>UI: mapped userIndex (success)
else no match or failure
Resolver-->>Resolver: continue
end
end
Resolver-->>UI: false (if none matched)
Estimated code review effortðŊ 4 (Complex) | âąïļ ~45 minutes Possibly related PRs
Suggested labels
Poem
ðĨ Pre-merge checks | â 2 | â 1â Failed checks (1 warning)
â Passed checks (2 passed)
âïļ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
ð§đ Nitpick comments (3)
ControlApp/Models/Util/XInputSlotResolver.cs (3)
41-41: Document the IOCTL code origin.
0x8000E008is the same IOCTL used by XInputBridge'sGlobalState::SymlinkToUserIndex; a brief comment referencing the source (like the one onXinputLedToPortMapat line 44) would help future maintainers trace the value and avoid accidental divergence.ðĪ Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@ControlApp/Models/Util/XInputSlotResolver.cs` at line 41, Add a brief comment above the IoctlXusbGetLedState constant documenting its origin and linking it to the same IOCTL used by XInputBridge's GlobalState::SymlinkToUserIndex (similar to the comment on XinputLedToPortMap); mention the original source/identifier (XInputBridge) and the hexadecimal value 0x8000E008 so future maintainers can trace and verify the constant in XInputSlotResolver.cs.
71-99: Consider caching the resolved slot per container.
TryGetXInputUserIndexre-enumerates all present XUSB device interfaces and issues an IOCTL for each candidate on every call. With multiple DsHidMini devices being refreshed (e.g., on page navigation), this scales as O(N·M). Caching by container ID (with invalidation on PnP change notifications or mode transitions) would noticeably reduce latency and system-call load.ðĪ Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@ControlApp/Models/Util/XInputSlotResolver.cs` around lines 71 - 99, TryGetXInputUserIndex currently re-enumerates all XUSB interfaces and issues IOCTLs on every call; add a thread-safe cache mapping the container Guid (from TryGetBaseContainerId) to the resolved byte userIndex (including negative cache for not-found using InvalidXInputUserId) to avoid repeated work. On entry to TryGetXInputUserIndex check the cache for dshmContainer and return cached value if present; on miss perform the existing enumeration/TrySymlinkToUserIndex logic, store the result in the cache before returning. Ensure cache is invalidated/cleared in the PnP change notification and mode-transition handlers (where device topology changes are observed) so stale mappings are removed; use a concurrent structure (e.g., ConcurrentDictionary) or proper locking to make caching safe across threads.
101-146: Hardcoded* 2for WCHAR size â usesizeof(char)for clarity.
Marshal.AllocHGlobal((int)(lenChars * 2))andint byteLen = (int)(lenChars * 2)assume 2 bytes per WCHAR. While correct on Windows, usingsizeof(char)(or a named constant) makes the intent explicit and avoids the magic number. Also consider guarding the(int)cast against overflow for very large interface lists, though in practicelenCharsis tiny.ðĪ Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@ControlApp/Models/Util/XInputSlotResolver.cs` around lines 101 - 146, Replace the hardcoded "* 2" byte-size math in EnumeratePresentXusbDeviceInterfacePaths with an explicit char-size expression and guard the cast to int: use lenChars * sizeof(char) (or a named constant like WCHAR_SIZE) when calling Marshal.AllocHGlobal and computing byteLen, and check that (lenChars * sizeof(char)) does not exceed int.MaxValue before casting (throw or yield break on overflow) so the Marshal.AllocHGlobal((int)... ) and int byteLen = (int)... are safe; update references in the same method where the "* 2" appears.
ðĪ Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@ControlApp/Models/Util/XInputSlotResolver.cs`:
- Around line 270-286: The nullable annotation on SafeFileHandle is incorrect:
change the using declaration in TrySymlinkToUserIndex to use non-nullable
SafeFileHandle (remove the '?') when calling PInvoke.CreateFile; keep the
subsequent handle.IsInvalid check and using disposal as-is since CreateFile
returns a non-null SafeFileHandle even on failure, and no other logic needs to
change.
In `@ControlApp/ViewModels/UserControls/DeviceViewModel.cs`:
- Around line 461-484: RefreshXInputSlotLabel synchronously calls
XInputSlotResolver.TryGetXInputUserIndex which performs blocking P/Invoke work
on the UI thread; change RefreshXInputSlotLabel to run the resolve off the UI
thread (e.g. call await Task.Run(() =>
XInputSlotResolver.TryGetXInputUserIndex(Device, out byte userIndex))) then
marshal the resulting UI updates (XInputSlotDetail, XInputSlotBanner and
OnPropertyChanged(nameof(IsXInputHidMode))) back to the UI thread before setting
them; update callers such as DevicesViewModel.OnNavigatedToAsync and
ApplyChanges to await the new async RefreshXInputSlotLabel method or otherwise
schedule the background work so the enumeration/DeviceIoControl calls no longer
block the UI.
---
Nitpick comments:
In `@ControlApp/Models/Util/XInputSlotResolver.cs`:
- Line 41: Add a brief comment above the IoctlXusbGetLedState constant
documenting its origin and linking it to the same IOCTL used by XInputBridge's
GlobalState::SymlinkToUserIndex (similar to the comment on XinputLedToPortMap);
mention the original source/identifier (XInputBridge) and the hexadecimal value
0x8000E008 so future maintainers can trace and verify the constant in
XInputSlotResolver.cs.
- Around line 71-99: TryGetXInputUserIndex currently re-enumerates all XUSB
interfaces and issues IOCTLs on every call; add a thread-safe cache mapping the
container Guid (from TryGetBaseContainerId) to the resolved byte userIndex
(including negative cache for not-found using InvalidXInputUserId) to avoid
repeated work. On entry to TryGetXInputUserIndex check the cache for
dshmContainer and return cached value if present; on miss perform the existing
enumeration/TrySymlinkToUserIndex logic, store the result in the cache before
returning. Ensure cache is invalidated/cleared in the PnP change notification
and mode-transition handlers (where device topology changes are observed) so
stale mappings are removed; use a concurrent structure (e.g.,
ConcurrentDictionary) or proper locking to make caching safe across threads.
- Around line 101-146: Replace the hardcoded "* 2" byte-size math in
EnumeratePresentXusbDeviceInterfacePaths with an explicit char-size expression
and guard the cast to int: use lenChars * sizeof(char) (or a named constant like
WCHAR_SIZE) when calling Marshal.AllocHGlobal and computing byteLen, and check
that (lenChars * sizeof(char)) does not exceed int.MaxValue before casting
(throw or yield break on overflow) so the Marshal.AllocHGlobal((int)... ) and
int byteLen = (int)... are safe; update references in the same method where the
"* 2" appears.
ðŠ Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
âđïļ Review info
âïļ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 2ad125c0-2106-4c01-bb09-2004773ee5ee
ð Files selected for processing (5)
ControlApp/Models/Util/SetupApiWrapper.csControlApp/Models/Util/XInputSlotResolver.csControlApp/ViewModels/UserControls/DeviceViewModel.csControlApp/Views/Pages/DevicesPage.xamlControlApp/Views/UserControls/DeviceUserControl.xaml
There was a problem hiding this comment.
Actionable comments posted: 2
ðĪ Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@ControlApp/Models/Util/XInputSlotResolver.cs`:
- Around line 93-125: The negative cache is being poisoned by always writing
InvalidXInputUserId into ResolutionCacheByBaseContainer on any miss; change
Resolve logic in the block using ResolutionCacheByBaseContainer,
EnumeratePresentXusbDeviceInterfacePaths,
TryGetDeviceInstanceIdFromInterfacePath, TryGetBaseContainerId and
TrySymlinkToUserIndex so that you only write a cache entry on successful
resolutions (set ResolutionCacheByBaseContainer[dshmContainer] = idx only when a
valid idx is found), and remove or modify the unconditional write of
InvalidXInputUserId at the end; if you need negative caching, replace that
unconditional sentinel write with a timestamped/TTL negative entry or an
explicit short-lived retry mechanism so transient DeviceIoControl/settling races
don't permanently block future resolution attempts.
In `@ControlApp/ViewModels/UserControls/DeviceViewModel.cs`:
- Around line 482-487: The current stale-result guard comparing
device.InstanceId to Device.InstanceId is ineffective because Device is
immutable; implement a refresh-generation counter (e.g., an int
_refreshGeneration on the DeviceViewModel) or a CancellationTokenSource to mark
the generation when starting an async refresh and capture its value/token in the
awaited task, then inside the Application.Current.Dispatcher.InvokeAsync
callback verify the captured generation/token still matches the current one
before updating slot labels (replace uses of device.InstanceId/Device.InstanceId
with this generation/token check) so slower older refreshes cannot overwrite
newer results.
ðŠ Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
âđïļ Review info
âïļ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: d422d918-a8b6-4312-b901-bdf6e612a160
ð Files selected for processing (4)
ControlApp/Models/DshmDevMan.csControlApp/Models/Util/XInputSlotResolver.csControlApp/ViewModels/Pages/DevicesViewModel.csControlApp/ViewModels/UserControls/DeviceViewModel.cs
There was a problem hiding this comment.
Actionable comments posted: 2
ðĪ Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@ControlApp/Models/Util/XInputSlotResolver.cs`:
- Around line 102-135: The current logic checks
NegativeResolutionExpiryByBaseContainer before ResolutionCacheByBaseContainer
which can cause a race where a later negative entry masks an earlier positive
cache; change the order so you first check ResolutionCacheByBaseContainer and
return the cached userIndex if present, and only then check
NegativeResolutionExpiryByBaseContainer for a recent negative TTL; keep the
existing behavior of removing negative entries on a successful discovery
(NegativeResolutionExpiryByBaseContainer.TryRemove) and leave the rest of the
enumeration logic (EnumeratePresentXusbDeviceInterfacePaths,
TryGetDeviceInstanceIdFromInterfacePath, TryGetBaseContainerId,
TrySymlinkToUserIndex, InvalidXInputUserId) unchanged.
- Around line 45-55: The DEVPKEY constants DevpKeyDeviceInstanceId and
DevpKeyDeviceBaseContainerId are incorrect; replace their handwritten
integer-based constructors with the exact Windows SDK DEVPROPKEY values:
DEVPKEY_Device_InstanceId (GUID 78C34FC8-104A-4ACA-9EA4-524D5294395D, PID 256)
and DEVPKEY_Device_BaseContainerId (GUID 80497100-8C73-48EA-8708-33A16B1877FA,
PID 2). To avoid byte-order mistakes, construct them using
Guid.Parse("78c34fc8-104a-4aca-9ea4-524d5294395d") and
Guid.Parse("80497100-8c73-48ea-8708-33a16b1877fa") (or new Guid(string)) and
pass the correct property id values when creating the SetupApiWrapper.DevPropKey
instances used by CM_Get_Device_Interface_Property and CM_Get_DevNode_Property
(symbols: DevpKeyDeviceInstanceId, DevpKeyDeviceBaseContainerId).
ðŠ Autofix (Beta)
â Autofix completed
âđïļ Review info
âïļ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 79007987-dc74-4a70-9052-8770c80e5462
ð Files selected for processing (2)
ControlApp/Models/Util/XInputSlotResolver.csControlApp/ViewModels/UserControls/DeviceViewModel.cs
There was a problem hiding this comment.
âŧïļ Duplicate comments (1)
ControlApp/Models/Util/XInputSlotResolver.cs (1)
93-126:â ïļ Potential issue | ðĄ MinorCheck the positive cache before honoring a negative TTL.
A concurrent miss can still write a negative entry after another thread has cached a valid index, and the current order makes that negative entry mask the success until the TTL expires. This is the same cache-ordering race previously flagged.
ð Proposed fix
- if (NegativeResolutionExpiryByBaseContainer.TryGetValue(dshmContainer, out DateTime negUntil) - && DateTime.UtcNow < negUntil) - { - return false; - } - if (ResolutionCacheByBaseContainer.TryGetValue(dshmContainer, out byte cached)) { userIndex = cached; return true; } + + if (NegativeResolutionExpiryByBaseContainer.TryGetValue(dshmContainer, out DateTime negUntil) + && DateTime.UtcNow < negUntil) + { + return false; + } @@ - NegativeResolutionExpiryByBaseContainer[dshmContainer] = DateTime.UtcNow.Add(NegativeResolutionCacheTtl); + if (!ResolutionCacheByBaseContainer.ContainsKey(dshmContainer)) + { + NegativeResolutionExpiryByBaseContainer[dshmContainer] = DateTime.UtcNow.Add(NegativeResolutionCacheTtl); + } return false;ðĪ Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@ControlApp/Models/Util/XInputSlotResolver.cs` around lines 93 - 126, The code currently checks NegativeResolutionExpiryByBaseContainer before the positive ResolutionCacheByBaseContainer which allows a race where a concurrent successful resolution writes ResolutionCacheByBaseContainer after we pass the cache check but before we write a negative TTL; to fix, before writing NegativeResolutionExpiryByBaseContainer[dshmContainer] = ..., re-check ResolutionCacheByBaseContainer.TryGetValue(dshmContainer, out byte cached) and if present set userIndex = cached and return true (this mirrors the positive-path cache hit behavior and prevents overwriting a fresh positive entry with a negative TTL).
ðĪ Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Duplicate comments:
In `@ControlApp/Models/Util/XInputSlotResolver.cs`:
- Around line 93-126: The code currently checks
NegativeResolutionExpiryByBaseContainer before the positive
ResolutionCacheByBaseContainer which allows a race where a concurrent successful
resolution writes ResolutionCacheByBaseContainer after we pass the cache check
but before we write a negative TTL; to fix, before writing
NegativeResolutionExpiryByBaseContainer[dshmContainer] = ..., re-check
ResolutionCacheByBaseContainer.TryGetValue(dshmContainer, out byte cached) and
if present set userIndex = cached and return true (this mirrors the
positive-path cache hit behavior and prevents overwriting a fresh positive entry
with a negative TTL).
âđïļ Review info
âïļ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 992a6374-9253-4e9a-8b30-4530a246351c
ð Files selected for processing (1)
ControlApp/Models/Util/XInputSlotResolver.cs
|
Note Autofix is a beta feature. Expect some limitations and changes as we gather feedback and continue to improve it. Fixes Applied SuccessfullyFixed 2 file(s) based on 1 unresolved review comment. Files modified:
Commit: The changes have been pushed to the Time taken: |
Fixed 2 file(s) based on 1 unresolved review comment. Co-authored-by: CodeRabbit <noreply@coderabbit.ai>
There was a problem hiding this comment.
Actionable comments posted: 1
ðĪ Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@ControlApp/Models/Util/XInputSlotResolver.cs`:
- Around line 35-38: InvalidateResolutionCache can race with
TryGetXInputUserIndex because a thread can compute and write stale entries after
a clear; fix by adding a cache-generation token (e.g. a long _cacheGeneration
incremented inside InvalidateResolutionCache) and modify TryGetXInputUserIndex
so it captures the generation before resolving and only performs writes to
ResolutionCacheByBaseContainer and NegativeResolutionExpiryByBaseContainer if
the captured generation still equals the current _cacheGeneration; reference the
methods InvalidateResolutionCache() and TryGetXInputUserIndex() and the
dictionaries ResolutionCacheByBaseContainer /
NegativeResolutionExpiryByBaseContainer when making the change.
ðŠ Autofix (Beta)
â Autofix completed
âđïļ Review info
âïļ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: a8680848-bfcf-4dba-b08a-7b1ccd8e86c0
ð Files selected for processing (2)
ControlApp/Models/Util/XInputSlotResolver.csbuild/_build.csproj
â Files skipped from review due to trivial changes (1)
- build/_build.csproj
|
Note Autofix is a beta feature. Expect some limitations and changes as we gather feedback and continue to improve it. Fixes Applied SuccessfullyFixed 1 file(s) based on 1 unresolved review comment. Files modified:
Commit: The changes have been pushed to the Time taken: |
Fixed 1 file(s) based on 1 unresolved review comment. Co-authored-by: CodeRabbit <noreply@coderabbit.ai>
Summary by CodeRabbit
New Features
Chores