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 @@ -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]
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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]
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.

## 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: ______
- [ ] 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: <nome> (<vid:pid>) <n>%" uma vez. Resultado: ______
Expand Down
2 changes: 2 additions & 0 deletions src/ConsoleMode/Controls/ShortcutPicker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -143,6 +144,7 @@ private void StopCapture()
_capture = null;
_timer.Stop();
SonyHidReader.Release();
HidHomeButtonReader.Release();
_vm.EndShortcutCapture();
Refresh();
}
Expand Down
99 changes: 99 additions & 0 deletions src/ConsoleMode/Native/HidDevices.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,60 @@ public static IEnumerable<string> EnumeratePaths()
}
}

/// <summary>
/// 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.
/// </summary>
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);
}

/// <summary>The usages among <paramref name="wanted"/> that a collection declares as input buttons.</summary>
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);
}
}

/// <summary>
/// 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.
/// </summary>
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;
}

/// <summary>Releases the preparsed data an <see cref="HidReader"/> holds.</summary>
internal static void Free(nint preparsed) => HidD_FreePreparsedData(preparsed);

/// <summary>The device node behind a collection's interface path (0 when Windows doesn't know it).</summary>
public static uint DevNodeOf(string interfacePath)
{
Expand Down Expand Up @@ -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;
/// <summary>sizeof(HIDP_BUTTON_CAPS): the same 72 bytes on x86 and x64.</summary>
private const int ButtonCapsSize = 72;
private const uint FileShareRead = 0x1;
private const uint FileShareWrite = 0x2;
private const uint OpenExisting = 3;
Expand All @@ -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
{
Expand Down Expand Up @@ -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);

Expand Down Expand Up @@ -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);
}

/// <summary>A HID collection open for reading, with its parsed descriptor. Dispose closes both.</summary>
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; }

/// <summary>Pressed buttons in one report (see HidDevices.PressedButtons); null for a report it can't parse.</summary>
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);
}
}
13 changes: 11 additions & 2 deletions src/ConsoleMode/Services/ControllerHoldWatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
/// </summary>
public sealed class ControllerHoldWatcher : IDisposable
{
Expand Down Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -98,6 +104,7 @@ public static IReadOnlyDictionary<string, ushort> ReadHeldByDevice()
{
var held = new Dictionary<string, ushort>(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
{
Expand All @@ -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
{
Expand Down
30 changes: 30 additions & 0 deletions src/ConsoleMode/Services/ControllerMapping.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,36 @@ public static class ControllerMapping
{
public const ushort SonyVendorId = 0x054C;
public const ushort NintendoVendorId = 0x057E;
public const ushort MicrosoftVendorId = 0x045E;

/// <summary>A HID usage: page and id, as the device descriptor declares it.</summary>
public readonly record struct HidUsage(ushort Page, ushort Id);

/// <summary>
/// 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.
/// </summary>
public static readonly IReadOnlyList<HidUsage> HomeUsages = [new(0x01, 0x85), new(0x0C, 0x0223)];

public static bool IsHomeUsage(ushort page, ushort id) => HomeUsages.Contains(new HidUsage(page, id));

/// <summary>
/// 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).
/// </summary>
public static bool ReadsHomeFromHid(ushort vendorId) => vendorId is not (MicrosoftVendorId or SonyVendorId);

/// <summary>The name of a usage for logs and diagnostics: "Generic Desktop 0x85 (System Main Menu)".</summary>
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}"
};

/// <summary>HID button indexes of L1/R1 (LB/RB): 4 and 5 on Sony, Nintendo and generic pads.</summary>
public const int HidShoulderLeft = 4;
Expand Down
131 changes: 131 additions & 0 deletions src/ConsoleMode/Services/HidHomeButtonReader.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
using ConsoleMode.Native;

namespace ConsoleMode.Services;

/// <summary>
/// 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.
/// </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 CancellationTokenSource? _cts;
private static int _users;

/// <summary>Guide (0x0400) for each collection whose centre button is held right now, 0 for the others.</summary>
public static IReadOnlyDictionary<string, ushort> ReadStates()
{
lock (Gate) return new Dictionary<string, ushort>(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<HidInfo>().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();
}
}
}
Loading
Loading