Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.en-US.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions docs/TESTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 4 additions & 0 deletions src/ConsoleMode/Models/Models.cs
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,10 @@ public sealed class ConsoleRuntimeState
public bool AudioPendingTarget { get; set; }
public nint CachedBigPictureHandle { get; set; }
public DateTime? PlayniteWindowMissingSince { get; set; }
/// <summary>Playnite's big window last seen showing; it stays (hidden) while a game it started runs.</summary>
public nint PlayniteWindow { get; set; }
/// <summary>That window is put away for a game; only so the log says it once per game.</summary>
public bool PlayniteWindowPutAway { get; set; }
/// <summary>"customApp": the process name that keeps the session going, and when it went missing.</summary>
public string CustomAppWatchName { get; set; } = "";
public DateTime? CustomAppGoneSince { get; set; }
Expand Down
3 changes: 3 additions & 0 deletions src/ConsoleMode/Native/NativeWindows.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
42 changes: 37 additions & 5 deletions src/ConsoleMode/Services/ConsoleEngine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ public void Start(AppConfig config, MonitorInfo? focusInfo, Func<ScreenRect?, bo
// Before anything changes on screen: a custom app that can't be launched blocks the start.
if (config.FullscreenMode == CustomApp.Mode && CustomApp.ProblemText(config.CustomAppPath) is { } problem)
throw new InvalidOperationException(problem);
var saved = config;
config = ResolveMonitorNames(config);
AppLog.Write($"Start: foco={config.FocusMonitor}, esconder={string.Join('+', config.HideMonitors)}, estratégia={config.HideStrategy}, modo={config.FullscreenMode}");

Expand All @@ -62,6 +63,8 @@ public void Start(AppConfig config, MonitorInfo? focusInfo, Func<ScreenRect?, bo
State.AbsenceCount = 0;
State.CachedBigPictureHandle = 0;
State.PlayniteWindowMissingSince = null;
State.PlayniteWindow = 0;
State.PlayniteWindowPutAway = false;
State.CustomAppWatchName = "";
State.CustomAppGoneSince = null;
State.CustomAppTimeoutLogged = false;
Expand Down Expand Up @@ -146,6 +149,7 @@ public void Start(AppConfig config, MonitorInfo? focusInfo, Func<ScreenRect?, bo
AppLog.Write($"Start: {config.FocusMonitor} não ativou; restaurando");
throw new InvalidOperationException(LocalizationService.Get("GameScreenDidNotTurnOn"));
}
config = FollowFocusRename(saved, config);
focusInfo = Monitors.GetMonitors(true).FirstOrDefault(m => m.Name == config.FocusMonitor);
Monitors.GetDisplayModes(config.FocusMonitor, focusInfo, forceRefresh: true);
}
Expand All @@ -169,6 +173,7 @@ public void Start(AppConfig config, MonitorInfo? focusInfo, Func<ScreenRect?, bo
Thread.Sleep(400);
break;
}
config = FollowFocusRename(saved, config);
}

Monitors.SetPrimary(config.FocusMonitor);
Expand Down Expand Up @@ -618,6 +623,22 @@ private AppConfig ResolveMonitorNames(AppConfig config)
return config.WithMonitors(focus, hide, modes);
}

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

Expand Down
20 changes: 20 additions & 0 deletions src/ConsoleMode/Services/DisplayIdentity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,26 @@ public static List<string> LayoutMismatches(
return wrong;
}

/// <summary>
/// What each name of the backup is called now (saved name → current name), matched by <c>MonitorID</c> like
/// <see cref="RemapLayoutNames"/>. 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).
/// </summary>
public static Dictionary<string, string> CurrentNames(
Dictionary<string, Dictionary<string, string>> specs, IEnumerable<(string MonitorId, string Name)> current)
{
var byId = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var (id, name) in current)
if (!string.IsNullOrWhiteSpace(id)) byId.TryAdd(id, name);

var names = new Dictionary<string, string>(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;
}

/// <summary>
/// Re-keys layout sections by the name each monitor has now, matched by <c>MonitorID</c>: a
/// monitor that was disabled can come back as another \.\DISPLAYn. Sections whose monitor isn't
Expand Down
9 changes: 9 additions & 0 deletions src/ConsoleMode/Services/LaunchService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,15 @@ public nint[] GetPlayniteHandles()

public bool IsPlayniteRunning() => Process.GetProcessesByName("Playnite.FullscreenApp").Length > 0;

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

Expand Down
52 changes: 33 additions & 19 deletions src/ConsoleMode/Services/MonitorService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,13 @@ public void SaveBackupMeta(MonitorBackupMeta meta)
File.WriteAllText(AppPaths.BackupMonitorMeta, JsonSerializer.Serialize(meta, JsonUtil.Options));
}

public MonitorRestoreContext GetRestoreContext(ConsoleRuntimeState state)
/// <param name="rename">
/// Saved name → current name (<see cref="DisplayIdentity.CurrentNames"/>), 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.
/// </param>
public MonitorRestoreContext GetRestoreContext(ConsoleRuntimeState state, IReadOnlyDictionary<string, string>? 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,
Expand All @@ -81,10 +86,10 @@ public MonitorRestoreContext GetRestoreContext(ConsoleRuntimeState state)
{
var meta = JsonSerializer.Deserialize<MonitorBackupMeta>(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 */ }
Expand All @@ -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)
Expand Down Expand Up @@ -155,28 +165,30 @@ 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
{
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++)
Expand All @@ -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}");
}
}

Expand Down
9 changes: 7 additions & 2 deletions src/ConsoleMode/Services/PlayniteExitPolicy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,15 @@ public static class PlayniteExitPolicy
public static readonly TimeSpan WindowGrace = TimeSpan.FromSeconds(20);

/// <param name="windowMissingSince">When the big window went missing, or null if it is showing.</param>
public static bool IsExit(bool processRunning, bool bigWindowShowing, DateTime? windowMissingSince, DateTime now)
/// <param name="windowPutAway">
/// Its window still exists but is hidden or minimized: Playnite does that while a game it started runs, however
/// long the game lasts.
/// </param>
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;
}
}
Loading
Loading