Skip to content
Closed
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
4 changes: 4 additions & 0 deletions CHANGELOG.en-US.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
English (US) release notes, mirroring CHANGELOG.md (Brazilian Portuguese). Before publishing a version, add a `## [VERSION]` section to **both** files: the workflow publishes the section matching the tag from each one and fails if either is missing.

## [Unreleased]
### What's new
- **Your own scripts**: in Settings → Your own scripts, type a command (a `.bat` file, a program with arguments or a PowerShell line) that runs when console mode starts and another that runs after the desk is back. They run hidden, Console Mode waits up to 60 seconds for each, and a script that fails or hangs never stops the session or the restore. The stop command also runs when the start was rolled back, so whatever the start command took away is given back.
- **Exact refresh rate**: a new Settings option asks the game screen for the TV-style rate (119.88 Hz instead of 120 Hz, 59.94 instead of 60) once the mode is set, and reads it back. Windows' mode list only has whole numbers, so the rate is requested exactly; when the screen doesn't accept it, the whole-number rate stays and the log says so.
- **Move the mouse pointer out of the way**: a new Settings option moves the pointer to the bottom-right corner of the game screen once the launcher is up (Big Picture, Playnite, Xbox mode or a custom app), instead of leaving it in the middle of the TV.

## [1.7.0-alpha.2]
### What's new
Expand Down
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
Notas em português do Brasil; a versão em inglês (Estados Unidos) fica em `CHANGELOG.en-US.md`. Antes de publicar uma versão, adicione uma seção `## [VERSÃO]` com o changelog daquela versão **nos dois arquivos**. O workflow publica as duas seções correspondentes à tag na mesma release e falha se faltar alguma.

## [Unreleased]
### Novidades
- **Seus próprios scripts**: em Ajustes → Seus próprios scripts, informe um comando (um arquivo `.bat`, um programa com argumentos ou uma linha do PowerShell) que roda quando o modo console começa e outro que roda depois que a mesa volta. Eles rodam ocultos, o Console Mode espera até 60 segundos por cada um, e um script que falha ou trava nunca impede a sessão nem a restauração. O comando do fim também roda quando o início foi desfeito, então o que o comando do início tirou é devolvido.
- **Taxa de atualização exata**: uma opção nova em Ajustes pede à tela de jogo a taxa de TV (119,88 Hz em vez de 120 Hz, 59,94 em vez de 60) depois de aplicar o modo, e confere o resultado. A lista de modos do Windows só tem números inteiros, então a taxa é pedida de forma exata; se a tela não aceitar, a taxa inteira continua e o log registra.
- **Tirar o ponteiro do mouse do caminho**: uma opção nova em Ajustes leva o ponteiro para o canto inferior direito da tela de jogo assim que o iniciador aparece (Big Picture, Playnite, modo Xbox ou aplicativo personalizado), em vez de deixá-lo no meio da TV.

## [1.7.0-alpha.2]
### Novidades
Expand Down
10 changes: 10 additions & 0 deletions docs/GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,16 @@ Waking uses the Android wake-up key, then the **HDMI 1-4** key. If your TV ignor

"Wireless debugging" with a pairing code (Android 11+ phones) is a different, TLS-wrapped protocol and isn't supported: use USB / network debugging.

## Scripts, exact refresh rate and pointer

These three options live in the desktop **Settings**.

**Your own scripts.** *Settings → Your own scripts* takes one command that runs when a session starts and one that runs after the desk is back. A command is anything `cmd` can run: a `.bat` file, a program with arguments, or a PowerShell line such as `powershell -NoProfile -File "C:\Scripts\x.ps1"`. Put a path that has spaces in quotes. Both run hidden, and Console Mode waits up to 60 seconds for each; if one takes longer or fails, the session carries on and the log (`Script (início)` / `Script (fim)`) has the exit code. The start command runs once the session is registered, before the screens change. The stop command runs at the end of the restore, also when the start was rolled back or the restore had trouble, so what the start command took away (closing a browser, taking game mods out) can be given back. Nothing is shown on screen, so a script that waits for a key (`pause`) just runs into the 60-second limit.

**Exact refresh rate.** Many TVs run their 120 Hz mode at 119.88 Hz and their 60 Hz mode at 59.94 Hz. Windows' mode list only has whole numbers (and may list 119.88 as 119), so it can't be picked from the resolution list. With this option on, Console Mode sets the mode as usual and then asks for the same rate × 1000/1001 and reads it back. Only rates that have such a twin (24, 30, 48, 60, 120 and 240 Hz) are changed, and when the screen doesn't take it the whole-number rate stays and the log says so (`Taxa NTSC`).

**Move the mouse pointer out of the way.** Once the launcher is up, the pointer is moved to the bottom-right corner of the game screen, twice (Steam and others recenter it while their window opens). Xbox mode has no window to watch, so it goes by the time since the launch.

## Optional extras

### HDR
Expand Down
10 changes: 10 additions & 0 deletions docs/GUIDE.pt-BR.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,16 @@ Para acordar, o app usa a tecla de despertar do Android e depois a tecla **HDMI

A "Depuração sem fio" com código de pareamento (Android 11+ em celulares) é outro protocolo, com TLS, e não é suportada: use a depuração USB / pela rede.

## Scripts, taxa de atualização exata e ponteiro

Estas três opções ficam em **Ajustes**, na interface desktop.

**Seus próprios scripts.** *Ajustes → Seus próprios scripts* recebe um comando que roda quando a sessão começa e outro que roda depois que a mesa volta. Um comando é qualquer coisa que o `cmd` execute: um arquivo `.bat`, um programa com argumentos ou uma linha do PowerShell como `powershell -NoProfile -File "C:\Scripts\x.ps1"`. Caminhos com espaço vão entre aspas. Os dois rodam ocultos, e o Console Mode espera até 60 segundos por cada um; se um demorar mais ou falhar, a sessão segue e o log (`Script (início)` / `Script (fim)`) traz o código de saída. O comando do início roda assim que a sessão é registrada, antes de as telas mudarem. O comando do fim roda no final da restauração, também quando o início foi desfeito ou a restauração teve problemas, então o que o comando do início tirou (fechar um navegador, retirar mods de jogos) pode ser devolvido. Nada aparece na tela, então um script que espera uma tecla (`pause`) só termina no limite de 60 segundos.

**Taxa de atualização exata.** Muitas TVs rodam o modo de 120 Hz a 119,88 Hz e o de 60 Hz a 59,94 Hz. A lista de modos do Windows só tem números inteiros (e pode listar 119,88 como 119), então não dá para escolher isso na lista de resoluções. Com a opção ligada, o Console Mode aplica o modo normalmente e depois pede a mesma taxa × 1000/1001 e confere o resultado. Só são alteradas as taxas que têm esse par (24, 30, 48, 60, 120 e 240 Hz), e, se a tela não aceitar, a taxa inteira continua e o log registra (`Taxa NTSC`).

**Tirar o ponteiro do mouse do caminho.** Quando o iniciador aparece, o ponteiro vai para o canto inferior direito da tela de jogo, duas vezes (a Steam e outros o recentralizam enquanto abrem a janela). O modo Xbox não tem uma janela para acompanhar, então vale o tempo desde a abertura.

## Extras opcionais

### HDR
Expand Down
39 changes: 39 additions & 0 deletions docs/TESTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -545,3 +545,42 @@ Pré-requisito: RivaTuner Statistics Server instalado, com "Show On-Screen Displ
- [ ] Nenhum caminho mostra o nome do usuário do Windows (`C:\Users\…\`), nem com Playnite instalado em `%LOCALAPPDATA%`.
- [ ] **Copiar relatório** mostra o aviso de copiado e o texto colado no Bloco de Notas é igual ao da tela.
- [ ] Com uma seção falhando (ex.: sem permissão de leitura do log), ela mostra "unavailable" e o resto do relatório continua aparecendo.

## Scripts próprios, taxa exata (119,88 Hz) e ponteiro

Pré-condições: TV como tela de jogo; no Windows, a TV aceita 119,88 Hz (Ajustes → Sistema → Tela → Taxa de atualização avançada). Nada disso é coberto pelos testes automáticos (só a lógica pura: `UserCommand`, `RefreshRate`, `PointerParking`).

### Scripts próprios (Ajustes → Seus próprios scripts)

- [ ] Com os dois campos vazios, nada muda e o log não tem linhas `Script (...)`. Resultado: ______
- [ ] Início: `cmd /c echo ok > %TEMP%\cm-start.txt`. Ao iniciar, o arquivo existe **antes** de as telas mudarem e o log mostra `Script (início): ...` e `terminou com código 0`. Resultado: ______
- [ ] Fim: o mesmo com `cm-stop.txt`. O arquivo aparece ao voltar ao PC, depois da mesa restaurada. Resultado: ______
- [ ] Caminho com espaço entre aspas e argumento (`"C:\Meus Scripts\mods.bat" off`) funciona. Resultado: ______
- [ ] Um `.bat` com `timeout /t 3 /nobreak >nul` termina normalmente (não falha na hora). Resultado: ______
- [ ] Nenhuma janela de console aparece, nem pisca. Resultado: ______
- [ ] Comando que não existe: o log registra o código de saída diferente de zero e a sessão começa mesmo assim. Resultado: ______
- [ ] Script que demora mais de 60 s (`timeout /t 100`): o log diz `passou de 60 s` e a sessão segue. Resultado: ______
- [ ] Início desfeito (recusar a confirmação "Você vê esta tela?" ou deixar o tempo acabar): o comando do fim também roda. Resultado: ______
- [ ] Encerrar pela bandeja, pelo menu da sessão e fechando o launcher: o comando do fim roda em todos. Resultado: ______

### Taxa de atualização exata

- [ ] Ligar "Taxa de atualização exata", escolher 3840 x 2160 @ 120 Hz e iniciar: Ajustes do Windows → Tela avançada mostra **119,88 Hz** e o log traz `Taxa NTSC: ... em 119,88 Hz`. Resultado: ______
- [ ] O mesmo com 60 Hz: 59,94 Hz. Resultado: ______
- [ ] Com o modo da lista em "119 Hz" (como o Windows pode listar 119,88), o resultado também é 119,88 Hz, não 118,88. Resultado: ______
- [ ] Sem modo salvo para a tela (opção "Não alterar"): usa a taxa atual da tela. Resultado: ______
- [ ] Taxa sem par (144 ou 165 Hz): nada muda e o log diz `não tem equivalente 1000/1001`. Resultado: ______
- [ ] Tela que não aceita 119,88: a taxa inteira continua e o log diz `não aceitou`. Resultado: ______
- [ ] A resolução e a posição da tela de jogo **não** mudam, e ela continua como tela principal. Resultado: ______
- [ ] Com HDR e VRR ligados no app, a taxa continua 119,88 Hz depois que eles são ativados. Resultado: ______
- [ ] Ao voltar ao PC, a mesa volta como estava (resolução, taxa, posições). Resultado: ______
- [ ] A tela de teste "Você vê esta tela?" ainda aparece e reverte quando a configuração da tela de jogo muda. Resultado: ______

### Tirar o ponteiro do caminho

- [ ] Big Picture: com o ponteiro no meio da TV, ele vai para o canto inferior direito logo que o Big Picture aparece, e de novo cerca de 3 s depois se a Steam o recentralizar; o log tem duas linhas `Ponteiro: estacionado em ...`. Resultado: ______
- [ ] Playnite fullscreen, modo Xbox (cerca de 4-9 s depois de abrir) e aplicativo personalizado: o mesmo. Resultado: ______
- [ ] O ponteiro cai dentro da tela de jogo (com a TV não sendo a primeira da esquerda e com escala de 150-200 %). Resultado: ______
- [ ] Com a opção desligada, o ponteiro não é movido. Resultado: ______
- [ ] Com "Controlar o mouse" ou "Ocultar o ponteiro" ligados no menu da sessão, mover o ponteiro duas vezes no começo não atrapalha. Resultado: ______
- [ ] A segunda sessão (iniciar de novo sem fechar o app) também estaciona duas vezes. Resultado: ______
20 changes: 20 additions & 0 deletions src/ConsoleMode/Models/Models.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,21 @@ public sealed class AppConfig
/// <summary>Turning the TV on / to the PC's input when console mode starts (issue #75).</summary>
public TvControlConfig Tv { get; set; } = new();

/// <summary>
/// The user's own command (a .bat, a PowerShell line, an exe with arguments) that runs when a session
/// starts, once the session is registered and before the screens change. Empty = none.
/// </summary>
public string StartScript { get; set; } = "";

/// <summary>The user's own command that runs after the desk is restored (also when the start was rolled back). Empty = none.</summary>
public string StopScript { get; set; } = "";

/// <summary>Ask for the 1000/1001 twin of the game screen's rate (119.88 Hz instead of 120, 59.94 instead of 60) once the mode is set.</summary>
public bool NtscRefresh { get; set; }

/// <summary>Move the mouse pointer to a corner of the game screen once the launcher is up.</summary>
public bool ParkPointer { get; set; }

/// <summary>
/// A copy with other monitor fields and every other setting as it is here. A copy, not a field-by-field
/// rebuild: a setting added later is carried along without anyone having to remember it.
Expand Down Expand Up @@ -363,6 +378,11 @@ public sealed class ConsoleRuntimeState
public bool HdrTurnedOffByUser { get; set; }
public DateTime? SessionStartedAt { get; set; }
public string? BackupAudioId { get; set; }
/// <summary>The user's command to run after the desk is restored (taken from the config when the session starts).</summary>
public string StopScript { get; set; } = "";
public bool ParkPointer { get; set; }
public int PointerParks { get; set; }
public DateTime? LastPointerPark { get; set; }
}

public sealed class RtssBackup
Expand Down
64 changes: 64 additions & 0 deletions src/ConsoleMode/Native/CcdHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,70 @@ public static int SetPositions(IReadOnlyDictionary<string, (int X, int Y)> posit
SDC_APPLY | SDC_USE_SUPPLIED_DISPLAY_CONFIG | SDC_SAVE_TO_DATABASE | SDC_ALLOW_CHANGES);
}

private const uint MODE_INFO_TYPE_TARGET = 2;
private const uint MODE_IDX_INVALID = 0xFFFFFFFF;
private const uint SDC_VALIDATE = 0x40;

/// <summary>
/// The refresh rate Windows reports for an active screen as a fraction (119.88 Hz reads 120000/1001), or null
/// when the screen is not active. The DEVMODE rate is a whole number, so it cannot tell 120 from 119.88.
/// </summary>
public static (uint Numerator, uint Denominator)? GetRefreshRate(string gdiDeviceName)
{
if (GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, out var numPaths, out var numModes) != 0) return null;
var paths = new PATH_INFO[numPaths];
var modes = new MODE_INFO[numModes];
if (QueryDisplayConfig(QDC_ONLY_ACTIVE_PATHS, ref numPaths, paths, ref numModes, modes, 0) != 0) return null;

for (var i = 0; i < numPaths; i++)
{
var name = GetSourceGdiName(paths[i].sourceInfo.adapterId, paths[i].sourceInfo.id);
if (!string.Equals(name, gdiDeviceName, StringComparison.OrdinalIgnoreCase)) continue;

var rate = paths[i].targetInfo.refreshRate;
// The signal of the target mode is the most exact reading, when the path has one.
var index = paths[i].targetInfo.modeInfoIdx;
if (index < numModes && modes[index].infoType == MODE_INFO_TYPE_TARGET)
rate = modes[index].mode.targetMode.targetVideoSignalInfo.vSyncFreq;
return rate.Denominator == 0 ? null : (rate.Numerator, rate.Denominator);
}
return null;
}

/// <summary>
/// Asks for an exact refresh rate (120000/1001 for 119.88 Hz) on an active screen, keeping its size and
/// position. Windows picks the timing for the new rate. Validated before it is applied, so a rate the screen
/// does not take changes nothing. 0 = applied; the caller reads the rate back to be sure it took.
/// </summary>
public static int SetRefreshRate(string gdiDeviceName, uint numerator, uint denominator)
{
if (numerator == 0 || denominator == 0) return -101;
var err = GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, out var numPaths, out var numModes);
if (err != 0) return err;
var paths = new PATH_INFO[numPaths];
var modes = new MODE_INFO[numModes];
err = QueryDisplayConfig(QDC_ONLY_ACTIVE_PATHS, ref numPaths, paths, ref numModes, modes, 0);
if (err != 0) return err;

var found = false;
for (var i = 0; i < numPaths; i++)
{
var name = GetSourceGdiName(paths[i].sourceInfo.adapterId, paths[i].sourceInfo.id);
if (!string.Equals(name, gdiDeviceName, StringComparison.OrdinalIgnoreCase)) continue;
paths[i].targetInfo.refreshRate = new RATIONAL { Numerator = numerator, Denominator = denominator };
// No fixed target timing: Windows chooses one for the rate above. The source mode stays, so the
// resolution and the screen's place on the desktop do not change.
paths[i].targetInfo.modeInfoIdx = MODE_IDX_INVALID;
found = true;
}
if (!found) return -100;

var flags = SDC_USE_SUPPLIED_DISPLAY_CONFIG | SDC_ALLOW_CHANGES;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SDC_ALLOW_CHANGES permits Windows to modify supplied source and target mode information, and the same flag is used for the subsequent apply. That means this request can alter the source mode's resolution or desktop position, contrary to the method's preservation guarantee; avoid allowing source-mode changes or verify and preserve those values.

Technical details
# Exact refresh request may change source mode data

## Affected sites
- `src/ConsoleMode/Native/CcdHelper.cs:368-371` — validation and application both include `SDC_ALLOW_CHANGES` while passing the queried `modes` array.
- `src/ConsoleMode/Native/CcdHelper.cs:361-363` — source mode data is retained but its values are not checked after application.

## Required outcome
- Apply the target refresh-rate request without silently changing the display's source resolution or desktop position.

## Suggested approach
- Reject configurations that require source-mode changes, or confirm the applied source mode still has the original dimensions and position.

var check = SetDisplayConfig(numPaths, paths, numModes, modes, flags | SDC_VALIDATE);
if (check != 0) return check;
return SetDisplayConfig(numPaths, paths, numModes, modes, flags | SDC_APPLY | SDC_SAVE_TO_DATABASE);
}

public static int SetPrimary(string gdiDeviceName)
{
var err = GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, out var numPaths, out var numModes);
Expand Down
4 changes: 4 additions & 0 deletions src/ConsoleMode/Native/NativeWindows.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,10 @@ public static bool ForceForeground(nint hwnd)

public const uint WmClose = 0x0010;

/// <summary>Moves the mouse pointer to a place on the virtual desktop (physical pixels; the app is per-monitor DPI aware).</summary>
[DllImport("user32.dll")]
public static extern bool SetCursorPos(int x, int y);

[DllImport("user32.dll")]
public static extern nint SetWinEventHook(uint eventMin, uint eventMax, nint hmodWinEventProc, WinEventDelegate lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags);

Expand Down
9 changes: 9 additions & 0 deletions src/ConsoleMode/Resources/Strings.de-DE.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,15 @@
"EnteringConsoleSection": "Beim Starten des Konsolenmodus",
"LaunchCard": "Öffnen",
"AudioOutputCard": "Audioausgabe",
"NtscRefreshCard": "Exakte Bildwiederholrate (119,88 Hz)",
"NtscRefreshDescription": "Nutzt auf dem Spielbildschirm 119,88 Hz statt 120 Hz (59,94 statt 60), die Rate, die viele Fernseher tatsächlich verwenden. Kann Tearing und Ruckeln beheben. Nimmt der Bildschirm sie nicht an, bleibt die ganzzahlige Rate.",
"ParkPointerCard": "Mauszeiger aus dem Weg räumen",
"ParkPointerDescription": "Sobald der Launcher auf dem Fernseher erscheint, wird der Mauszeiger in die untere rechte Ecke des Spielbildschirms verschoben, statt in der Mitte zu bleiben.",
"ScriptsSection": "Eigene Skripte",
"StartScriptCard": "Beim Wechsel in den Konsolenmodus ausführen",
"StartScriptDescription": "Eine .bat-Datei, eine PowerShell-Zeile oder ein Programm, bei Bedarf mit Argumenten. Läuft verborgen, bevor sich die Bildschirme ändern; Console Mode wartet bis zu 60 Sekunden darauf. Leer lassen, um nichts auszuführen.",
"StopScriptCard": "Beim Zurück zum PC ausführen",
"StopScriptDescription": "Läuft verborgen, nachdem der Schreibtisch wiederhergestellt ist, auch wenn die Wiederherstellung Probleme hatte. Wartet bis zu 60 Sekunden. Leer lassen, um nichts auszuführen.",
"OptionalExtrasSection": "Optionale Extras",
"HdrCard": "HDR auf dem Gaming-Bildschirm",
"HdrDescription": "Wird beim Start aktiviert und beim Beenden auf den vorherigen Zustand zurückgesetzt.",
Expand Down
Loading