Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.en-US.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
7 changes: 7 additions & 0 deletions docs/TESTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <vid:pid> …" 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 <fonte>: …" 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 (<vid:pid>, …)" e segurar o botão central com o app na bandeja abre o modo console. Resultado: ______
Expand Down
32 changes: 30 additions & 2 deletions src/ConsoleMode/Services/ControllerBatteryMonitor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,39 @@ public static IReadOnlyList<BatteryReading> 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<BatteryReading> _sources = [];

/// <summary>
/// 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.
/// </summary>
public static string DescribeSources()
{
IReadOnlyList<BatteryReading> 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<string> LoggedBluetooth = [];
private static bool _loggedBluetoothError;

Expand Down
17 changes: 17 additions & 0 deletions src/ConsoleMode/Services/ControllerHoldWatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,23 @@ public static IReadOnlyDictionary<string, ushort> ReadHeldByDevice()
return held;
}

/// <summary>
/// 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.
/// </summary>
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.
Expand Down
8 changes: 7 additions & 1 deletion src/ConsoleMode/Services/ControllerInput.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
133 changes: 115 additions & 18 deletions src/ConsoleMode/Services/HidHomeButtonReader.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Text;
using ConsoleMode.Native;

namespace ConsoleMode.Services;
Expand All @@ -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 (<see cref="AcquireDiagnostics"/>), the other collections of those devices are
/// read too, only to show which usages each button sends.
/// </summary>
public static class HidHomeButtonReader
{
private static readonly object Gate = new();
private static readonly Dictionary<string, ushort> Held = new(StringComparer.OrdinalIgnoreCase);
private static readonly HashSet<string> Reading = new(StringComparer.OrdinalIgnoreCase);
/// <summary>Collections looked at already (with or without a centre button), so the scan doesn't reopen them every time.</summary>
private static readonly HashSet<string> Checked = new(StringComparer.OrdinalIgnoreCase);
private static readonly Dictionary<string, Collection> Open = new(StringComparer.OrdinalIgnoreCase);
/// <summary>Collections looked at already, so the scan doesn't query their buttons every time.</summary>
private static readonly Dictionary<string, Collection> Seen = new(StringComparer.OrdinalIgnoreCase);
private static CancellationTokenSource? _cts;
private static int _users;
private static int _diagnosticUsers;

/// <summary>One collection of a controller: what it declares, whether it's being read, and (for the test) what is pressed.</summary>
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; } = [];
}

/// <summary>Guide (0x0400) for each collection whose centre button is held right now, 0 for the others.</summary>
public static IReadOnlyDictionary<string, ushort> ReadStates()
Expand All @@ -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();
}
}

/// <summary>The controller test: read every collection of the controllers, to show what each button sends.</summary>
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();
Comment thread
pullfrog[bot] marked this conversation as resolved.
Resolved
}
Release();
}

/// <summary>
/// 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.
/// </summary>
public static string Describe()
{
List<Collection> 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)
Expand All @@ -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
Expand All @@ -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)
Expand Down
Loading
Loading