diff --git a/CHANGELOG.en-US.md b/CHANGELOG.en-US.md
index 590890f..2da3c15 100644
--- a/CHANGELOG.en-US.md
+++ b/CHANGELOG.en-US.md
@@ -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
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d0cff8c..f20caf9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -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
diff --git a/docs/GUIDE.md b/docs/GUIDE.md
index f493c78..af57199 100644
--- a/docs/GUIDE.md
+++ b/docs/GUIDE.md
@@ -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
diff --git a/docs/GUIDE.pt-BR.md b/docs/GUIDE.pt-BR.md
index 8a9ce9e..3cbd9a3 100644
--- a/docs/GUIDE.pt-BR.md
+++ b/docs/GUIDE.pt-BR.md
@@ -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
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 6129468..2683aea 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -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: ______
diff --git a/src/ConsoleMode/Models/Models.cs b/src/ConsoleMode/Models/Models.cs
index 9a40c75..acaf5be 100644
--- a/src/ConsoleMode/Models/Models.cs
+++ b/src/ConsoleMode/Models/Models.cs
@@ -99,6 +99,21 @@ public sealed class AppConfig
/// Turning the TV on / to the PC's input when console mode starts (issue #75).
public TvControlConfig Tv { get; set; } = new();
+ ///
+ /// 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.
+ ///
+ public string StartScript { get; set; } = "";
+
+ /// The user's own command that runs after the desk is restored (also when the start was rolled back). Empty = none.
+ public string StopScript { get; set; } = "";
+
+ /// 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.
+ public bool NtscRefresh { get; set; }
+
+ /// Move the mouse pointer to a corner of the game screen once the launcher is up.
+ public bool ParkPointer { get; set; }
+
///
/// 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.
@@ -363,6 +378,11 @@ public sealed class ConsoleRuntimeState
public bool HdrTurnedOffByUser { get; set; }
public DateTime? SessionStartedAt { get; set; }
public string? BackupAudioId { get; set; }
+ /// The user's command to run after the desk is restored (taken from the config when the session starts).
+ public string StopScript { get; set; } = "";
+ public bool ParkPointer { get; set; }
+ public int PointerParks { get; set; }
+ public DateTime? LastPointerPark { get; set; }
}
public sealed class RtssBackup
diff --git a/src/ConsoleMode/Native/CcdHelper.cs b/src/ConsoleMode/Native/CcdHelper.cs
index 041818e..8399900 100644
--- a/src/ConsoleMode/Native/CcdHelper.cs
+++ b/src/ConsoleMode/Native/CcdHelper.cs
@@ -307,6 +307,70 @@ public static int SetPositions(IReadOnlyDictionary 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;
+
+ ///
+ /// 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.
+ ///
+ 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;
+ }
+
+ ///
+ /// 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.
+ ///
+ 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;
+ 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);
diff --git a/src/ConsoleMode/Native/NativeWindows.cs b/src/ConsoleMode/Native/NativeWindows.cs
index 264a582..1d6ca08 100644
--- a/src/ConsoleMode/Native/NativeWindows.cs
+++ b/src/ConsoleMode/Native/NativeWindows.cs
@@ -83,6 +83,10 @@ public static bool ForceForeground(nint hwnd)
public const uint WmClose = 0x0010;
+ /// Moves the mouse pointer to a place on the virtual desktop (physical pixels; the app is per-monitor DPI aware).
+ [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);
diff --git a/src/ConsoleMode/Resources/Strings.de-DE.json b/src/ConsoleMode/Resources/Strings.de-DE.json
index 435d76b..5d01a5f 100644
--- a/src/ConsoleMode/Resources/Strings.de-DE.json
+++ b/src/ConsoleMode/Resources/Strings.de-DE.json
@@ -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.",
diff --git a/src/ConsoleMode/Resources/Strings.en-US.json b/src/ConsoleMode/Resources/Strings.en-US.json
index 5945df9..29c20f5 100644
--- a/src/ConsoleMode/Resources/Strings.en-US.json
+++ b/src/ConsoleMode/Resources/Strings.en-US.json
@@ -36,6 +36,15 @@
"EnteringConsoleSection": "When entering console mode",
"LaunchCard": "Open",
"AudioOutputCard": "Audio output",
+ "NtscRefreshCard": "Exact refresh rate (119.88 Hz)",
+ "NtscRefreshDescription": "Runs the gaming display at 119.88 Hz instead of 120 Hz (59.94 instead of 60), the rate many TVs really use. Can fix tearing and stutter. If the screen doesn't accept it, the whole-number rate stays.",
+ "ParkPointerCard": "Move the mouse pointer out of the way",
+ "ParkPointerDescription": "Once the launcher is on the TV, the mouse pointer is moved to the bottom-right corner of the gaming display instead of staying in the middle.",
+ "ScriptsSection": "Your own scripts",
+ "StartScriptCard": "Run when entering console mode",
+ "StartScriptDescription": "A .bat file, a PowerShell line or a program, with its arguments if any. It runs hidden before the displays change, and Console Mode waits up to 60 seconds for it. Leave empty to run nothing.",
+ "StopScriptCard": "Run when going back to the PC",
+ "StopScriptDescription": "Runs hidden after the desk is back, even if the restore had trouble. Waits up to 60 seconds. Leave empty to run nothing.",
"OptionalExtrasSection": "Optional extras",
"HdrCard": "HDR on the gaming display",
"HdrDescription": "Enabled on entry and restored to its previous state on exit.",
diff --git a/src/ConsoleMode/Resources/Strings.es-ES.json b/src/ConsoleMode/Resources/Strings.es-ES.json
index 6b5da4c..76a5c3d 100644
--- a/src/ConsoleMode/Resources/Strings.es-ES.json
+++ b/src/ConsoleMode/Resources/Strings.es-ES.json
@@ -36,6 +36,15 @@
"EnteringConsoleSection": "Al entrar en modo consola",
"LaunchCard": "Abrir",
"AudioOutputCard": "Salida de audio",
+ "NtscRefreshCard": "Frecuencia de actualización exacta (119,88 Hz)",
+ "NtscRefreshDescription": "Usa 119,88 Hz en lugar de 120 Hz (59,94 en lugar de 60) en la pantalla de juego, la frecuencia que usan realmente muchos televisores. Puede arreglar los cortes de imagen y los tirones. Si la pantalla no la acepta, se mantiene la frecuencia entera.",
+ "ParkPointerCard": "Quitar el puntero del ratón de en medio",
+ "ParkPointerDescription": "Cuando el lanzador aparece en el televisor, el puntero del ratón se mueve a la esquina inferior derecha de la pantalla de juego en lugar de quedarse en el centro.",
+ "ScriptsSection": "Tus propios scripts",
+ "StartScriptCard": "Ejecutar al entrar en el modo consola",
+ "StartScriptDescription": "Un archivo .bat, una línea de PowerShell o un programa, con sus argumentos si los tiene. Se ejecuta oculto antes de que cambien las pantallas, y Console Mode espera hasta 60 segundos. Déjalo vacío para no ejecutar nada.",
+ "StopScriptCard": "Ejecutar al volver al PC",
+ "StopScriptDescription": "Se ejecuta oculto cuando el escritorio ya ha vuelto, incluso si la restauración tuvo problemas. Espera hasta 60 segundos. Déjalo vacío para no ejecutar nada.",
"OptionalExtrasSection": "Extras opcionales",
"HdrCard": "HDR en la pantalla de juego",
"HdrDescription": "Se activa al entrar y vuelve a su estado anterior al salir.",
diff --git a/src/ConsoleMode/Resources/Strings.fr-FR.json b/src/ConsoleMode/Resources/Strings.fr-FR.json
index 88328f2..65c7b2e 100644
--- a/src/ConsoleMode/Resources/Strings.fr-FR.json
+++ b/src/ConsoleMode/Resources/Strings.fr-FR.json
@@ -36,6 +36,15 @@
"EnteringConsoleSection": "À l'entrée en mode console",
"LaunchCard": "Ouvrir",
"AudioOutputCard": "Sortie audio",
+ "NtscRefreshCard": "Fréquence d'actualisation exacte (119,88 Hz)",
+ "NtscRefreshDescription": "Utilise 119,88 Hz au lieu de 120 Hz (59,94 au lieu de 60) sur l'écran de jeu, la fréquence que de nombreux téléviseurs utilisent réellement. Peut corriger le déchirement de l'image et les saccades. Si l'écran ne l'accepte pas, la fréquence entière est conservée.",
+ "ParkPointerCard": "Écarter le pointeur de la souris",
+ "ParkPointerDescription": "Quand le lanceur apparaît sur la télé, le pointeur de la souris est déplacé dans le coin inférieur droit de l'écran de jeu au lieu de rester au milieu.",
+ "ScriptsSection": "Vos propres scripts",
+ "StartScriptCard": "Exécuter à l'entrée en mode console",
+ "StartScriptDescription": "Un fichier .bat, une ligne PowerShell ou un programme, avec ses arguments si besoin. Il s'exécute masqué avant le changement des écrans, et Console Mode attend jusqu'à 60 secondes. Laissez vide pour ne rien exécuter.",
+ "StopScriptCard": "Exécuter au retour sur le PC",
+ "StopScriptDescription": "S'exécute masqué une fois le bureau rétabli, même si la restauration a rencontré des problèmes. Attend jusqu'à 60 secondes. Laissez vide pour ne rien exécuter.",
"OptionalExtrasSection": "Options supplémentaires",
"HdrCard": "HDR sur l'écran de jeu",
"HdrDescription": "Activé à l'entrée et remis dans son état précédent à la sortie.",
diff --git a/src/ConsoleMode/Resources/Strings.pt-BR.json b/src/ConsoleMode/Resources/Strings.pt-BR.json
index dd0986b..dba01ef 100644
--- a/src/ConsoleMode/Resources/Strings.pt-BR.json
+++ b/src/ConsoleMode/Resources/Strings.pt-BR.json
@@ -36,6 +36,15 @@
"EnteringConsoleSection": "Ao entrar no modo console",
"LaunchCard": "Abrir",
"AudioOutputCard": "Saída de áudio",
+ "NtscRefreshCard": "Taxa de atualização exata (119,88 Hz)",
+ "NtscRefreshDescription": "Usa 119,88 Hz em vez de 120 Hz (59,94 em vez de 60) na tela de jogo, a taxa que muitas TVs realmente usam. Pode resolver rasgos na imagem e travadinhas. Se a tela não aceitar, a taxa inteira continua.",
+ "ParkPointerCard": "Tirar o ponteiro do mouse do caminho",
+ "ParkPointerDescription": "Quando o iniciador aparece na TV, o ponteiro do mouse vai para o canto inferior direito da tela de jogo em vez de ficar no meio.",
+ "ScriptsSection": "Seus próprios scripts",
+ "StartScriptCard": "Executar ao entrar no modo console",
+ "StartScriptDescription": "Um arquivo .bat, uma linha do PowerShell ou um programa, com argumentos se precisar. Roda oculto antes de as telas mudarem, e o Console Mode espera até 60 segundos. Deixe vazio para não executar nada.",
+ "StopScriptCard": "Executar ao voltar para o PC",
+ "StopScriptDescription": "Roda oculto depois que a mesa volta, mesmo que a restauração tenha tido problemas. Espera até 60 segundos. Deixe vazio para não executar nada.",
"OptionalExtrasSection": "Extras opcionais",
"HdrCard": "HDR na tela de jogo",
"HdrDescription": "Liga ao entrar e volta como estava ao sair.",
diff --git a/src/ConsoleMode/Resources/Strings.ru-RU.json b/src/ConsoleMode/Resources/Strings.ru-RU.json
index 93468b9..ab7a582 100644
--- a/src/ConsoleMode/Resources/Strings.ru-RU.json
+++ b/src/ConsoleMode/Resources/Strings.ru-RU.json
@@ -36,6 +36,15 @@
"EnteringConsoleSection": "При входе в режим консоли",
"LaunchCard": "Открыть",
"AudioOutputCard": "Аудиовыход",
+ "NtscRefreshCard": "Точная частота обновления (119,88 Гц)",
+ "NtscRefreshDescription": "Использует на игровом экране 119,88 Гц вместо 120 Гц (59,94 вместо 60) — частоту, на которой на самом деле работают многие телевизоры. Может устранить разрывы изображения и подтормаживания. Если экран её не принимает, остаётся целая частота.",
+ "ParkPointerCard": "Убрать указатель мыши с дороги",
+ "ParkPointerDescription": "Когда лаунчер появляется на телевизоре, указатель мыши перемещается в правый нижний угол игрового экрана, а не остаётся посередине.",
+ "ScriptsSection": "Ваши собственные скрипты",
+ "StartScriptCard": "Запускать при входе в режим консоли",
+ "StartScriptDescription": "Файл .bat, строка PowerShell или программа с аргументами, если нужны. Запускается скрыто до смены экранов; Console Mode ждёт до 60 секунд. Оставьте пустым, чтобы ничего не запускать.",
+ "StopScriptCard": "Запускать при возврате к ПК",
+ "StopScriptDescription": "Запускается скрыто после возврата рабочего стола, даже если при восстановлении были проблемы. Ждёт до 60 секунд. Оставьте пустым, чтобы ничего не запускать.",
"OptionalExtrasSection": "Дополнительно",
"HdrCard": "HDR на игровом экране",
"HdrDescription": "Включается при входе и возвращается в прежнее состояние при выходе.",
diff --git a/src/ConsoleMode/Services/ConsoleEngine.cs b/src/ConsoleMode/Services/ConsoleEngine.cs
index 7a1a0f6..4b56628 100644
--- a/src/ConsoleMode/Services/ConsoleEngine.cs
+++ b/src/ConsoleMode/Services/ConsoleEngine.cs
@@ -71,6 +71,10 @@ public void Start(AppConfig config, MonitorInfo? focusInfo, Func
+ /// "Park the pointer": once the launcher is up, moves the mouse pointer 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.
+ ///
+ private void TickPointer()
+ {
+ var now = DateTime.Now;
+ var ready = State.FullscreenMode == "xboxMode"
+ ? State.LaunchTime is { } launched && now - launched >= PointerParking.XboxDelay
+ : State.HasAppeared;
+ if (!PointerParking.IsDue(State.ParkPointer, State.PointerParks, ready, State.LastPointerPark, now)) return;
+
+ var rect = State.FocusMonitorRect
+ ?? (State.FocusMonitor is { Length: > 0 } name ? Monitors.GetMonitorRect(name, State) : null);
+ if (rect is null) return;
+
+ var (x, y) = PointerParking.BottomRight(rect);
+ if (!NativeWindows.SetCursorPos(x, y)) AppLog.Write($"Ponteiro: não foi possível mover para {x},{y}");
+ else AppLog.Write($"Ponteiro: estacionado em {x},{y}");
+ State.PointerParks++;
+ State.LastPointerPark = now;
+ }
+
public int PollDelayMs()
{
if (State.FullscreenMode == "xboxMode") return 5000;
@@ -340,6 +380,13 @@ public void Stop()
}
finally
{
+ // The user's own stop command, with the desk back (or as back as it got): it also runs when the
+ // restore had trouble, so what the start command took away is given back.
+ UserHooks.Run("fim", State.StopScript);
+ State.StopScript = "";
+ State.ParkPointer = false;
+ State.PointerParks = 0;
+ State.LastPointerPark = null;
State.RestoreInProgress = false;
State.IsActive = false;
State.ShouldExit = false;
diff --git a/src/ConsoleMode/Services/LocalizationService.cs b/src/ConsoleMode/Services/LocalizationService.cs
index 67cb87e..a0b9326 100644
--- a/src/ConsoleMode/Services/LocalizationService.cs
+++ b/src/ConsoleMode/Services/LocalizationService.cs
@@ -156,6 +156,15 @@ internal void NotifyAll()
public string CustomAppWatchCard => LocalizationService.Get(nameof(CustomAppWatchCard));
public string CustomAppWatchDescription => LocalizationService.Get(nameof(CustomAppWatchDescription));
public string AudioOutputCard => LocalizationService.Get(nameof(AudioOutputCard));
+ public string NtscRefreshCard => LocalizationService.Get(nameof(NtscRefreshCard));
+ public string NtscRefreshDescription => LocalizationService.Get(nameof(NtscRefreshDescription));
+ public string ParkPointerCard => LocalizationService.Get(nameof(ParkPointerCard));
+ public string ParkPointerDescription => LocalizationService.Get(nameof(ParkPointerDescription));
+ public string ScriptsSection => LocalizationService.Get(nameof(ScriptsSection));
+ public string StartScriptCard => LocalizationService.Get(nameof(StartScriptCard));
+ public string StartScriptDescription => LocalizationService.Get(nameof(StartScriptDescription));
+ public string StopScriptCard => LocalizationService.Get(nameof(StopScriptCard));
+ public string StopScriptDescription => LocalizationService.Get(nameof(StopScriptDescription));
public string OptionalExtrasSection => LocalizationService.Get(nameof(OptionalExtrasSection));
public string HdrCard => LocalizationService.Get(nameof(HdrCard));
public string HdrDescription => LocalizationService.Get(nameof(HdrDescription));
diff --git a/src/ConsoleMode/Services/MonitorService.cs b/src/ConsoleMode/Services/MonitorService.cs
index 84e7020..e374774 100644
--- a/src/ConsoleMode/Services/MonitorService.cs
+++ b/src/ConsoleMode/Services/MonitorService.cs
@@ -332,6 +332,43 @@ public void ApplyFocusMode(string focusMonitor, SavedDisplayMode mode)
Thread.Sleep(300);
}
+ ///
+ /// Moves the game screen from a whole-number rate to its 1000/1001 twin (120 → 119.88 Hz, 60 → 59.94 Hz), the
+ /// rate many TVs actually run those modes at. Windows' mode list can't say 119.88, so the exact rate is asked
+ /// for through CCD and read back. Best effort: when the screen does not take it, the whole-number rate stays.
+ ///
+ /// The rate the mode was set to; 0 = read the current one.
+ /// Whether the screen now runs at the twin rate.
+ public bool ApplyNtscRefresh(string monitorName, int frequency)
+ {
+ var hertz = frequency > 0 ? frequency : NativeWindows.GetCurrentDisplayMode(monitorName)?.Frequency ?? 0;
+ if (!RefreshRate.TryNtsc(hertz, out var numerator, out var denominator))
+ {
+ AppLog.Write($"Taxa NTSC: {hertz} Hz não tem equivalente 1000/1001; mantida");
+ return false;
+ }
+
+ var wanted = RefreshRate.Label(RefreshRate.ToHertz(numerator, denominator));
+ for (var attempt = 1; attempt <= 2; attempt++)
+ {
+ var code = CcdHelper.SetRefreshRate(monitorName, numerator, denominator);
+ Thread.Sleep(600);
+ if (CcdHelper.GetRefreshRate(monitorName) is { } now &&
+ RefreshRate.Matches(now.Numerator, now.Denominator, numerator, denominator))
+ {
+ AppLog.Write($"Taxa NTSC: {monitorName} em {wanted} Hz");
+ return true;
+ }
+ AppLog.Write($"Taxa NTSC: tentativa {attempt} de {wanted} Hz em {monitorName} => {code}");
+ }
+
+ var current = CcdHelper.GetRefreshRate(monitorName);
+ AppLog.Write(current is { } c
+ ? $"Taxa NTSC: {monitorName} não aceitou {wanted} Hz; ficou em {RefreshRate.Label(RefreshRate.ToHertz(c.Numerator, c.Denominator))} Hz"
+ : $"Taxa NTSC: {monitorName} não aceitou {wanted} Hz");
+ return false;
+ }
+
public List GetDisplayModes(string monitorName, MonitorInfo? monitor, bool forceRefresh = false)
{
lock (_modesCache) return ReadDisplayModes(monitorName, monitor, forceRefresh);
diff --git a/src/ConsoleMode/Services/PointerParking.cs b/src/ConsoleMode/Services/PointerParking.cs
new file mode 100644
index 0000000..a0a69d6
--- /dev/null
+++ b/src/ConsoleMode/Services/PointerParking.cs
@@ -0,0 +1,34 @@
+using ConsoleMode.Models;
+
+namespace ConsoleMode.Services;
+
+///
+/// "Park the pointer": a session that starts leaves the mouse pointer in the middle of the TV, so it is moved to a
+/// corner of the game screen, out of the way. Steam and others recenter it while their window opens, so it is done
+/// twice. Pure, so it's tested.
+///
+public static class PointerParking
+{
+ /// How far inside the corner the pointer sits (some TVs crop the very edge).
+ public const int Margin = 6;
+
+ /// How many times the pointer is parked per session.
+ public const int Parks = 2;
+
+ /// Between two parks, so the second one lands after the launcher has settled.
+ public static readonly TimeSpan Between = TimeSpan.FromSeconds(3);
+
+ /// Xbox mode shows no window the app can watch: it is parked this long after the launch instead.
+ public static readonly TimeSpan XboxDelay = TimeSpan.FromSeconds(4);
+
+ /// The bottom-right corner of the screen, a few pixels inside it.
+ public static (int X, int Y) BottomRight(ScreenRect rect) =>
+ (rect.X + Math.Max(rect.Width - 1 - Margin, 0), rect.Y + Math.Max(rect.Height - 1 - Margin, 0));
+
+ /// The setting is on.
+ /// How many times it was parked in this session.
+ /// The launcher is up (its window appeared, or the Xbox delay passed).
+ /// When it was last parked, or null.
+ public static bool IsDue(bool enabled, int done, bool ready, DateTime? last, DateTime now) =>
+ enabled && ready && done < Parks && (last is null || now - last.Value >= Between);
+}
diff --git a/src/ConsoleMode/Services/RefreshRate.cs b/src/ConsoleMode/Services/RefreshRate.cs
new file mode 100644
index 0000000..6b99ab3
--- /dev/null
+++ b/src/ConsoleMode/Services/RefreshRate.cs
@@ -0,0 +1,53 @@
+namespace ConsoleMode.Services;
+
+///
+/// The "NTSC" twin of a whole-number refresh rate: many TVs run their 120 Hz mode at 119.88 Hz (120 × 1000/1001),
+/// 60 Hz at 59.94 Hz, and so on. Windows' mode list is whole numbers (and often shows 119.88 as 119), so the exact
+/// rate is asked for as a fraction. Pure, so it's tested.
+///
+public static class RefreshRate
+{
+ /// The rates that have a 1000/1001 twin on TVs.
+ private static readonly int[] NtscBases = [24, 30, 48, 60, 120, 240];
+
+ ///
+ /// The whole-number rate a listed rate stands for. Windows can list 119.88 as 119 (and 59.94 as 59), so one
+ /// below a base counts as that base; anything else is itself.
+ ///
+ public static int NtscBase(int hertz)
+ {
+ foreach (var rate in NtscBases)
+ if (hertz == rate || hertz == rate - 1) return rate;
+ return hertz;
+ }
+
+ public static bool HasNtscTwin(int hertz) => hertz > 0 && Array.IndexOf(NtscBases, NtscBase(hertz)) >= 0;
+
+ /// The twin as a fraction (120 → 120000/1001); false when the rate has none (144, 165…).
+ public static bool TryNtsc(int hertz, out uint numerator, out uint denominator)
+ {
+ numerator = 0;
+ denominator = 0;
+ if (!HasNtscTwin(hertz)) return false;
+ numerator = (uint)NtscBase(hertz) * 1000;
+ denominator = 1001;
+ return true;
+ }
+
+ public static double ToHertz(uint numerator, uint denominator) =>
+ denominator == 0 ? 0 : (double)numerator / denominator;
+
+ /// True when two fractions are the same rate for any practical purpose (within 0.02 Hz).
+ public static bool Matches(uint numeratorA, uint denominatorA, uint numeratorB, uint denominatorB) =>
+ denominatorA != 0 && denominatorB != 0 &&
+ Math.Abs(ToHertz(numeratorA, denominatorA) - ToHertz(numeratorB, denominatorB)) < 0.02;
+
+ /// "119.88" for a fractional rate, "120" for a whole one; always a dot, whatever the language.
+ public static string Label(double hertz)
+ {
+ var rounded = Math.Round(hertz);
+ return Math.Abs(hertz - rounded) < 0.005
+ ? rounded.ToString("0", System.Globalization.CultureInfo.InvariantCulture)
+ : hertz.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture);
+ }
+}
diff --git a/src/ConsoleMode/Services/UserCommand.cs b/src/ConsoleMode/Services/UserCommand.cs
new file mode 100644
index 0000000..15be063
--- /dev/null
+++ b/src/ConsoleMode/Services/UserCommand.cs
@@ -0,0 +1,28 @@
+namespace ConsoleMode.Services;
+
+///
+/// Pure helpers for the user's own commands: one that runs when a session starts and one that runs after
+/// the desk is back (a .bat, a PowerShell line, an exe with arguments). Pure, so it's tested.
+///
+public static class UserCommand
+{
+ /// How long a command may run before the session carries on without waiting for it.
+ public static readonly TimeSpan Timeout = TimeSpan.FromSeconds(60);
+
+ public static string Clean(string? command) => (command ?? "").Trim();
+
+ public static bool IsSet(string? command) => Clean(command).Length > 0;
+
+ ///
+ /// Arguments for cmd.exe that run the command the way the Run box would. /s makes cmd drop only the outer
+ /// pair of quotes, so a quoted path followed by arguments ("C:\My Scripts\mods.bat" off) stays intact.
+ ///
+ public static string CmdArguments(string? command) => $"/d /s /c \"{Clean(command)}\"";
+
+ /// The command as the log shows it: one line, never long.
+ public static string ForLog(string? command)
+ {
+ var line = Clean(command).Replace("\r\n", " ").Replace('\r', ' ').Replace('\n', ' ');
+ return line.Length <= 120 ? line : line[..117] + "...";
+ }
+}
diff --git a/src/ConsoleMode/Services/UserHooks.cs b/src/ConsoleMode/Services/UserHooks.cs
new file mode 100644
index 0000000..d4c3597
--- /dev/null
+++ b/src/ConsoleMode/Services/UserHooks.cs
@@ -0,0 +1,46 @@
+using System.Diagnostics;
+
+namespace ConsoleMode.Services;
+
+///
+/// Runs the user's own commands around a session. A hook never stops the session or the restore of the desk:
+/// every failure is only logged.
+///
+public static class UserHooks
+{
+ /// Runs the command hidden and waits for it, up to .
+ /// Where in the session it runs, for the log.
+ public static void Run(string label, string? command)
+ {
+ if (!UserCommand.IsSet(command)) return;
+ var text = UserCommand.ForLog(command);
+ try
+ {
+ AppLog.Write($"Script ({label}): {text}");
+ // ShellExecute with a hidden window, not CreateNoWindow: cmd then gets a real (hidden) console, so
+ // "timeout" and "pause" in a .bat behave; with redirected handles "timeout" fails on the spot.
+ using var process = Process.Start(new ProcessStartInfo
+ {
+ FileName = "cmd.exe",
+ Arguments = UserCommand.CmdArguments(command),
+ UseShellExecute = true,
+ WindowStyle = ProcessWindowStyle.Hidden
+ });
+ if (process is null)
+ {
+ AppLog.Write($"Script ({label}): não foi possível iniciar");
+ return;
+ }
+ if (!process.WaitForExit((int)UserCommand.Timeout.TotalMilliseconds))
+ {
+ AppLog.Write($"Script ({label}): passou de {UserCommand.Timeout.TotalSeconds:0} s; seguindo sem esperar");
+ return;
+ }
+ AppLog.Write($"Script ({label}): terminou com código {process.ExitCode}");
+ }
+ catch (Exception ex)
+ {
+ AppLog.Write($"Script ({label}): {ex.Message}");
+ }
+ }
+}
diff --git a/src/ConsoleMode/ViewModels/MainViewModel.Automation.cs b/src/ConsoleMode/ViewModels/MainViewModel.Automation.cs
new file mode 100644
index 0000000..008fc99
--- /dev/null
+++ b/src/ConsoleMode/ViewModels/MainViewModel.Automation.cs
@@ -0,0 +1,25 @@
+using CommunityToolkit.Mvvm.ComponentModel;
+
+namespace ConsoleMode.ViewModels;
+
+// Settings that tune a session without changing how it works: the user's own scripts around it, the TV's
+// exact (NTSC) refresh rate, and parking the mouse pointer. Each saves as soon as it changes.
+public partial class MainViewModel
+{
+ /// A command that runs when a session starts, before the screens change.
+ [ObservableProperty] private string _startScript = "";
+
+ /// A command that runs after the desk is restored.
+ [ObservableProperty] private string _stopScript = "";
+
+ /// 119.88 Hz instead of 120 Hz, 59.94 instead of 60, on the game screen.
+ [ObservableProperty] private bool _ntscRefresh;
+
+ /// Move the mouse pointer to a corner of the game screen once the launcher is up.
+ [ObservableProperty] private bool _parkPointer;
+
+ partial void OnStartScriptChanged(string value) => SaveQuietly();
+ partial void OnStopScriptChanged(string value) => SaveQuietly();
+ partial void OnNtscRefreshChanged(bool value) => SaveQuietly();
+ partial void OnParkPointerChanged(bool value) => SaveQuietly();
+}
diff --git a/src/ConsoleMode/ViewModels/MainViewModel.cs b/src/ConsoleMode/ViewModels/MainViewModel.cs
index ff48274..5d26ef5 100644
--- a/src/ConsoleMode/ViewModels/MainViewModel.cs
+++ b/src/ConsoleMode/ViewModels/MainViewModel.cs
@@ -309,6 +309,10 @@ private void Apply(LoadResult data)
CustomAppPath = config.CustomAppPath ?? "";
CustomAppArguments = config.CustomAppArguments ?? "";
CustomAppWatchProcess = config.CustomAppWatchProcess ?? "";
+ StartScript = config.StartScript ?? "";
+ StopScript = config.StopScript ?? "";
+ NtscRefresh = config.NtscRefresh;
+ ParkPointer = config.ParkPointer;
IsPlayniteAvailable = Engine.Launch.IsPlayniteAvailable();
BuildLocalizedOptions();
SelectedLaunch = LaunchOptions.FirstOrDefault(o => o.Value == config.FullscreenMode) ?? LaunchOptions[0];
@@ -926,6 +930,10 @@ private AppConfig BuildConfig()
CustomAppPath = CustomApp.CleanPath(CustomAppPath),
CustomAppArguments = CustomAppArguments.Trim(),
CustomAppWatchProcess = CustomAppWatchProcess.Trim(),
+ StartScript = UserCommand.Clean(StartScript),
+ StopScript = UserCommand.Clean(StopScript),
+ NtscRefresh = NtscRefresh,
+ ParkPointer = ParkPointer,
AudioDeviceId = auto ? "" : audioId,
AudioDeviceName = auto ? "" : SelectedAudio?.Text ?? "",
AudioAutoSwitch = auto,
diff --git a/src/ConsoleMode/Views/SettingsView.xaml b/src/ConsoleMode/Views/SettingsView.xaml
index 6692c6f..b70611d 100644
--- a/src/ConsoleMode/Views/SettingsView.xaml
+++ b/src/ConsoleMode/Views/SettingsView.xaml
@@ -27,6 +27,13 @@
SelectedItem="{x:Bind ViewModel.FocusRow.SelectedMode, Mode=TwoWay}"
DisplayMemberPath="Text"/>
+
+
+
+
+
+
@@ -89,6 +96,13 @@
SelectedItem="{x:Bind ViewModel.SelectedAudio, Mode=TwoWay}"
DisplayMemberPath="Text"/>
+
+
+
+
+
+
@@ -174,6 +188,21 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/ConsoleMode.Tests/AutomationConfigTests.cs b/tests/ConsoleMode.Tests/AutomationConfigTests.cs
new file mode 100644
index 0000000..46b4eda
--- /dev/null
+++ b/tests/ConsoleMode.Tests/AutomationConfigTests.cs
@@ -0,0 +1,62 @@
+using System.Text.Json;
+using ConsoleMode.Models;
+
+namespace ConsoleMode.Tests;
+
+public class AutomationConfigTests
+{
+ private static readonly JsonSerializerOptions Options = new()
+ {
+ PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
+ PropertyNameCaseInsensitive = true
+ };
+
+ [Fact]
+ public void The_new_settings_start_off_and_empty_so_nothing_changes_for_existing_users()
+ {
+ var config = new AppConfig();
+ Assert.Equal("", config.StartScript);
+ Assert.Equal("", config.StopScript);
+ Assert.False(config.NtscRefresh);
+ Assert.False(config.ParkPointer);
+
+ // A config saved by an older version has none of them: it loads with the defaults.
+ var old = JsonSerializer.Deserialize("{\"fullscreenMode\":\"bigPicture\"}", Options)!;
+ Assert.Equal("", old.StartScript);
+ Assert.Equal("", old.StopScript);
+ Assert.False(old.NtscRefresh);
+ Assert.False(old.ParkPointer);
+ }
+
+ [Fact]
+ public void The_new_settings_roundtrip_through_json()
+ {
+ var config = new AppConfig
+ {
+ StartScript = "\"C:\\Game Modes\\bg3-mods.bat\" off",
+ StopScript = "C:\\Game Modes\\bg3-mods.bat on",
+ NtscRefresh = true,
+ ParkPointer = true
+ };
+
+ var json = JsonSerializer.Serialize(config, Options);
+ Assert.Contains("\"ntscRefresh\":true", json);
+ Assert.Contains("\"parkPointer\":true", json);
+
+ var loaded = JsonSerializer.Deserialize(json, Options)!;
+ Assert.Equal(config.StartScript, loaded.StartScript);
+ Assert.Equal(config.StopScript, loaded.StopScript);
+ Assert.True(loaded.NtscRefresh);
+ Assert.True(loaded.ParkPointer);
+ }
+
+ [Fact]
+ public void A_session_starts_with_no_stop_command_and_no_parked_pointer()
+ {
+ var state = new ConsoleRuntimeState();
+ Assert.Equal("", state.StopScript);
+ Assert.False(state.ParkPointer);
+ Assert.Equal(0, state.PointerParks);
+ Assert.Null(state.LastPointerPark);
+ }
+}
diff --git a/tests/ConsoleMode.Tests/ConsoleMode.Tests.csproj b/tests/ConsoleMode.Tests/ConsoleMode.Tests.csproj
index ecd0da5..cb7cd86 100644
--- a/tests/ConsoleMode.Tests/ConsoleMode.Tests.csproj
+++ b/tests/ConsoleMode.Tests/ConsoleMode.Tests.csproj
@@ -30,6 +30,9 @@
+
+
+
diff --git a/tests/ConsoleMode.Tests/PointerParkingTests.cs b/tests/ConsoleMode.Tests/PointerParkingTests.cs
new file mode 100644
index 0000000..b223ab2
--- /dev/null
+++ b/tests/ConsoleMode.Tests/PointerParkingTests.cs
@@ -0,0 +1,66 @@
+using ConsoleMode.Models;
+using ConsoleMode.Services;
+
+namespace ConsoleMode.Tests;
+
+public class PointerParkingTests
+{
+ private static readonly DateTime T0 = new(2026, 1, 1, 12, 0, 0, DateTimeKind.Utc);
+
+ [Fact]
+ public void The_pointer_goes_a_few_pixels_inside_the_bottom_right_corner()
+ {
+ var tv = new ScreenRect { X = 0, Y = 0, Width = 3840, Height = 2160 };
+ Assert.Equal((3833, 2153), PointerParking.BottomRight(tv));
+ }
+
+ [Fact]
+ public void A_screen_left_of_or_above_the_main_one_has_negative_coordinates()
+ {
+ var left = new ScreenRect { X = -1920, Y = 0, Width = 1920, Height = 1080 };
+ Assert.Equal((-7, 1073), PointerParking.BottomRight(left));
+
+ var above = new ScreenRect { X = 0, Y = -2160, Width = 3840, Height = 2160 };
+ Assert.Equal((3833, -7), PointerParking.BottomRight(above));
+ }
+
+ [Fact]
+ public void A_screen_to_the_right_uses_its_own_offset()
+ {
+ var right = new ScreenRect { X = 4480, Y = 0, Width = 3840, Height = 2160 };
+ Assert.Equal((8313, 2153), PointerParking.BottomRight(right));
+ }
+
+ [Fact]
+ public void A_degenerate_screen_never_pushes_the_pointer_outside_it()
+ {
+ var tiny = new ScreenRect { X = 100, Y = 50, Width = 3, Height = 3 };
+ Assert.Equal((100, 50), PointerParking.BottomRight(tiny));
+ }
+
+ [Fact]
+ public void Nothing_happens_while_the_setting_is_off_or_the_launcher_is_not_up()
+ {
+ Assert.False(PointerParking.IsDue(false, 0, true, null, T0));
+ Assert.False(PointerParking.IsDue(true, 0, false, null, T0));
+ }
+
+ [Fact]
+ public void The_first_park_is_due_as_soon_as_the_launcher_is_up() =>
+ Assert.True(PointerParking.IsDue(true, 0, true, null, T0));
+
+ [Fact]
+ public void The_second_park_waits_for_the_launcher_to_settle()
+ {
+ Assert.False(PointerParking.IsDue(true, 1, true, T0, T0.AddSeconds(1)));
+ Assert.False(PointerParking.IsDue(true, 1, true, T0, T0.AddSeconds(2.9)));
+ Assert.True(PointerParking.IsDue(true, 1, true, T0, T0.AddSeconds(3)));
+ }
+
+ [Fact]
+ public void It_stops_after_two_parks_per_session()
+ {
+ Assert.Equal(2, PointerParking.Parks);
+ Assert.False(PointerParking.IsDue(true, 2, true, T0, T0.AddMinutes(5)));
+ }
+}
diff --git a/tests/ConsoleMode.Tests/RefreshRateTests.cs b/tests/ConsoleMode.Tests/RefreshRateTests.cs
new file mode 100644
index 0000000..3101bd9
--- /dev/null
+++ b/tests/ConsoleMode.Tests/RefreshRateTests.cs
@@ -0,0 +1,93 @@
+using ConsoleMode.Services;
+
+namespace ConsoleMode.Tests;
+
+public class RefreshRateTests
+{
+ [Theory]
+ [InlineData(120, 120)]
+ [InlineData(119, 120)] // Windows can list 119.88 Hz as 119
+ [InlineData(60, 60)]
+ [InlineData(59, 60)]
+ [InlineData(30, 30)]
+ [InlineData(29, 30)]
+ [InlineData(24, 24)]
+ [InlineData(23, 24)]
+ [InlineData(48, 48)]
+ [InlineData(47, 48)]
+ [InlineData(240, 240)]
+ [InlineData(239, 240)]
+ [InlineData(144, 144)]
+ [InlineData(165, 165)]
+ [InlineData(0, 0)]
+ public void A_listed_rate_stands_for_its_whole_number_base(int listed, int expected) =>
+ Assert.Equal(expected, RefreshRate.NtscBase(listed));
+
+ [Theory]
+ [InlineData(120, true)]
+ [InlineData(119, true)]
+ [InlineData(60, true)]
+ [InlineData(24, true)]
+ [InlineData(144, false)]
+ [InlineData(165, false)]
+ [InlineData(100, false)]
+ [InlineData(0, false)]
+ [InlineData(-5, false)]
+ public void Only_tv_rates_have_a_1000_over_1001_twin(int hertz, bool expected) =>
+ Assert.Equal(expected, RefreshRate.HasNtscTwin(hertz));
+
+ [Fact]
+ public void The_twin_of_120_is_119_88_as_a_fraction()
+ {
+ Assert.True(RefreshRate.TryNtsc(120, out var numerator, out var denominator));
+ Assert.Equal(120000u, numerator);
+ Assert.Equal(1001u, denominator);
+ Assert.Equal(119.88, RefreshRate.ToHertz(numerator, denominator), 2);
+
+ // 119 is how Windows may list 119.88: it gives the same fraction, not 118.88.
+ Assert.True(RefreshRate.TryNtsc(119, out var n2, out var d2));
+ Assert.Equal((numerator, denominator), (n2, d2));
+
+ Assert.True(RefreshRate.TryNtsc(60, out var n3, out var d3));
+ Assert.Equal(59.94, RefreshRate.ToHertz(n3, d3), 2);
+ }
+
+ [Theory]
+ [InlineData(144)]
+ [InlineData(165)]
+ [InlineData(0)]
+ public void A_rate_without_a_twin_gives_no_fraction(int hertz)
+ {
+ Assert.False(RefreshRate.TryNtsc(hertz, out var numerator, out var denominator));
+ Assert.Equal(0u, numerator);
+ Assert.Equal(0u, denominator);
+ }
+
+ [Fact]
+ public void Rates_match_within_a_few_hundredths_of_a_hertz()
+ {
+ Assert.True(RefreshRate.Matches(120000, 1001, 119880, 1000));
+ Assert.True(RefreshRate.Matches(120000, 1001, 119879, 1000));
+ Assert.False(RefreshRate.Matches(120000, 1001, 120, 1)); // 119.88 is not 120
+ Assert.False(RefreshRate.Matches(120000, 1001, 144, 1));
+ Assert.False(RefreshRate.Matches(120000, 0, 120000, 1001)); // an unreadable rate matches nothing
+ }
+
+ [Fact]
+ public void Zero_denominator_reads_as_zero_hertz() =>
+ Assert.Equal(0, RefreshRate.ToHertz(120000, 0));
+
+ [Theory]
+ [InlineData(119.88, "119.88")]
+ [InlineData(120.0, "120")]
+ [InlineData(59.94, "59.94")]
+ [InlineData(60.001, "60")]
+ [InlineData(23.976, "23.98")]
+ public void The_label_uses_a_dot_and_drops_empty_decimals(double hertz, string expected)
+ {
+ var previous = System.Globalization.CultureInfo.CurrentCulture;
+ System.Globalization.CultureInfo.CurrentCulture = new System.Globalization.CultureInfo("pt-BR");
+ try { Assert.Equal(expected, RefreshRate.Label(hertz)); }
+ finally { System.Globalization.CultureInfo.CurrentCulture = previous; }
+ }
+}
diff --git a/tests/ConsoleMode.Tests/UserCommandTests.cs b/tests/ConsoleMode.Tests/UserCommandTests.cs
new file mode 100644
index 0000000..f95b81f
--- /dev/null
+++ b/tests/ConsoleMode.Tests/UserCommandTests.cs
@@ -0,0 +1,49 @@
+using ConsoleMode.Services;
+
+namespace ConsoleMode.Tests;
+
+public class UserCommandTests
+{
+ [Theory]
+ [InlineData(" C:\\Scripts\\mods.bat off ", "C:\\Scripts\\mods.bat off")]
+ [InlineData("", "")]
+ [InlineData(" ", "")]
+ [InlineData(null, "")]
+ public void Clean_trims_and_never_returns_null(string? input, string expected) =>
+ Assert.Equal(expected, UserCommand.Clean(input));
+
+ [Theory]
+ [InlineData("mods.bat", true)]
+ [InlineData(" powershell -File x.ps1 ", true)]
+ [InlineData("", false)]
+ [InlineData(" ", false)]
+ [InlineData(null, false)]
+ public void A_command_is_set_only_when_it_has_text(string? input, bool expected) =>
+ Assert.Equal(expected, UserCommand.IsSet(input));
+
+ [Fact]
+ public void Cmd_arguments_keep_a_quoted_path_with_arguments_intact()
+ {
+ // /s drops only the outer pair of quotes, so the quoted path (with a space) and its argument survive.
+ Assert.Equal("/d /s /c \"\"C:\\My Scripts\\mods.bat\" off\"",
+ UserCommand.CmdArguments("\"C:\\My Scripts\\mods.bat\" off"));
+ Assert.Equal("/d /s /c \"mods.bat on\"", UserCommand.CmdArguments(" mods.bat on "));
+ }
+
+ [Fact]
+ public void The_log_shows_one_short_line()
+ {
+ Assert.Equal("a b", UserCommand.ForLog("a\r\nb"));
+ Assert.Equal("", UserCommand.ForLog(null));
+
+ var longCommand = new string('x', 300);
+ var shown = UserCommand.ForLog(longCommand);
+ Assert.Equal(120, shown.Length);
+ Assert.EndsWith("...", shown);
+ Assert.Equal(new string('y', 120), UserCommand.ForLog(new string('y', 120)));
+ }
+
+ [Fact]
+ public void A_command_may_run_for_a_minute_before_the_session_moves_on() =>
+ Assert.Equal(TimeSpan.FromSeconds(60), UserCommand.Timeout);
+}