diff --git a/CHANGELOG.en-US.md b/CHANGELOG.en-US.md index ffc65c9b..b330f331 100644 --- a/CHANGELOG.en-US.md +++ b/CHANGELOG.en-US.md @@ -3,6 +3,9 @@ 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] +### Fixes +- Playnite: starting a game no longer ends the session. With "Minimize after game startup" on (the Selene theme turns it on), Playnite hides its window while the game runs, and after 20 s Console Mode took it as closed and brought the desk screens back mid-game. The session now lasts until Playnite really closes. (#191) +- Screens: when Windows renames the screens during a session (the TV goes in as `DISPLAY3` and comes out as `DISPLAY1`), the chosen resolution goes to the TV and going back to the PC turns the right screens on and off; before, it could turn off a desk monitor taking it for the TV. Going back also no longer spends 10 s trying to detach the TV while it is still the main screen. (#191) ## [1.7.0-beta.1] ### What's new diff --git a/CHANGELOG.md b/CHANGELOG.md index 6845fad4..a6170c55 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,9 @@ 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] +### Correções +- Playnite: abrir um jogo não encerra mais a sessão. Com "Minimizar após iniciar o jogo" ligado (o tema Selene liga), o Playnite esconde a janela enquanto o jogo roda, e depois de 20 s o Console Mode achava que ele tinha fechado e devolvia as telas da mesa no meio do jogo. Agora a sessão segue até o Playnite fechar de verdade. (#191) +- Telas: quando o Windows troca o nome das telas no meio da sessão (a TV entra como `DISPLAY3` e sai como `DISPLAY1`), a resolução escolhida vai para a TV e a volta ao PC liga e desliga as telas certas; antes, ele podia desligar um monitor da mesa achando que era a TV. A volta também não perde mais 10 s tentando desligar a TV enquanto ela ainda é a tela principal. (#191) ## [1.7.0-beta.1] ### Novidades diff --git a/docs/TESTING.md b/docs/TESTING.md index 0b1d3916..038b7729 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -630,6 +630,12 @@ Pré-condições: a opção **Tirar o ponteiro do mouse do caminho** ligada (é - [ ] Interface Console: nenhuma faixa cinza no topo; o fundo (Aurora, capas ou imagem) vai até a borda da janela, e minimizar, maximizar e fechar aparecem brancos, com realce suave ao passar o mouse e mais forte ao clicar. Resultado: ______ - [ ] Interface Console: arrastar a janela pela área de cima (fora das abas e dos botões) funciona; as abas, o relógio e os botões redondos continuam clicáveis. Resultado: ______ +## Playnite com jogo aberto e nomes das telas (#191) + +- [ ] Playnite em tela cheia com "Minimizar após iniciar o jogo" ligado (Selene): abrir um jogo pela sessão e jogar mais de 1 minuto. A sessão continua (o log diz "Playnite escondeu a janela (jogo aberto); a sessão continua"); ao fechar o jogo o Playnite volta na TV ("voltou a mostrar a janela") e a sessão segue. Resultado: ______ +- [ ] Fechar o Playnite depois disso encerra a sessão e a mesa volta como estava ("Restore: concluído com sucesso", sem "Não foi possível desconectar"). Resultado: ______ +- [ ] Com a TV como tela de jogo e os dois monitores da mesa desligados pela sessão, abrir e encerrar várias sessões seguidas. Se o log mostrar "Telas: a tela de jogo passou de … para …", a resolução da TV é aplicada, o jogo abre na TV e a volta religa os monitores da mesa nas posições certas (o log da volta mostra "telas com outro nome desde o backup"). Resultado: ______ + ## Interface única e tour guiado (1.7.0) Pré-condições: um `config.json` sem `consoleTourDone` (vale para quem atualiza de uma versão anterior, mesmo tendo visto o tutorial antigo). Teste com controle, só com mouse e só com teclado. diff --git a/src/ConsoleMode/Models/Models.cs b/src/ConsoleMode/Models/Models.cs index b9d56ecf..9c74c266 100644 --- a/src/ConsoleMode/Models/Models.cs +++ b/src/ConsoleMode/Models/Models.cs @@ -414,6 +414,10 @@ public sealed class ConsoleRuntimeState public bool AudioPendingTarget { get; set; } public nint CachedBigPictureHandle { get; set; } public DateTime? PlayniteWindowMissingSince { get; set; } + /// Playnite's big window last seen showing; it stays (hidden) while a game it started runs. + public nint PlayniteWindow { get; set; } + /// That window is put away for a game; only so the log says it once per game. + public bool PlayniteWindowPutAway { get; set; } /// "customApp": the process name that keeps the session going, and when it went missing. public string CustomAppWatchName { get; set; } = ""; public DateTime? CustomAppGoneSince { get; set; } diff --git a/src/ConsoleMode/Native/NativeWindows.cs b/src/ConsoleMode/Native/NativeWindows.cs index 264a582d..2e1c8afc 100644 --- a/src/ConsoleMode/Native/NativeWindows.cs +++ b/src/ConsoleMode/Native/NativeWindows.cs @@ -63,6 +63,9 @@ public static bool ForceForeground(nint hwnd) [DllImport("user32.dll")] public static extern bool IsWindowVisible(nint hWnd); + [DllImport("user32.dll")] + public static extern bool IsIconic(nint hWnd); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetClassName(nint hWnd, StringBuilder lpClassName, int nMaxCount); diff --git a/src/ConsoleMode/Services/ConsoleEngine.cs b/src/ConsoleMode/Services/ConsoleEngine.cs index 9c502acf..cc075275 100644 --- a/src/ConsoleMode/Services/ConsoleEngine.cs +++ b/src/ConsoleMode/Services/ConsoleEngine.cs @@ -39,6 +39,7 @@ public void Start(AppConfig config, MonitorInfo? focusInfo, Func m.Name == config.FocusMonitor); Monitors.GetDisplayModes(config.FocusMonitor, focusInfo, forceRefresh: true); } @@ -169,6 +173,7 @@ public void Start(AppConfig config, MonitorInfo? focusInfo, Func + /// Turning screens on and off can give the game screen another \\.\DISPLAYn (the TV went in as DISPLAY3 and came + /// out as DISPLAY1 once the desk screens were detached): it is looked up again by its id, so the mode, HDR and + /// the window placement land on it and not on a name that is now another screen's, or nobody's. + /// + private AppConfig FollowFocusRename(AppConfig saved, AppConfig resolved) + { + Monitors.ClearCache(); + var now = ResolveMonitorNames(saved); + if (string.Equals(now.FocusMonitor, resolved.FocusMonitor, StringComparison.OrdinalIgnoreCase)) return resolved; + AppLog.Write($"Telas: a tela de jogo passou de {resolved.FocusMonitor} para {now.FocusMonitor}"); + State.FocusMonitor = now.FocusMonitor; + State.FocusMonitorRect = null; + return now; + } + private void MoveToFocus(string monitorName, nint[] handles, ScreenRect? rect) { if (rect is not null) @@ -655,17 +676,28 @@ private bool IsPlayniteExitSignaled(bool watchedGone) { if (watchedGone) State.CachedBigPictureHandle = 0; var showing = Launch.IsPlayniteActive(State); + var handle = State.CachedBigPictureHandle; if (showing && watchedGone) { - var handle = State.CachedBigPictureHandle; - AppLog.Write("Loop: Playnite trocou de janela; acompanhando a nova"); + // The same window back from a game is not a new one; it is watched again all the same. + if (handle != State.PlayniteWindow) AppLog.Write("Loop: Playnite trocou de janela; acompanhando a nova"); OnUi(() => State.BigPictureWatchActive = NativeWindows.StartBigPictureExitWatch(handle)); } + if (showing) State.PlayniteWindow = handle; + + // A game started from Playnite: it hides its window until the game ends. That is not leaving the session. + var putAway = !showing && LaunchService.IsPlayniteWindowPutAway(State.PlayniteWindow); + if (putAway != State.PlayniteWindowPutAway) + { + State.PlayniteWindowPutAway = putAway; + AppLog.Write(putAway ? "Loop: Playnite escondeu a janela (jogo aberto); a sessão continua" : "Loop: Playnite voltou a mostrar a janela"); + } - if (showing) State.PlayniteWindowMissingSince = null; + if (showing || putAway) State.PlayniteWindowMissingSince = null; else State.PlayniteWindowMissingSince ??= DateTime.Now; - var exit = PlayniteExitPolicy.IsExit(Launch.IsPlayniteRunning(), showing, State.PlayniteWindowMissingSince, DateTime.Now); - if (exit) AppLog.Write("Loop: Playnite fechou"); + var running = Launch.IsPlayniteRunning(); + var exit = PlayniteExitPolicy.IsExit(running, showing, State.PlayniteWindowMissingSince, DateTime.Now, putAway); + if (exit) AppLog.Write(running ? $"Loop: Playnite sem janela há {PlayniteExitPolicy.WindowGrace.TotalSeconds:0} s" : "Loop: Playnite fechou"); return exit; } diff --git a/src/ConsoleMode/Services/DisplayIdentity.cs b/src/ConsoleMode/Services/DisplayIdentity.cs index 9e98ff19..a9c9fadb 100644 --- a/src/ConsoleMode/Services/DisplayIdentity.cs +++ b/src/ConsoleMode/Services/DisplayIdentity.cs @@ -189,6 +189,26 @@ public static List LayoutMismatches( return wrong; } + /// + /// What each name of the backup is called now (saved name → current name), matched by MonitorID like + /// . The names saved next to the backup (primary, game screen, hidden screens) go + /// through it: a session can shuffle the \\.\DISPLAYn names, and a stale one would point at another screen. + /// Names whose monitor isn't found are left out (they stay as saved). + /// + public static Dictionary CurrentNames( + Dictionary> specs, IEnumerable<(string MonitorId, string Name)> current) + { + var byId = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var (id, name) in current) + if (!string.IsNullOrWhiteSpace(id)) byId.TryAdd(id, name); + + var names = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var (savedName, spec) in specs) + if (spec.TryGetValue("MonitorID", out var id) && byId.TryGetValue(id, out var now)) + names[savedName] = now; + return names; + } + /// /// Re-keys layout sections by the name each monitor has now, matched by MonitorID: a /// monitor that was disabled can come back as another \.\DISPLAYn. Sections whose monitor isn't diff --git a/src/ConsoleMode/Services/LaunchService.cs b/src/ConsoleMode/Services/LaunchService.cs index 6e78bacc..0821ad09 100644 --- a/src/ConsoleMode/Services/LaunchService.cs +++ b/src/ConsoleMode/Services/LaunchService.cs @@ -188,6 +188,15 @@ public nint[] GetPlayniteHandles() public bool IsPlayniteRunning() => Process.GetProcessesByName("Playnite.FullscreenApp").Length > 0; + /// + /// Playnite puts its window away while a game runs ("Minimize after game startup" in its fullscreen settings, on in + /// themes like Selene): the same window is hidden (or minimized) and comes back when the game ends. It still + /// exists, unlike a loading window swapped for the main one, which is destroyed. + /// + public static bool IsPlayniteWindowPutAway(nint window) => + window != 0 && NativeWindows.IsWindow(window) + && (!NativeWindows.IsWindowVisible(window) || NativeWindows.IsIconic(window)); + public nint[] GetFullscreenHandles(string mode) => mode == "playnite" ? GetPlayniteHandles() : GetBigPictureHandles(); diff --git a/src/ConsoleMode/Services/MonitorService.cs b/src/ConsoleMode/Services/MonitorService.cs index 84e7020f..ae6fade9 100644 --- a/src/ConsoleMode/Services/MonitorService.cs +++ b/src/ConsoleMode/Services/MonitorService.cs @@ -65,8 +65,13 @@ public void SaveBackupMeta(MonitorBackupMeta meta) File.WriteAllText(AppPaths.BackupMonitorMeta, JsonSerializer.Serialize(meta, JsonUtil.Options)); } - public MonitorRestoreContext GetRestoreContext(ConsoleRuntimeState state) + /// + /// Saved name → current name (), applied to what the backup's meta file + /// says only: those names are from the moment of the backup, while the session's own may already be current. + /// + public MonitorRestoreContext GetRestoreContext(ConsoleRuntimeState state, IReadOnlyDictionary? rename = null) { + string Now(string name) => rename is not null && rename.TryGetValue(name, out var current) ? current : name; var ctx = new MonitorRestoreContext { OriginalPrimary = state.OriginalPrimary, @@ -81,10 +86,10 @@ public MonitorRestoreContext GetRestoreContext(ConsoleRuntimeState state) { var meta = JsonSerializer.Deserialize(File.ReadAllText(AppPaths.BackupMonitorMeta), JsonUtil.Options); if (meta is null) return ctx; - if (!string.IsNullOrWhiteSpace(meta.OriginalPrimary)) ctx.OriginalPrimary = meta.OriginalPrimary; + if (!string.IsNullOrWhiteSpace(meta.OriginalPrimary)) ctx.OriginalPrimary = Now(meta.OriginalPrimary); ctx.FocusWasInactive = meta.FocusWasInactive; - if (!string.IsNullOrWhiteSpace(meta.FocusMonitor)) ctx.FocusMonitor = meta.FocusMonitor; - if (meta.HideMonitors.Count > 0) ctx.HideMonitors = meta.HideMonitors; + if (!string.IsNullOrWhiteSpace(meta.FocusMonitor)) ctx.FocusMonitor = Now(meta.FocusMonitor); + if (meta.HideMonitors.Count > 0) ctx.HideMonitors = [.. meta.HideMonitors.Select(Now)]; if (!string.IsNullOrWhiteSpace(meta.HideStrategy)) ctx.HideStrategy = meta.HideStrategy; } catch { /* keep in-memory context */ } @@ -102,8 +107,13 @@ public RestoreResult RestoreBackup(ConsoleRuntimeState state) return result; } - var ctx = GetRestoreContext(state); - var backupSpecs = _backend.ResolveLayout(GetBackupMonitorSpecs(AppPaths.BackupMonitorConfig)); + var savedSpecs = GetBackupMonitorSpecs(AppPaths.BackupMonitorConfig); + var backupSpecs = _backend.ResolveLayout(savedSpecs); + var rename = DisplayIdentity.CurrentNames(savedSpecs, GetMonitors(true).Select(m => (m.MonitorId, m.Name))); + var ctx = GetRestoreContext(state, rename); + var moved = rename.Where(kv => !string.Equals(kv.Key, kv.Value, StringComparison.OrdinalIgnoreCase)).ToList(); + if (moved.Count > 0) + AppLog.Write($"Restore: telas com outro nome desde o backup: {string.Join(", ", moved.Select(kv => $"{kv.Key} → {kv.Value}"))}"); AppLog.Write($"Restore: iniciando (primário={ctx.OriginalPrimary}, foco={ctx.FocusMonitor}, focoInativo={ctx.FocusWasInactive}, esconder={string.Join('+', ctx.HideMonitors)})"); if (ctx.HideStrategy == "turnOff" && ctx.HideMonitors.Count > 0) @@ -155,14 +165,22 @@ public RestoreResult RestoreBackup(ConsoleRuntimeState state) // 2. Detach the screens that were off BEFORE placing the others: while the TV is still part of the // desktop, Windows keeps the positions around it and moves the other screens when it goes. If the // originals didn't come back, the TV is the only picture left: leave it on. + // The primary goes back first: Windows refuses to detach the primary screen (the TV, during the session). + if (!string.IsNullOrWhiteSpace(ctx.OriginalPrimary)) + { + backupSpecs.TryGetValue(ctx.OriginalPrimary, out var primarySpec); + if (!RestorePrimaryWithRetry(ctx.OriginalPrimary, primarySpec)) + result.Issues.Add($"Não foi possível restaurar o primário para {ctx.OriginalPrimary}"); + } + if (restored) { AppLog.Write($"Restore: telas que voltam a ficar desligadas: {(monitorsToDisable.Count == 0 ? "nenhuma" : string.Join('+', monitorsToDisable))}"); + // A refusal here is tried again below; only a screen still on at the end is a problem. foreach (var name in monitorsToDisable) { if (string.Equals(name, ctx.OriginalPrimary, StringComparison.OrdinalIgnoreCase)) continue; - if (!DisableWithRetry(name)) - result.Issues.Add($"Não foi possível desconectar {name}"); + DisableWithRetry(name); } } else @@ -170,13 +188,7 @@ public RestoreResult RestoreBackup(ConsoleRuntimeState state) AppLog.Write("Restore: telas originais não voltaram; a tela de jogo fica ligada para não ficar sem imagem"); } - // 3. Primary, then every position and mode of the backup in one go, and check that it stuck. - if (!string.IsNullOrWhiteSpace(ctx.OriginalPrimary)) - { - backupSpecs.TryGetValue(ctx.OriginalPrimary, out var primarySpec); - if (!RestorePrimaryWithRetry(ctx.OriginalPrimary, primarySpec)) - result.Issues.Add($"Não foi possível restaurar o primário para {ctx.OriginalPrimary}"); - } + // 3. Every position and mode of the backup in one go, and check that it stuck. const int layoutAttempts = 3; for (var attempt = 1; attempt <= layoutAttempts; attempt++) @@ -201,10 +213,12 @@ public RestoreResult RestoreBackup(ConsoleRuntimeState state) if (back.Count == 0) break; AppLog.Write($"Restore: {string.Join('+', back)} voltou a ligar ao aplicar o layout; desconectando de novo ({round}/2)"); foreach (var name in back) - { - if (!DisableWithRetry(name) && round == 2) - result.Issues.Add($"Não foi possível desconectar {name}"); - } + DisableWithRetry(name); + } + foreach (var name in monitorsToDisable) + { + if (string.Equals(name, ctx.OriginalPrimary, StringComparison.OrdinalIgnoreCase) || !IsActiveNow(name)) continue; + result.Issues.Add($"Não foi possível desconectar {name}"); } } diff --git a/src/ConsoleMode/Services/PlayniteExitPolicy.cs b/src/ConsoleMode/Services/PlayniteExitPolicy.cs index 24895a05..89334f76 100644 --- a/src/ConsoleMode/Services/PlayniteExitPolicy.cs +++ b/src/ConsoleMode/Services/PlayniteExitPolicy.cs @@ -10,10 +10,15 @@ public static class PlayniteExitPolicy public static readonly TimeSpan WindowGrace = TimeSpan.FromSeconds(20); /// When the big window went missing, or null if it is showing. - public static bool IsExit(bool processRunning, bool bigWindowShowing, DateTime? windowMissingSince, DateTime now) + /// + /// Its window still exists but is hidden or minimized: Playnite does that while a game it started runs, however + /// long the game lasts. + /// + public static bool IsExit(bool processRunning, bool bigWindowShowing, DateTime? windowMissingSince, DateTime now, + bool windowPutAway = false) { if (!processRunning) return true; - if (bigWindowShowing || windowMissingSince is null) return false; + if (bigWindowShowing || windowPutAway || windowMissingSince is null) return false; return now - windowMissingSince.Value >= WindowGrace; } } diff --git a/tests/ConsoleMode.Tests/DisplayIdentityTests.cs b/tests/ConsoleMode.Tests/DisplayIdentityTests.cs index 201ec0a0..678ad399 100644 --- a/tests/ConsoleMode.Tests/DisplayIdentityTests.cs +++ b/tests/ConsoleMode.Tests/DisplayIdentityTests.cs @@ -88,6 +88,40 @@ public void Layout_file_round_trips_and_follows_renamed_monitors() Assert.Equal(@"\\.\DISPLAY2", remapped[@"\\.\DISPLAY2"]["Name"]); } + [Fact] + public void Saved_names_follow_their_monitors_when_two_swap() + { + // The owner's desk: the TV (off) was DISPLAY3 and the HP DISPLAY1 at the backup; after the session the + // TV is DISPLAY1 and the HP DISPLAY3. The game screen saved as DISPLAY3 must now mean DISPLAY1, not the HP. + var text = DisplayIdentity.FormatLayout( + [ + new LayoutEntry(@"\\.\DISPLAY2", @"MONITOR\TCL1003\{x}\0011", "", 32, 1920, 1080, 240, 0, 0), + new LayoutEntry(@"\\.\DISPLAY1", @"MONITOR\HWP3318\{x}\0012", "BRG", 32, 1080, 1920, 60, 1920, -301, 1), + new LayoutEntry(@"\\.\DISPLAY3", @"MONITOR\GSM0001\{x}\0002", "", 0, 0, 0, 0, 0, 0) + ]); + var specs = DisplayIdentity.ParseLayout(text.Split("\r\n")); + + var names = DisplayIdentity.CurrentNames(specs, + [ + (@"MONITOR\TCL1003\{x}\0011", @"\\.\DISPLAY2"), + (@"MONITOR\GSM0001\{x}\0002", @"\\.\DISPLAY1"), + (@"MONITOR\HWP3318\{x}\0012", @"\\.\DISPLAY3") + ]); + + Assert.Equal(@"\\.\DISPLAY2", names[@"\\.\DISPLAY2"]); + Assert.Equal(@"\\.\DISPLAY1", names[@"\\.\DISPLAY3"]); + Assert.Equal(@"\\.\DISPLAY3", names[@"\\.\DISPLAY1"]); + } + + [Fact] + public void Saved_names_of_a_missing_monitor_are_left_out() + { + var specs = DisplayIdentity.ParseLayout(DisplayIdentity.FormatLayout( + [new LayoutEntry(@"\\.\DISPLAY3", @"MONITOR\GSM0001\{x}\0002", "", 0, 0, 0, 0, 0, 0)]).Split("\r\n")); + + Assert.Empty(DisplayIdentity.CurrentNames(specs, [(@"MONITOR\DEL4083\{x}\0001", @"\\.\DISPLAY1")])); + } + [Fact] public void Layout_file_keeps_a_rotated_monitor_portrait() { diff --git a/tests/ConsoleMode.Tests/PlayniteExitPolicyTests.cs b/tests/ConsoleMode.Tests/PlayniteExitPolicyTests.cs index 536a98c8..e4737e96 100644 --- a/tests/ConsoleMode.Tests/PlayniteExitPolicyTests.cs +++ b/tests/ConsoleMode.Tests/PlayniteExitPolicyTests.cs @@ -21,4 +21,13 @@ public void Waits_while_the_loading_window_is_swapped_for_the_main_one() => [Fact] public void Exits_when_the_process_stays_windowless_past_the_grace() => Assert.True(PlayniteExitPolicy.IsExit(processRunning: true, bigWindowShowing: false, windowMissingSince: T0, T0 + PlayniteExitPolicy.WindowGrace)); + + [Fact] + public void Stays_while_playnite_hides_its_window_for_a_game() => + // "Minimize after game startup" (Selene turns it on): a game that lasts hours is still the session. + Assert.False(PlayniteExitPolicy.IsExit(processRunning: true, bigWindowShowing: false, windowMissingSince: T0, T0 + TimeSpan.FromHours(3), windowPutAway: true)); + + [Fact] + public void Exits_when_playnite_closes_while_its_window_is_put_away() => + Assert.True(PlayniteExitPolicy.IsExit(processRunning: false, bigWindowShowing: false, windowMissingSince: null, T0, windowPutAway: true)); }