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
3 changes: 3 additions & 0 deletions CHANGELOG.en-US.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ English (US) release notes, mirroring CHANGELOG.md (Brazilian Portuguese). Befor
### Fixes
- Custom app: Console Mode moves only the program's largest window to the game screen, instead of every window Windows reports as its main one; a tooltip is no longer stretched over the TV. (#175)
- If the app closes or the PC shuts down in the middle of a session, the next time Console Mode opens it restores everything the session changed (displays, audio, RTSS, desktop icons and pointer) and says so. Before, the displays stayed as the session left them until you fixed them by hand. (#178)
- Audio output **The one that shows up when connecting**: when the TV's own output was already on before the session (so it never "showed up"), the audio stayed on the desk; now, if no new output shows up within about 10 s, Console Mode uses the game screen's output that was already on. A soundbar or receiver that wakes up later still wins. (issue #149, #180)
- Controllers: a stick that reads off-centre from the start (an axis that isn't really a stick, or a misread report) no longer makes the menu "keep going up". The stick only counts once it has been seen centred; the D-pad and buttons keep working. (issue #149, #180)
- Console interface, Session tab: the quick setting captions wrap onto two lines instead of being cut with an ellipsis ("Resolución y frecuencia…" in Spanish, for example). (#180)

## [1.7.0-alpha.2]
### What's new
Expand Down
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ Notas em português do Brasil; a versão em inglês (Estados Unidos) fica em `CH
### Correções
- Aplicativo personalizado: o Console Mode leva para a tela de jogo só a maior janela do programa, em vez de todas as que o Windows aponta como principal; uma dica de ferramenta não é mais esticada sobre a TV. (#175)
- Se o app fechar ou o PC desligar no meio de uma sessão, a próxima abertura do Console Mode restaura tudo o que a sessão mudou (telas, áudio, RTSS, ícones da área de trabalho e ponteiro) e avisa. Antes, as telas ficavam como a sessão deixou até você arrumar à mão. (#178)
- Saída de áudio **A que aparecer ao conectar**: quando a saída da própria TV já estava ligada antes da sessão (e por isso nunca "aparecia"), o áudio ficava na mesa; agora, se nenhuma saída nova surgir em uns 10 s, o Console Mode usa a saída da tela de jogo que já estava ativa. Uma soundbar ou receiver que acorde depois continua tendo prioridade. (issue #149, #180)
- Controles: um analógico que aparece fora do centro desde o início (um eixo que não é analógico de verdade, ou uma leitura errada) não deixa mais o menu "subindo sozinho". O analógico só passa a valer depois de ser visto no centro; o direcional e os botões continuam funcionando. (issue #149, #180)
- Interface Console, aba Sessão: as legendas dos ajustes rápidos quebram em duas linhas em vez de serem cortadas com reticências ("Resolución y frecuencia…" em espanhol, por exemplo). (#180)

## [1.7.0-alpha.2]
### Novidades
Expand Down
7 changes: 4 additions & 3 deletions docs/PRD.md
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,7 @@ Legenda: **P0** = necessário para a 1.7.0; **P1** = próxima versão; **P2** =
- [ ] **REL-020 — Validar no hardware** os PRs #167 a #170 pelo `TESTING.md` e corrigir o que falhar. _Estado: a branch local `local/1.7-teste` junta os quatro._
- [ ] **INPUT-013 — Ajuste do #168:** se o script de ativação não encontrar nenhum dispositivo (por exemplo, desconectado com o UAC aberto), mostrar erro em vez de "Feito", ou conferir o estado depois.
- [ ] **REL-021 — Mesclar** #167 a #170 e o #175.
- [x] **REL-025 — Correções de uso diário (issue #149):** BUG-001, BUG-002 e BUG-003 entram na 1.7. (#180)
- [ ] **REL-022 — Preparar a 1.7.0:** `[Unreleased]` vira `## [1.7.0]` nos dois changelogs; README, GUIDE e traduções enxutas; roadmap do README revisado.
- [ ] **REL-023 — Sincronizar o fork do winget** (`lippdev/winget-pkgs`) antes da estável; sem isso o job falha com `CreateRef`.
- [ ] **REL-024 — Publicar a 1.7.0**, só com pedido do mantenedor (D-06).
Expand Down Expand Up @@ -508,9 +509,9 @@ Legenda: **P0** = necessário para a 1.7.0; **P1** = próxima versão; **P2** =

### Épico BUG — Problemas conhecidos sem correção

- [ ] **BUG-001 (P1) — Menu "fica subindo".** Relato de usuário (feedback do #150): no menu, o Cima se repete sozinho. Diagnóstico de 17/10: o `ControllerInput` junta todas as fontes com OU, e um eixo HID que não é de gamepad parado em 0 (ou um relatório Sony mal lido) vira um Cima permanente com repetição. Falta o modelo do controle e a saída do "Testar controle".
- [ ] **BUG-002 (P1) — Áudio "Ao conectar" não pega a TV já ativa.** Issue #149: a troca automática só reage a saídas que ficam ativas depois do início da sessão (linha de base em `ConsoleEngine.InitializeAudioWatch`), então uma saída da TV já ativa nunca é escolhida. Correção provável: escolhê-la também quando já está ativa no início. Falta o `consolemode.log` do usuário.
- [ ] **BUG-003 (P2) —** Na aba Sessão da interface Console, os tiles de ajuste rápido cortam legendas longas ("Resolução e taxa de atualização", "VRR") com reticências em es, fr e ru (visto na 1.6.2; conferir na interface da 1.7). É limite de layout, não de tradução.
- [x] **BUG-001 — Menu "fica subindo".** Relato de usuário (feedback do #150): no menu, o Cima se repete sozinho. Diagnóstico de 17/10: o `ControllerInput` junta todas as fontes com OU, e um eixo HID que não é de gamepad parado em 0 (ou um relatório Sony mal lido) vira um Cima permanente com repetição. Falta o modelo do controle e a saída do "Testar controle". _Corrigido: o analógico HID só vale depois de ser visto no centro; a confirmar com o controle do usuário._ (#180, 1.7.0)
- [x] **BUG-002 — Áudio "Ao conectar" não pega a TV já ativa.** Issue #149: a troca automática só reage a saídas que ficam ativas depois do início da sessão (linha de base em `ConsoleEngine.InitializeAudioWatch`), então uma saída da TV já ativa nunca é escolhida. Correção provável: escolhê-la também quando já está ativa no início. Falta o `consolemode.log` do usuário. _Corrigido: depois de ~10 s sem saída nova, usa a saída já ativa com o nome da tela de jogo._ (#180, 1.7.0)
- [x] **BUG-003 —** Na aba Sessão da interface Console, os tiles de ajuste rápido cortam legendas longas ("Resolução e taxa de atualização", "VRR") com reticências em es, fr e ru (visto na 1.6.2; conferir na interface da 1.7). É limite de layout, não de tradução. _Confirmado na 1.7 e corrigido: as legendas quebram em duas linhas._ (#180, 1.7.0)
- [ ] **INPUT-016 (P3) —** Controle Switch Pro: hoje é ignorado por mandar leituras impossíveis pelo HID genérico (#115). Suporte exige ler o protocolo dele.

### Épico DATA (P3)
Expand Down
9 changes: 9 additions & 0 deletions docs/TESTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -610,3 +610,12 @@ Pré-condições: a opção **Tirar o ponteiro do mouse do caminho** ligada (é
- [ ] Com a TV como tela de jogo e os monitores da mesa desligados pela sessão, fechar o Console Mode à força no Gerenciador de Tarefas (Finalizar tarefa) no meio da sessão. Abrir o Console Mode de novo: as telas da mesa voltam como estavam, o áudio volta, o ponteiro volta para onde estava e aparece o aviso de que a última sessão não terminou direito. Resultado: ______
- [ ] O mesmo, desligando o PC no botão (ou tirando da tomada) no meio da sessão e ligando de novo com o Console Mode iniciando com o Windows: a mesa volta ao entrar no Windows. Resultado: ______
- [ ] Uma sessão normal (voltar ao PC pelo atalho ou pelo menu) não deixa o arquivo `session.json` na pasta de dados, e abrir o app depois não mostra o aviso. Resultado: ______

## Correções da issue #149 (#180)

- [ ] Saída de áudio **A que aparecer ao conectar**, com a TV **já ligada** e o áudio HDMI dela já aparecendo no Windows antes de começar: uns 10 s depois de entrar no modo console, o áudio vai para a TV (log: `Áudio: nenhuma saída nova; usando a saída já ativa da tela de jogo`). Resultado: ______
- [ ] O mesmo com a TV **desligada** antes de começar: o áudio vai para a TV assim que ela liga, como antes. Resultado: ______
- [ ] Com uma soundbar ou receiver que liga junto com a TV: o áudio vai para a soundbar, não para a TV. Resultado: ______
- [ ] Controle que fazia o menu "subir sozinho": o menu fica parado; se o log mostrar `analógico fora do centro desde o início`, o direcional e os botões continuam navegando. Anote o modelo do controle. Resultado: ______
- [ ] Controle normal: o analógico navega como antes (na primeira leitura ele está no centro). Resultado: ______
- [ ] Aba Sessão em espanhol, francês e russo: as legendas dos ajustes rápidos aparecem inteiras, em até duas linhas. Resultado: ______
24 changes: 24 additions & 0 deletions src/ConsoleMode/Services/AudioNaming.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,28 @@ public static string DisplayName(string endpointName, string adapterName)
if (!string.IsNullOrWhiteSpace(adapterName) && adapterName != endpointName) return $"{endpointName} ({adapterName})";
return endpointName;
}

/// <summary>
/// "The one that shows up when connecting" waits this long for a new output before settling for the game
/// screen's own output that was already on (issue #149): a soundbar or receiver that wakes up later still wins.
/// </summary>
public static readonly TimeSpan ActiveOutputFallbackAfter = TimeSpan.FromSeconds(10);

/// <summary>
/// The game screen's own HDMI/DisplayPort output: Windows names it after the monitor, as in
/// "LG TV SSCR2 (NVIDIA High Definition Audio)" for the screen "LG TV SSCR2". Generic monitor names never match.
/// </summary>
public static bool BelongsToScreen(string? deviceName, string? monitorName)
{
var monitor = (monitorName ?? "").Trim();
if (monitor.Length < 3 || IsGenericMonitorName(monitor)) return false;
var device = (deviceName ?? "").Trim();
return device.Equals(monitor, StringComparison.OrdinalIgnoreCase)
|| device.StartsWith(monitor + " (", StringComparison.OrdinalIgnoreCase);
}

private static bool IsGenericMonitorName(string name) =>
name.Contains("Generic", StringComparison.OrdinalIgnoreCase)
|| name.Contains("genérico", StringComparison.OrdinalIgnoreCase)
|| name.Contains("PnP", StringComparison.OrdinalIgnoreCase);
}
44 changes: 38 additions & 6 deletions src/ConsoleMode/Services/ConsoleEngine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -766,13 +766,13 @@ private void UpdateAutoSwitch()

var devices = Audio.GetDevices(true);
var newly = devices.Where(d => d.IsActive && !State.AudioBaselineActiveIds.Contains(d.FriendlyId)).ToList();
if (newly.Count == 0) return;

MonitorInfo? focus = null;
if (!string.IsNullOrWhiteSpace(State.FocusMonitor))
focus = Monitors.GetMonitors().FirstOrDefault(m => m.Name == State.FocusMonitor)
?? Monitors.GetMonitors(true).FirstOrDefault(m => m.Name == State.FocusMonitor);
if (newly.Count == 0)
{
UseGameScreenOutputAlreadyOn(devices, now);
return;
}

var focus = FocusMonitorInfo();
var pick = Audio.PickNewDevice(newly, State.AudioDeviceHint, focus);
if (pick is null) return;
if (TrySetOutput(pick.FriendlyId))
Expand All @@ -783,6 +783,38 @@ private void UpdateAutoSwitch()
CompleteAudioWatch();
}

private MonitorInfo? FocusMonitorInfo()
{
if (string.IsNullOrWhiteSpace(State.FocusMonitor)) return null;
return Monitors.GetMonitors().FirstOrDefault(m => m.Name == State.FocusMonitor)
?? Monitors.GetMonitors(true).FirstOrDefault(m => m.Name == State.FocusMonitor);
}

/// <summary>
/// "The one that shows up when connecting" with nothing new showing up: the TV's own output was already on
/// before the session (issue #149), so it never "appeared". After a while, that one is used.
/// </summary>
private void UseGameScreenOutputAlreadyOn(IReadOnlyList<AudioDevice> devices, DateTime now)
{
if (State.LaunchTime is not { } launched || now - launched < AudioNaming.ActiveOutputFallbackAfter) return;
var focus = FocusMonitorInfo();
var own = devices.FirstOrDefault(d => d.IsActive && AudioNaming.BelongsToScreen(d.Name, focus?.MonitorName));
if (own is null) return;

if (own.IsDefault)
{
AppLog.Write($"Áudio: a saída da tela de jogo já é a padrão: {own.Name}");
}
else
{
AppLog.Write($"Áudio: nenhuma saída nova; usando a saída já ativa da tela de jogo: {own.Name}");
if (!TrySetOutput(own.FriendlyId)) return;
}
State.AudioDeviceId = own.FriendlyId;
State.LastAudioSwitchName = own.Name;
CompleteAudioWatch();
}

private void UpdatePendingTarget()
{
if (!State.AudioPendingTarget || string.IsNullOrWhiteSpace(State.AudioDeviceId)) return;
Expand Down
43 changes: 38 additions & 5 deletions src/ConsoleMode/Services/ControllerInput.cs
Original file line number Diff line number Diff line change
Expand Up @@ -284,13 +284,19 @@ private static void ReadGamepads(bool[] held, StringBuilder? diag, HashSet<Gamep

private static readonly Dictionary<string, int> NoisyStreaks = [];
private static readonly HashSet<string> DistrustedPads = [];
private static readonly HashSet<string> CenteredSticks = [];
private static readonly HashSet<string> UncenteredLogged = [];

private static HashSet<Gamepad> ReadRaw(bool[] held, int xinputPads, StringBuilder? diag)
{
var invalidGamepads = new HashSet<Gamepad>();
var present = new HashSet<string>();
foreach (var raw in RawGameController.RawGameControllers)
{
var name = SafeName(raw);
// The physical device, not its model: two identical pads must not share the stick state.
var device = DeviceKey(raw, name);
present.Add(device);
try
{
var gamepad = Gamepad.FromGameController(raw);
Expand Down Expand Up @@ -348,11 +354,26 @@ private static HashSet<Gamepad> ReadRaw(bool[] held, int xinputPads, StringBuild
}
if (axes.Length > 1)
{
var (l, r, u, d) = ControllerMapping.StickDirections(axes[0], axes[1]);
held[(int)ControllerAction.Left] |= l;
held[(int)ControllerAction.Right] |= r;
held[(int)ControllerAction.Up] |= u;
held[(int)ControllerAction.Down] |= d;
// The stick counts only once it has been seen centred: one stuck at 0 would hold Up forever.
bool counts, firstMiss = false;
lock (CenteredSticks)
{
if (ControllerMapping.StickCentered(axes[0], axes[1])) CenteredSticks.Add(device);
counts = CenteredSticks.Contains(device);
if (!counts) firstMiss = UncenteredLogged.Add(device);
}
if (counts)
{
var (l, r, u, d) = ControllerMapping.StickDirections(axes[0], axes[1]);
held[(int)ControllerAction.Left] |= l;
held[(int)ControllerAction.Right] |= r;
held[(int)ControllerAction.Up] |= u;
held[(int)ControllerAction.Down] |= d;
}
else if (firstMiss)
{
AppLog.Write($"Controles: {name}: analógico fora do centro desde o início (x={axes[0]:F2}, y={axes[1]:F2}); ignorado até voltar ao centro, o direcional e os botões continuam valendo");
}
}

if (diag is not null)
Expand All @@ -369,6 +390,12 @@ private static HashSet<Gamepad> ReadRaw(bool[] held, int xinputPads, StringBuild
diag?.AppendLine($"HID {name}: erro {ex.Message}");
}
}
// A pad that left (unplugged, asleep) has to be seen centred again when it comes back.
lock (CenteredSticks)
{
CenteredSticks.IntersectWith(present);
UncenteredLogged.IntersectWith(present);
}
return invalidGamepads;
}

Expand All @@ -377,6 +404,12 @@ private static void Set(bool[] held, ControllerAction action, bool[] buttons, in
if (index >= 0 && index < buttons.Length) held[(int)action] |= buttons[index];
}

private static string DeviceKey(RawGameController raw, string name)
{
try { return string.IsNullOrEmpty(raw.NonRoamableId) ? name : raw.NonRoamableId; }
catch { return name; }
}

private static string SafeName(RawGameController raw)
{
try { return $"{raw.DisplayName} ({raw.HardwareVendorId:X4}:{raw.HardwareProductId:X4})"; }
Expand Down
6 changes: 6 additions & 0 deletions src/ConsoleMode/Services/ControllerMapping.cs
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,12 @@ public static bool UpdateHidTrust(int pressedButtons, ref int noisyStreak)
return noisyStreak >= DistrustAfterPolls;
}

/// <summary>
/// Both stick axes inside the dead zone. A HID stick only counts once it has been seen here (issue #149): an axis
/// that isn't really a stick, or a misread report, can rest at 0 and would otherwise hold Up forever.
/// </summary>
public static bool StickCentered(double x, double y) => x is >= 0.25 and <= 0.75 && y is >= 0.25 and <= 0.75;

/// <summary>Stick axis from 0..1 (0.5 centred) to a direction; ±0.25 dead zone.</summary>
public static (bool Left, bool Right, bool Up, bool Down) StickDirections(double x, double y) =>
(x < 0.25, x > 0.75, y < 0.25, y > 0.75);
Expand Down
Loading
Loading