diff --git a/CHANGELOG.en-US.md b/CHANGELOG.en-US.md index 42114f8..27729ef 100644 --- a/CHANGELOG.en-US.md +++ b/CHANGELOG.en-US.md @@ -5,6 +5,7 @@ English (US) release notes, mirroring CHANGELOG.md (Brazilian Portuguese). Befor ## [Unreleased] ### 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) +- **Test controller** shows more: the Xbox (Guide) button when it arrives, other brands' pads' buttons with the HID usage of each, and the battery each source reports and which one shows on screen. Helps sort out pads that misbehave from the copied diagnostics. (#227) ### 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) diff --git a/CHANGELOG.md b/CHANGELOG.md index 289957d..8456283 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ Notas em português do Brasil; a versão em inglês (Estados Unidos) fica em `CH ## [Unreleased] ### 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) +- **Testar controle** mostra mais: o botão Xbox (Guide) quando ele chega, os botões de controles de outras marcas com o código HID de cada um, e a bateria que cada fonte informa e qual aparece na tela. Ajuda a resolver controles que não funcionam direito a partir do diagnóstico copiado. (#227) ### 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) diff --git a/docs/TESTING.md b/docs/TESTING.md index 4739e98..88b896c 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. +## Testar controle: Guide, códigos HID e bateria (#227) + +- [ ] Controle Xbox: em Testar controle, segurar o botão Xbox faz a linha "XInput #0" mostrar "(Guide)". Resultado: ______ +- [ ] Controle de outra marca (Amazon Luna, 8BitDo…): aparecem linhas "HID …" por coleção, com "botão central = …" ou "sem botão central padrão", e cada botão segurado aparece em "apertado: …" com o código (ex.: "Button 13", "Consumer 0x223 (AC Home)"). Copiar diagnóstico leva essas linhas. Resultado: ______ +- [ ] A lista de dispositivos termina com "Bateria : …" de cada fonte e "← mostrada" na que aparece no canto da tela. Resultado: ______ +- [ ] Fechar o Testar controle: o log não mostra erro, e o atalho do botão central continua funcionando depois. Resultado: ______ + ## 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: ______ diff --git a/src/ConsoleMode/Services/ControllerBatteryMonitor.cs b/src/ConsoleMode/Services/ControllerBatteryMonitor.cs index 46d7e24..14c89b1 100644 --- a/src/ConsoleMode/Services/ControllerBatteryMonitor.cs +++ b/src/ConsoleMode/Services/ControllerBatteryMonitor.cs @@ -71,11 +71,39 @@ public static IReadOnlyList Refresh() _loggedBluetoothError = true; } - var all = ControllerBattery.Combine(SonyHidReader.ReadBatteries(), wgi, xinput, bluetooth); - lock (Gate) _snapshot = all; + var sony = SonyHidReader.ReadBatteries(); + var all = ControllerBattery.Combine(sony, wgi, xinput, bluetooth); + lock (Gate) + { + _snapshot = all; + _sources = [.. sony, .. bluetooth, .. wgi.Select(w => w.Item1), .. xinput]; + } return all; } + private static IReadOnlyList _sources = []; + + /// + /// For the controller test: what every source said at the last refresh, and which reading is shown, so a pad whose + /// sources disagree (issue #224) is visible at a glance. + /// + public static string DescribeSources() + { + IReadOnlyList sources, shown; + lock (Gate) + { + sources = _sources; + shown = _snapshot; + } + if (sources.Count == 0) return "Bateria: nenhuma fonte"; + return string.Join(Environment.NewLine, sources.Select(r => + { + var ids = r.VendorId == 0 ? "" : $" ({r.VendorId:X4}:{r.ProductId:X4})"; + var used = shown.Contains(r) ? " ← mostrada" : ""; + return $"Bateria {r.Source}: {r.Name}{ids} {ControllerBattery.Format(r)}{(r.Charging ? ", carregando" : "")}{used}"; + })); + } + private static readonly HashSet LoggedBluetooth = []; private static bool _loggedBluetoothError; diff --git a/src/ConsoleMode/Services/ControllerHoldWatcher.cs b/src/ConsoleMode/Services/ControllerHoldWatcher.cs index 3ee12fa..a8e7979 100644 --- a/src/ConsoleMode/Services/ControllerHoldWatcher.cs +++ b/src/ConsoleMode/Services/ControllerHoldWatcher.cs @@ -121,6 +121,23 @@ public static IReadOnlyDictionary ReadHeldByDevice() return held; } + /// + /// The buttons of one XInput slot as the shortcuts see them, Guide included (XInputGetStateEx); null when the slot + /// is empty or XInput 1.4 isn't there. For the controller test. + /// + public static ushort? ReadButtonsWithGuide(uint slot) + { + if (_unavailable) return null; + try + { + return XInputGetStateEx(slot, out var state) == 0 ? state.Gamepad.wButtons : null; + } + catch (Exception ex) when (ex is DllNotFoundException or EntryPointNotFoundException) + { + return null; + } + } + private static bool IsHeld(ushort mask) { // Test each physical Sony pad separately; combining their masks creates impossible chords. diff --git a/src/ConsoleMode/Services/ControllerInput.cs b/src/ConsoleMode/Services/ControllerInput.cs index 17d6352..470ef85 100644 --- a/src/ConsoleMode/Services/ControllerInput.cs +++ b/src/ConsoleMode/Services/ControllerInput.cs @@ -243,7 +243,13 @@ private static int ReadXInput(bool[] held, StringBuilder? diag) held[(int)ControllerAction.Down] |= (b & XInputDpadDown) != 0 || state.Gamepad.sThumbLY < -StickThreshold; held[(int)ControllerAction.Left] |= (b & XInputDpadLeft) != 0 || state.Gamepad.sThumbLX < -StickThreshold; held[(int)ControllerAction.Right] |= (b & XInputDpadRight) != 0 || state.Gamepad.sThumbLX > StickThreshold; - diag?.AppendLine($"XInput #{i}: buttons=0x{b:X4} LX={state.Gamepad.sThumbLX} LY={state.Gamepad.sThumbLY}"); + if (diag is not null) + { + // XInputGetState never has the Guide button; the shortcuts read it with XInputGetStateEx, so show that. + var withGuide = ControllerHoldWatcher.ReadButtonsWithGuide(i) ?? b; + var guide = (withGuide & ControllerHoldWatcher.GuideButton) != 0 ? " (Guide)" : ""; + diag.AppendLine($"XInput #{i}: buttons=0x{withGuide:X4}{guide} LX={state.Gamepad.sThumbLX} LY={state.Gamepad.sThumbLY}"); + } } return count; } diff --git a/src/ConsoleMode/Services/HidHomeButtonReader.cs b/src/ConsoleMode/Services/HidHomeButtonReader.cs index 20bec58..3ee9b5d 100644 --- a/src/ConsoleMode/Services/HidHomeButtonReader.cs +++ b/src/ConsoleMode/Services/HidHomeButtonReader.cs @@ -1,3 +1,4 @@ +using System.Text; using ConsoleMode.Native; namespace ConsoleMode.Services; @@ -9,16 +10,29 @@ namespace ConsoleMode.Services; /// 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. +/// While the controller test is open (), the other collections of those devices are +/// read too, only to show which usages each button sends. /// 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 readonly Dictionary Open = new(StringComparer.OrdinalIgnoreCase); + /// Collections looked at already, so the scan doesn't query their buttons every time. + private static readonly Dictionary Seen = new(StringComparer.OrdinalIgnoreCase); private static CancellationTokenSource? _cts; private static int _users; + private static int _diagnosticUsers; + + /// One collection of a controller: what it declares, whether it's being read, and (for the test) what is pressed. + private sealed class Collection(HidInfo info, string? homeUsage) + { + public HidInfo Info { get; } = info; + public string? HomeUsage { get; } = homeUsage; + public bool Unreadable { get; set; } + public CancellationTokenSource? Stop { get; set; } + public IReadOnlyList<(ushort Page, ushort Id)> Pressed { get; set; } = []; + } /// Guide (0x0400) for each collection whose centre button is held right now, 0 for the others. public static IReadOnlyDictionary ReadStates() @@ -44,11 +58,58 @@ public static void Release() if (_users == 0 || --_users > 0) return; _cts?.Cancel(); _cts = null; + _diagnosticUsers = 0; Held.Clear(); - Checked.Clear(); + Seen.Clear(); } } + /// The controller test: read every collection of the controllers, to show what each button sends. + public static void AcquireDiagnostics() + { + lock (Gate) _diagnosticUsers++; + Acquire(); + } + + public static void ReleaseDiagnostics() + { + lock (Gate) + { + if (_diagnosticUsers > 0 && --_diagnosticUsers == 0) + // The collections opened only for the test close; the centre buttons stay read. + foreach (var c in Open.Values.Where(c => c.HomeUsage is null)) c.Stop?.Cancel(); + } + Release(); + } + + /// + /// For the controller test: each collection of the controllers (not Xbox or PlayStation) with its centre-button + /// usage, whether it's read, and the usages pressed right now. + /// + public static string Describe() + { + List all; + lock (Gate) all = [.. Seen.Values]; + if (all.Count == 0) return ""; + var sb = new StringBuilder(); + foreach (var c in all.OrderBy(c => c.Info.VendorId).ThenBy(c => c.Info.ProductId).ThenBy(c => c.Info.UsagePage)) + { + var i = c.Info; + bool reading; + IReadOnlyList<(ushort Page, ushort Id)> pressed; + lock (Gate) + { + reading = Open.ContainsKey(i.Path); + pressed = c.Pressed; + } + var home = c.HomeUsage is null ? "sem botão central padrão" : $"botão central = {c.HomeUsage}"; + var state = c.Unreadable ? "o Windows não deixa ler" : reading ? "lido" : "não lido"; + var now = pressed.Count == 0 ? "" : " · apertado: " + string.Join(", ", pressed.Select(u => ControllerMapping.DescribeUsage(u.Page, u.Id))); + sb.AppendLine($"HID {i.VendorId:X4}:{i.ProductId:X4} {ControllerMapping.DescribeUsage(i.UsagePage, i.Usage)}: {home}; {state}{now}"); + } + return sb.ToString().TrimEnd(); + } + private static async Task ScanLoopAsync(CancellationToken ct) { while (!ct.IsCancellationRequested) @@ -71,38 +132,70 @@ private static void Scan(CancellationToken ct) // 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(); + bool diagnostics; + lock (Gate) + { + diagnostics = _diagnosticUsers > 0; + // A collection opened for the test by a scan that raced its closing: close it now. + if (!diagnostics) + foreach (var c in Open.Values.Where(c => c.HomeUsage is null)) c.Stop?.Cancel(); + } foreach (var info in all) { if (!pads.Contains((info.VendorId, info.ProductId))) continue; + Collection? collection; lock (Gate) { - if (Reading.Contains(info.Path) || !Checked.Add(info.Path)) continue; + if (Open.ContainsKey(info.Path)) continue; + Seen.TryGetValue(info.Path, out collection); + } + if (collection is null) + { + var declared = HidDevices.DeclaredButtons(info.Path, ControllerMapping.HomeUsages.Select(u => (u.Page, u.Id))); + collection = new Collection(info, declared.Count == 0 ? null : ControllerMapping.DescribeUsage(declared[0].Page, declared[0].Id)); + lock (Gate) Seen[info.Path] = collection; } - 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); + // Without a centre button, a collection is only read for the controller test. + if (collection.Unreadable || (collection.HomeUsage is null && !diagnostics)) continue; 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"); + collection.Unreadable = true; + if (collection.HomeUsage is not null) + AppLog.Write($"Controle: botão central em {info.VendorId:X4}:{info.ProductId:X4} ({collection.HomeUsage}), 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); + var stop = CancellationTokenSource.CreateLinkedTokenSource(ct); + lock (Gate) + { + // The test may have closed since this scan started: then a collection without a centre button isn't wanted. + if (collection.HomeUsage is null && _diagnosticUsers == 0) + { + stop.Dispose(); + reader.Dispose(); + continue; + } + collection.Stop = stop; + Open[info.Path] = collection; + } + if (collection.HomeUsage is not null) + AppLog.Write($"Controle: lendo o botão central pelo HID ({info.VendorId:X4}:{info.ProductId:X4}, {collection.HomeUsage})"); _ = Task.Run(async () => { - await ReadLoopAsync(reader, ct); + await ReadLoopAsync(reader, collection, stop.Token); + stop.Dispose(); lock (Gate) { Held.Remove(info.Path); - Reading.Remove(info.Path); + Open.Remove(info.Path); + collection.Pressed = []; // Unplugged: when it comes back it is looked at again. - Checked.Remove(info.Path); + if (!ct.IsCancellationRequested && collection.HomeUsage is not null) Seen.Remove(info.Path); } }); } } - private static async Task ReadLoopAsync(HidReader reader, CancellationToken ct) + private static async Task ReadLoopAsync(HidReader reader, Collection collection, CancellationToken ct) { var path = reader.Info.Path; try @@ -113,10 +206,14 @@ private static async Task ReadLoopAsync(HidReader reader, CancellationToken ct) { 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. + // A report of another id says nothing about the buttons: keep what they were. 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; + lock (Gate) + { + collection.Pressed = pressed; + if (collection.HomeUsage is not null) + Held[path] = pressed.Any(u => ControllerMapping.IsHomeUsage(u.Page, u.Id)) ? ControllerShortcuts.Guide : (ushort)0; + } } } catch (Exception ex) when (ex is IOException or OperationCanceledException or ObjectDisposedException) diff --git a/src/ConsoleMode/ViewModels/MainViewModel.ControllerTest.cs b/src/ConsoleMode/ViewModels/MainViewModel.ControllerTest.cs index a4d7d2c..90602e1 100644 --- a/src/ConsoleMode/ViewModels/MainViewModel.ControllerTest.cs +++ b/src/ConsoleMode/ViewModels/MainViewModel.ControllerTest.cs @@ -22,7 +22,8 @@ private void OpenControllerTest() { IsPickerOpen = false; IsRolePanelOpen = false; - ControllerDevicesText = ControllerInput.DescribeDevices(); + StartControllerTestReaders(); + ControllerDevicesText = DescribeControllerTestDevices(); ControllerSampleText = ""; _controllerTestTimer ??= _dispatcher.CreateTimer(); _controllerTestTimer.Interval = TimeSpan.FromMilliseconds(50); @@ -36,23 +37,65 @@ private void OpenControllerTest() private void CloseControllerTest() { _controllerTestTimer?.Stop(); + StopControllerTestReaders(); IsControllerTestOpen = false; } + private bool _controllerTestReading; + + /// + /// While the test is open: every HID collection of the pads is read (to show which usage each button sends) and the + /// battery is read once right away, so the list shows what each source says. + /// + private void StartControllerTestReaders() + { + if (_controllerTestReading) return; + _controllerTestReading = true; + HidHomeButtonReader.AcquireDiagnostics(); + _ = Task.Run(() => + { + try { ControllerBatteryMonitor.Refresh(); } + catch (Exception ex) { AppLog.Write($"Teste de controle: bateria: {ex.Message}"); } + }); + } + + private void StopControllerTestReaders() + { + if (!_controllerTestReading) return; + _controllerTestReading = false; + HidHomeButtonReader.ReleaseDiagnostics(); + } + + /// The device list and the battery of each source. + private static string DescribeControllerTestDevices() => + ControllerInput.DescribeDevices() + Environment.NewLine + ControllerBatteryMonitor.DescribeSources(); + + /// The live sample, with what the pads' HID collections declare and the usages pressed right now. + private static string SampleControllerTest() + { + var sample = ControllerInput.SampleDiagnostics(); + var hid = HidHomeButtonReader.Describe(); + return hid.Length == 0 ? sample : sample + Environment.NewLine + hid; + } + /// The desktop expander binds IsControllerTestOpen two-way: start/stop the timer with it. partial void OnIsControllerTestOpenChanged(bool value) { if (value && _controllerTestTimer?.IsRunning != true) OpenControllerTest(); - else if (!value) _controllerTestTimer?.Stop(); + else if (!value) + { + _controllerTestTimer?.Stop(); + StopControllerTestReaders(); + } } private int _controllerTestTicks; private void OnControllerTestTick(DispatcherQueueTimer sender, object args) { - ControllerSampleText = ControllerInput.SampleDiagnostics(); + ControllerSampleText = SampleControllerTest(); // The device list changes rarely; refresh it about once a second. - if (++_controllerTestTicks % 20 == 0) ControllerDevicesText = ControllerInput.DescribeDevices(); + if (++_controllerTestTicks % 20 == 0) ControllerDevicesText = DescribeControllerTestDevices(); } [RelayCommand] diff --git a/tests/ConsoleMode.Tests/ConsoleTourTests.cs b/tests/ConsoleMode.Tests/ConsoleTourTests.cs index 425dc95..a0845da 100644 --- a/tests/ConsoleMode.Tests/ConsoleTourTests.cs +++ b/tests/ConsoleMode.Tests/ConsoleTourTests.cs @@ -5,6 +5,8 @@ namespace ConsoleMode.Tests; +// Sets the app language (shared state): never in parallel with the other tests that do. +[Collection("App language")] public class ConsoleTourTests { [Fact] diff --git a/tests/ConsoleMode.Tests/LocalizationTests.cs b/tests/ConsoleMode.Tests/LocalizationTests.cs index c3a8305..1983519 100644 --- a/tests/ConsoleMode.Tests/LocalizationTests.cs +++ b/tests/ConsoleMode.Tests/LocalizationTests.cs @@ -5,6 +5,8 @@ namespace ConsoleMode.Tests; +// Sets the app language (shared state): never in parallel with the other tests that do. +[Collection("App language")] public sealed class LocalizationTests { private static readonly Regex PlaceholderPattern = new(@"\{\d+\}", RegexOptions.Compiled);