diff --git a/CHANGELOG.en-US.md b/CHANGELOG.en-US.md index 2c49672..42114f8 100644 --- a/CHANGELOG.en-US.md +++ b/CHANGELOG.en-US.md @@ -6,6 +6,7 @@ English (US) release notes, mirroring CHANGELOG.md (Brazilian Portuguese). Befor ### Changes - **Receive test versions** now brings betas only. Alpha versions, like those of the upcoming 2.0, are closed tests and no longer arrive through the app's updates, even with the option on. (#223) ### Fixes +- Controller: the centre button of other brands' pads (Amazon Luna, 8BitDo, Stadia…) now opens Console Mode like the Xbox button, when the pad declares that button the standard HID way. Before, only the Xbox and PS buttons worked, and those pads needed a two-button shortcut (reported by PLEXX-DE, issue #217). (#226) - Controller battery: on Bluetooth pads, the corner of the screen shows the same value as Windows Settings → Bluetooth. Some pads sent Windows a fixed value through the other path (an Amazon Luna pad always showed 10 % while at 90 %; reported by PLEXX-DE, issue #224). PlayStation pads still read the battery from the pad itself. (#225) ## [1.7.1-beta.3] diff --git a/CHANGELOG.md b/CHANGELOG.md index e93ef5c..289957d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ Notas em português do Brasil; a versão em inglês (Estados Unidos) fica em `CH ### Mudanças - **Receber versões de teste** agora traz só as betas. As versões alpha, como as da futura 2.0, são testes fechados e não chegam mais pela atualização do app, nem com a opção ligada. (#223) ### Correções +- Controle: o botão central de controles de outras marcas (Amazon Luna, 8BitDo, Stadia…) passa a abrir o Console Mode como o botão Xbox, quando o controle declara esse botão do jeito padrão do HID. Antes só os botões Xbox e PS funcionavam, e esses controles precisavam de um atalho com dois botões (relatado pelo PLEXX-DE, issue #217). (#226) - Bateria do controle: nos controles Bluetooth, o canto da tela mostra o mesmo valor das Configurações do Windows → Bluetooth. Alguns controles mandavam ao Windows um valor fixo pelo outro caminho (um Amazon Luna aparecia sempre com 10 % estando em 90 %; relatado pelo PLEXX-DE, issue #224). Os controles PlayStation continuam lendo a bateria pelo próprio controle. (#225) ## [1.7.1-beta.3] diff --git a/docs/TESTING.md b/docs/TESTING.md index 08361ed..4739e98 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -547,6 +547,13 @@ Pré-requisito: RivaTuner Statistics Server instalado, com "Show On-Screen Displ - [ ] Com a sessão ativa e a opção ligada, minimizar e reabrir pela bandeja continua funcionando; o atalho do controle para abrir o app também traz a janela de volta. - [ ] Fechar no X (sem sessão ativa) continua fechando o app, com a opção ligada ou desligada. +## Botão central de outras marcas (#226, issue #217) + +- [ ] Controle que não é Xbox nem PlayStation (Amazon Luna, 8BitDo, Stadia…), com o atalho para abrir o Console Mode no botão Xbox (padrão): o log tem "Controle: lendo o botão central pelo HID (, …)" e segurar o botão central com o app na bandeja abre o modo console. Resultado: ______ +- [ ] Se o log disser "…mas o Windows não deixa ler esse dispositivo" ou não falar do botão central: anotar o vid:pid e mandar o diagnóstico do Teste de controle. Resultado: ______ +- [ ] Gravar um atalho novo (Sistema → Controle) apertando só o botão central desse controle: fica gravado como o botão Xbox. Resultado: ______ +- [ ] Controle Xbox e controle PlayStation: o botão Xbox/PS continua funcionando como antes, e o teclado e o mouse não são lidos (nenhuma linha de botão central para eles no log). Resultado: ______ + ## Bateria dos controles Bluetooth (#225, issue #224) - [ ] Controle Bluetooth que não é PlayStation (Amazon Luna, Xbox por Bluetooth, 8BitDo…): a bateria no canto da tela é a mesma de Configurações → Bluetooth (pode levar até 30 s para atualizar). O log tem "Controle: bateria pelo Bluetooth do Windows: () %" uma vez. Resultado: ______ diff --git a/src/ConsoleMode/Controls/ShortcutPicker.cs b/src/ConsoleMode/Controls/ShortcutPicker.cs index 2437f92..924a8d0 100644 --- a/src/ConsoleMode/Controls/ShortcutPicker.cs +++ b/src/ConsoleMode/Controls/ShortcutPicker.cs @@ -131,6 +131,7 @@ private void StartCapture() _error.Visibility = Visibility.Collapsed; _capture = new ShortcutCapture(); SonyHidReader.Acquire(); + HidHomeButtonReader.Acquire(); _vm.BeginShortcutCapture(); _value.Text = LocalizationService.Get("ShortcutPressButtons"); Refresh(); @@ -143,6 +144,7 @@ private void StopCapture() _capture = null; _timer.Stop(); SonyHidReader.Release(); + HidHomeButtonReader.Release(); _vm.EndShortcutCapture(); Refresh(); } diff --git a/src/ConsoleMode/Native/HidDevices.cs b/src/ConsoleMode/Native/HidDevices.cs index 47d6e99..6a3be50 100644 --- a/src/ConsoleMode/Native/HidDevices.cs +++ b/src/ConsoleMode/Native/HidDevices.cs @@ -69,6 +69,60 @@ public static IEnumerable EnumeratePaths() } } + /// + /// Opens a collection to read its input reports, shared, so XInput, Steam and the game keep reading it too. Null when + /// Windows doesn't let anyone else read it (keyboards and mice are kept by the system) or it has no input report. + /// + public static HidReader? OpenForRead(HidInfo info) + { + if (info.InputReportLength == 0) return null; + var handle = CreateFile(info.Path, GenericRead, FileShareRead | FileShareWrite, 0, OpenExisting, FileFlagOverlapped, 0); + if (handle.IsInvalid) { handle.Dispose(); return null; } + if (!HidD_GetPreparsedData(handle, out var preparsed)) { handle.Dispose(); return null; } + return new HidReader(handle, preparsed, info); + } + + /// The usages among that a collection declares as input buttons. + public static IReadOnlyList<(ushort Page, ushort Id)> DeclaredButtons(string path, IEnumerable<(ushort Page, ushort Id)> wanted) + { + using var handle = CreateFile(path, 0, FileShareRead | FileShareWrite, 0, OpenExisting, 0, 0); + if (handle.IsInvalid || !HidD_GetPreparsedData(handle, out var preparsed)) return []; + try + { + var found = new List<(ushort, ushort)>(); + var caps = new byte[ButtonCapsSize * 8]; + foreach (var (page, id) in wanted) + { + ushort length = 8; + if (HidP_GetSpecificButtonCaps(HidpInput, page, 0, id, caps, ref length, preparsed) == HidpStatusSuccess && length > 0) + found.Add((page, id)); + } + return found; + } + finally + { + HidD_FreePreparsedData(preparsed); + } + } + + /// + /// Every button usage pressed in one input report (any page), or null when the report isn't one this parse + /// applies to (another report id): the caller keeps the state it had. + /// + internal static IReadOnlyList<(ushort Page, ushort Id)>? PressedButtons(nint preparsed, byte[] report, int length) + { + var list = new UsageAndPage[64]; + uint count = (uint)list.Length; + var status = HidP_GetUsagesEx(HidpInput, 0, list, ref count, preparsed, report, (uint)length); + if (status != HidpStatusSuccess) return null; + var pressed = new (ushort, ushort)[count]; + for (var i = 0; i < count; i++) pressed[i] = (list[i].UsagePage, list[i].Usage); + return pressed; + } + + /// Releases the preparsed data an holds. + internal static void Free(nint preparsed) => HidD_FreePreparsedData(preparsed); + /// The device node behind a collection's interface path (0 when Windows doesn't know it). public static uint DevNodeOf(string interfacePath) { @@ -133,6 +187,11 @@ public static uint DevNodeOf(string interfacePath) private static readonly DevPropKey DevPKeyFriendlyName = new() { FmtId = new Guid("a45c254e-df1c-4efd-8020-67d146a850e0"), Pid = 14 }; private static readonly DevPropKey DevPKeyDeviceDesc = new() { FmtId = new Guid("a45c254e-df1c-4efd-8020-67d146a850e0"), Pid = 2 }; + private const uint GenericRead = 0x80000000; + private const uint FileFlagOverlapped = 0x40000000; + private const int HidpInput = 0; + /// sizeof(HIDP_BUTTON_CAPS): the same 72 bytes on x86 and x64. + private const int ButtonCapsSize = 72; private const uint FileShareRead = 0x1; private const uint FileShareWrite = 0x2; private const uint OpenExisting = 3; @@ -144,6 +203,13 @@ public static uint DevNodeOf(string interfacePath) private const uint DevPropTypeByte = 0x03; private const uint DevPropTypeString = 0x12; + [StructLayout(LayoutKind.Sequential)] + private struct UsageAndPage + { + public ushort Usage; + public ushort UsagePage; + } + [StructLayout(LayoutKind.Sequential)] private struct DevPropKey { @@ -208,6 +274,12 @@ private struct SpDeviceInterfaceData [DllImport("hid.dll")] private static extern int HidP_GetCaps(nint preparsed, out HidpCaps caps); + [DllImport("hid.dll")] + private static extern int HidP_GetSpecificButtonCaps(int reportType, ushort usagePage, ushort linkCollection, ushort usage, byte[] buttonCaps, ref ushort length, nint preparsed); + + [DllImport("hid.dll")] + private static extern int HidP_GetUsagesEx(int reportType, ushort linkCollection, [Out] UsageAndPage[] usages, ref uint length, nint preparsed, byte[] report, uint reportLength); + [DllImport("setupapi.dll", CharSet = CharSet.Unicode)] private static extern nint SetupDiGetClassDevs(ref Guid classGuid, nint enumerator, nint parent, uint flags); @@ -238,3 +310,30 @@ private struct SpDeviceInterfaceData [DllImport("cfgmgr32.dll")] private static extern int CM_Get_DevNode_PropertyW(uint devInst, ref DevPropKey key, out uint type, byte[]? buffer, ref uint size, uint flags); } + +/// A HID collection open for reading, with its parsed descriptor. Dispose closes both. +internal sealed class HidReader : IDisposable +{ + private nint _preparsed; + + public HidReader(SafeFileHandle handle, nint preparsed, HidInfo info) + { + Handle = handle; + _preparsed = preparsed; + Info = info; + } + + public SafeFileHandle Handle { get; } + public HidInfo Info { get; } + + /// Pressed buttons in one report (see HidDevices.PressedButtons); null for a report it can't parse. + public IReadOnlyList<(ushort Page, ushort Id)>? Pressed(byte[] report, int length) => + _preparsed == 0 ? null : HidDevices.PressedButtons(_preparsed, report, length); + + public void Dispose() + { + Handle.Dispose(); + var preparsed = Interlocked.Exchange(ref _preparsed, 0); + if (preparsed != 0) HidDevices.Free(preparsed); + } +} diff --git a/src/ConsoleMode/Services/ControllerHoldWatcher.cs b/src/ConsoleMode/Services/ControllerHoldWatcher.cs index d3bbed0..3ee12fa 100644 --- a/src/ConsoleMode/Services/ControllerHoldWatcher.cs +++ b/src/ConsoleMode/Services/ControllerHoldWatcher.cs @@ -8,7 +8,8 @@ namespace ConsoleMode.Services; /// (zero = fire on press). Used for the shortcuts the user picked (see ControllerShortcuts): /// enter console mode from the tray, open the session menu and restore the desk, all of /// which work without focus. XInputGetStateEx (ordinal 100) is the only entry point that -/// reports the Guide button; PlayStation pads are read through SonyHidReader. +/// reports the Guide button; PlayStation pads are read through SonyHidReader, and other brands' centre button +/// through HidHomeButtonReader. /// public sealed class ControllerHoldWatcher : IDisposable { @@ -60,6 +61,7 @@ public void Start() { if (_timer.IsRunning) return; SonyHidReader.Acquire(); + HidHomeButtonReader.Acquire(); _heldSince = null; // A combo already held when the watch starts must be released first. _fired = true; @@ -68,7 +70,11 @@ public void Start() public void Stop() { - if (_timer.IsRunning) SonyHidReader.Release(); + if (_timer.IsRunning) + { + SonyHidReader.Release(); + HidHomeButtonReader.Release(); + } _timer.Stop(); _heldSince = null; _fired = false; @@ -98,6 +104,7 @@ public static IReadOnlyDictionary ReadHeldByDevice() { var held = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var (path, buttons) in SonyHidReader.ReadStates()) held[$"sony:{path}"] = buttons; + foreach (var (path, buttons) in HidHomeButtonReader.ReadStates()) held[$"home:{path}"] = buttons; if (_unavailable) return held; try { @@ -118,6 +125,8 @@ private static bool IsHeld(ushort mask) { // Test each physical Sony pad separately; combining their masks creates impossible chords. if (ControllerShortcuts.IsHeldOnAnyDevice(mask, SonyHidReader.ReadStates().Values)) return true; + // Other brands' centre button, read from HID as Guide alone (their other buttons come through XInput). + if (ControllerShortcuts.IsHeldOnAnyDevice(mask, HidHomeButtonReader.ReadStates().Values)) return true; if (_unavailable) return false; try { diff --git a/src/ConsoleMode/Services/ControllerMapping.cs b/src/ConsoleMode/Services/ControllerMapping.cs index aa014fa..35f1386 100644 --- a/src/ConsoleMode/Services/ControllerMapping.cs +++ b/src/ConsoleMode/Services/ControllerMapping.cs @@ -5,6 +5,36 @@ public static class ControllerMapping { public const ushort SonyVendorId = 0x054C; public const ushort NintendoVendorId = 0x057E; + public const ushort MicrosoftVendorId = 0x045E; + + /// A HID usage: page and id, as the device descriptor declares it. + public readonly record struct HidUsage(ushort Page, ushort Id); + + /// + /// The standard HID usages of a controller's centre button (Home, Guide, Luna, Stadia…): Generic Desktop "System Main + /// Menu" and Consumer "AC Home". A pad that declares one of them gets its centre button read as Guide, so the + /// controller shortcut works with any brand that follows the standard (issue #217), not only Xbox and PlayStation. + /// + public static readonly IReadOnlyList HomeUsages = [new(0x01, 0x85), new(0x0C, 0x0223)]; + + public static bool IsHomeUsage(ushort page, ushort id) => HomeUsages.Contains(new HidUsage(page, id)); + + /// + /// Whose centre button is read from HID: everyone but Microsoft (XInput already reports the Guide button of Xbox + /// pads) and Sony (SonyHidReader reads the PS button with the rest of the pad). + /// + public static bool ReadsHomeFromHid(ushort vendorId) => vendorId is not (MicrosoftVendorId or SonyVendorId); + + /// The name of a usage for logs and diagnostics: "Generic Desktop 0x85 (System Main Menu)". + public static string DescribeUsage(ushort page, ushort id) => (page, id) switch + { + (0x01, 0x85) => "Generic Desktop 0x85 (System Main Menu)", + (0x0C, 0x0223) => "Consumer 0x223 (AC Home)", + (0x09, _) => $"Button {id}", + (0x01, _) => $"Generic Desktop 0x{id:X2}", + (0x0C, _) => $"Consumer 0x{id:X3}", + _ => $"page 0x{page:X2} usage 0x{id:X2}" + }; /// HID button indexes of L1/R1 (LB/RB): 4 and 5 on Sony, Nintendo and generic pads. public const int HidShoulderLeft = 4; diff --git a/src/ConsoleMode/Services/HidHomeButtonReader.cs b/src/ConsoleMode/Services/HidHomeButtonReader.cs new file mode 100644 index 0000000..20bec58 --- /dev/null +++ b/src/ConsoleMode/Services/HidHomeButtonReader.cs @@ -0,0 +1,131 @@ +using ConsoleMode.Native; + +namespace ConsoleMode.Services; + +/// +/// Reads the centre button (Home, Luna, Stadia…) of controllers that aren't Xbox or PlayStation, through the standard +/// HID usages (ControllerMapping.HomeUsages), so the controller shortcut to open Console Mode works with them +/// (issue #217). XInput never reports that button for them, even when it covers the rest of the pad. Only the +/// collections that declare one of those usages are opened, shared, so Windows, Steam and the game keep reading them. +/// The button may sit on the gamepad collection or on a sibling one of the same device (a "consumer control"), so +/// every collection of a game controller's vendor and product is looked at. +/// +public static class HidHomeButtonReader +{ + private static readonly object Gate = new(); + private static readonly Dictionary Held = new(StringComparer.OrdinalIgnoreCase); + private static readonly HashSet Reading = new(StringComparer.OrdinalIgnoreCase); + /// Collections looked at already (with or without a centre button), so the scan doesn't reopen them every time. + private static readonly HashSet Checked = new(StringComparer.OrdinalIgnoreCase); + private static CancellationTokenSource? _cts; + private static int _users; + + /// Guide (0x0400) for each collection whose centre button is held right now, 0 for the others. + public static IReadOnlyDictionary ReadStates() + { + lock (Gate) return new Dictionary(Held, StringComparer.OrdinalIgnoreCase); + } + + public static void Acquire() + { + lock (Gate) + { + if (_users++ > 0) return; + _cts = new CancellationTokenSource(); + var token = _cts.Token; + _ = Task.Run(() => ScanLoopAsync(token)); + } + } + + public static void Release() + { + lock (Gate) + { + if (_users == 0 || --_users > 0) return; + _cts?.Cancel(); + _cts = null; + Held.Clear(); + Checked.Clear(); + } + } + + private static async Task ScanLoopAsync(CancellationToken ct) + { + while (!ct.IsCancellationRequested) + { + try + { + Scan(ct); + } + catch (Exception ex) + { + AppLog.Write($"Controle: botão central (HID): {ex.Message}"); + } + try { await Task.Delay(3000, ct); } catch (OperationCanceledException) { break; } + } + } + + private static void Scan(CancellationToken ct) + { + var all = HidDevices.EnumeratePaths().Select(HidDevices.Query).OfType().ToList(); + // The devices that are game controllers, by vendor and product: their other collections count too. + var pads = all.Where(i => i.IsGameController && ControllerMapping.ReadsHomeFromHid(i.VendorId)) + .Select(i => (i.VendorId, i.ProductId)).ToHashSet(); + foreach (var info in all) + { + if (!pads.Contains((info.VendorId, info.ProductId))) continue; + lock (Gate) + { + if (Reading.Contains(info.Path) || !Checked.Add(info.Path)) continue; + } + var declared = HidDevices.DeclaredButtons(info.Path, ControllerMapping.HomeUsages.Select(u => (u.Page, u.Id))); + if (declared.Count == 0) continue; + var usage = ControllerMapping.DescribeUsage(declared[0].Page, declared[0].Id); + if (HidDevices.OpenForRead(info) is not { } reader) + { + AppLog.Write($"Controle: botão central em {info.VendorId:X4}:{info.ProductId:X4} ({usage}), mas o Windows não deixa ler esse dispositivo"); + continue; + } + AppLog.Write($"Controle: lendo o botão central pelo HID ({info.VendorId:X4}:{info.ProductId:X4}, {usage})"); + lock (Gate) Reading.Add(info.Path); + _ = Task.Run(async () => + { + await ReadLoopAsync(reader, ct); + lock (Gate) + { + Held.Remove(info.Path); + Reading.Remove(info.Path); + // Unplugged: when it comes back it is looked at again. + Checked.Remove(info.Path); + } + }); + } + } + + private static async Task ReadLoopAsync(HidReader reader, CancellationToken ct) + { + var path = reader.Info.Path; + try + { + await using var stream = new FileStream(reader.Handle, FileAccess.Read, 0, isAsync: true); + var buffer = new byte[reader.Info.InputReportLength]; + while (!ct.IsCancellationRequested) + { + var read = await stream.ReadAsync(buffer.AsMemory(0, buffer.Length), ct); + if (read <= 0) break; + // A report of another id says nothing about the button: keep what it was. + if (reader.Pressed(buffer, read) is not { } pressed) continue; + var home = pressed.Any(u => ControllerMapping.IsHomeUsage(u.Page, u.Id)); + lock (Gate) Held[path] = home ? ControllerShortcuts.Guide : (ushort)0; + } + } + catch (Exception ex) when (ex is IOException or OperationCanceledException or ObjectDisposedException) + { + // Unplugged, or the watch stopped: the scan picks it up again. + } + finally + { + reader.Dispose(); + } + } +} diff --git a/tests/ConsoleMode.Tests/ControllerMappingTests.cs b/tests/ConsoleMode.Tests/ControllerMappingTests.cs index b36efec..fe12c53 100644 --- a/tests/ConsoleMode.Tests/ControllerMappingTests.cs +++ b/tests/ConsoleMode.Tests/ControllerMappingTests.cs @@ -179,4 +179,31 @@ public void DualSense_usb_report_keeps_its_own_layout_when_the_declared_size_is_ [InlineData(0x00, false)] public void Only_the_documented_sony_report_ids_are_known(byte id, bool known) => Assert.Equal(known, ControllerMapping.IsKnownSonyReport(id)); + + [Theory] + [InlineData(0x01, 0x85, true)] // Generic Desktop: System Main Menu + [InlineData(0x0C, 0x223, true)] // Consumer: AC Home + [InlineData(0x01, 0x86, false)] // System App Menu + [InlineData(0x0C, 0x40, false)] // Consumer: Menu + [InlineData(0x09, 0x0D, false)] // a plain button + public void The_centre_button_is_found_by_its_standard_usage(ushort page, ushort id, bool home) => + Assert.Equal(home, ControllerMapping.IsHomeUsage(page, id)); + + [Theory] + [InlineData(0x0171, true)] // Amazon Luna (issue #217) + [InlineData(0x2DC8, true)] // 8BitDo + [InlineData(ControllerMapping.NintendoVendorId, true)] + [InlineData(ControllerMapping.MicrosoftVendorId, false)] // XInput reports the Guide button + [InlineData(ControllerMapping.SonyVendorId, false)] // SonyHidReader reads the PS button + public void The_centre_button_is_read_from_hid_except_on_xbox_and_playstation_pads(ushort vendor, bool reads) => + Assert.Equal(reads, ControllerMapping.ReadsHomeFromHid(vendor)); + + [Theory] + [InlineData(0x01, 0x85, "Generic Desktop 0x85 (System Main Menu)")] + [InlineData(0x0C, 0x223, "Consumer 0x223 (AC Home)")] + [InlineData(0x09, 13, "Button 13")] + [InlineData(0x0C, 0xE9, "Consumer 0x0E9")] + [InlineData(0xFF00, 0x01, "page 0xFF00 usage 0x01")] + public void Usages_have_readable_names(ushort page, ushort id, string name) => + Assert.Equal(name, ControllerMapping.DescribeUsage(page, id)); }