diff --git a/CHANGELOG.en-US.md b/CHANGELOG.en-US.md index e6f998c..b1a0469 100644 --- a/CHANGELOG.en-US.md +++ b/CHANGELOG.en-US.md @@ -7,6 +7,7 @@ English (US) release notes, mirroring CHANGELOG.md (Brazilian Portuguese). Befor - Desktop icons go back where they were after a session: changing the main display could make Windows reshuffle them. Console Mode saves their positions before touching the screens and puts them back a few seconds after the desk is restored. Toggle it in Settings → **Put desktop icons back in place** (on by default); it does nothing while **Auto arrange icons** is on. (#167) - **Wake the PC with the controller**: in Settings (and in the Console System tab → Controller), Console Mode shows whether the Xbox Wireless Adapter, Bluetooth or a wired controller can wake the PC from sleep, and **Turn on** enables it for them (Windows asks for administrator permission). Together with **Enter when a controller connects**, pressing the controller's center button wakes the PC straight into console mode. It doesn't work when the PC is shut down or hibernating. (#168) - Console interface: the Home tiles show the official Steam, Playnite and Xbox logos, read from the installed apps, and Custom app shows its `.exe` icon. When an app isn't installed, its tile keeps the generic icon. (#169) +- **Per-game profiles**: each Steam game can have its own resolution, HDR, FPS limit and audio output. With the game running, open the session menu and pick **Game profile → Save the current settings**; next time it starts in console mode, the profile is applied by itself and undone when the game closes. Also works for Steam games opened from Playnite or the Xbox app. Profiles are listed in Settings → **Per-game profiles**, where you can delete them. (#170) ## [1.7.0-alpha.2] ### What's new diff --git a/CHANGELOG.md b/CHANGELOG.md index 726c206..396c694 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ Notas em português do Brasil; a versão em inglês (Estados Unidos) fica em `CH - Os ícones da área de trabalho voltam ao lugar depois da sessão: trocar a tela principal podia fazer o Windows embaralhá-los. O Console Mode salva a posição antes de mexer nas telas e os recoloca alguns segundos depois de restaurar a mesa. Liga e desliga em Ajustes → **Devolver os ícones da área de trabalho ao lugar** (ligado por padrão); não faz nada com **Organizar ícones automaticamente** ligado. (#167) - **Acordar o PC pelo controle**: em Ajustes (e na aba Sistema → Controle do modo Console), o Console Mode mostra se o adaptador sem fio Xbox, o Bluetooth ou o controle no cabo podem acordar o PC da suspensão e, em **Ativar**, liga isso para eles (o Windows pede permissão de administrador). Junto com **Entrar ao conectar um controle**, apertar o botão central do controle acorda o PC direto no modo console. Não funciona com o PC desligado ou em hibernação. (#168) - Interface Console: os blocos do Início mostram os logos oficiais da Steam, do Playnite e do Xbox, lidos dos apps instalados, e o Aplicativo personalizado mostra o ícone do seu `.exe`. Sem o app instalado, o bloco mantém o ícone genérico. (#169) +- **Perfis por jogo**: cada jogo da Steam pode ter sua própria resolução, HDR, limite de FPS e saída de áudio. Com o jogo rodando, abra o menu da sessão e escolha **Perfil do jogo → Salvar os ajustes atuais**; da próxima vez que ele abrir no modo console, o perfil é aplicado sozinho e desfeito quando o jogo fecha. Vale também para jogos da Steam abertos pelo Playnite ou pelo app Xbox. Os perfis ficam em Ajustes → **Perfis por jogo**, onde dá para apagá-los. (#170) ## [1.7.0-alpha.2] ### Novidades diff --git a/docs/GUIDE.de-DE.md b/docs/GUIDE.de-DE.md index f69016d..47b099a 100644 --- a/docs/GUIDE.de-DE.md +++ b/docs/GUIDE.de-DE.md @@ -31,6 +31,8 @@ Ein Wechsel des Hauptbildschirms kann Windows dazu bringen, die Desktopsymbole n **PC mit dem Controller aufwecken** erlaubt dem Xbox Wireless Adapter, Bluetooth oder einem Controller am Kabel, den PC mit der mittleren Taste des Controllers aus dem Energiesparmodus zu wecken. **Einschalten** fragt Windows nach Administratorrechten und aktiviert bei diesen Geräten *Gerät kann den Computer aus dem Ruhezustand aktivieren*. Ein ausgeschalteter PC oder einer im Ruhezustand wacht nicht auf, und manche PCs schalten Bluetooth im Energiesparmodus ab. Zusammen mit **Beim Verbinden eines Controllers starten** wacht der PC direkt im Konsolenmodus auf. +**Profile pro Spiel** geben jedem Steam-Spiel eine eigene Auflösung, HDR, ein FPS-Limit und eine Audioausgabe. Öffne bei laufendem Spiel das Sitzungsmenü und wähle **Spielprofil → Aktuelle Einstellungen für … speichern**: Gespeichert wird, was der Spielbildschirm in diesem Moment nutzt. Wenn das Spiel das nächste Mal während einer Sitzung startet, wendet Console Mode das Profil an, und beim Schließen kehrt der Bildschirm in den vorherigen Zustand zurück. Das Spiel wird über Steam erkannt, egal ob es aus Big Picture, Playnite oder der Xbox-App gestartet wurde. Die gespeicherten Profile stehen unter Einstellungen → **Profile pro Spiel** und lassen sich dort löschen (in der Konsolenoberfläche: System → Beim Starten des Konsolenmodus). + ## Lokale Steuerungs-API `consolemode://`-Links werden abgeschickt, ohne auf eine Antwort zu warten. Werkzeuge, die eine Antwort brauchen, etwa ein Fernsteuerungs-Agent, der als Windows-Dienst läuft, oder ein Stream-Deck-Plugin, das anzeigt, ob der Konsolenmodus aktiv ist, können die Named Pipe `\\.\pipe\ConsoleMode.Control` nutzen, solange die App läuft: Eine JSON-Zeile senden, eine zurückbekommen. diff --git a/docs/GUIDE.es-ES.md b/docs/GUIDE.es-ES.md index d50ec65..3858d7c 100644 --- a/docs/GUIDE.es-ES.md +++ b/docs/GUIDE.es-ES.md @@ -31,6 +31,8 @@ Cambiar la pantalla principal puede hacer que Windows reordene los iconos del es **Despertar el PC con el mando** permite que el adaptador inalámbrico Xbox, el Bluetooth o un mando con cable despierten el PC de la suspensión con el botón central del mando. **Activar** pide permiso de administrador a Windows y marca *Permitir que este dispositivo reactive el equipo* en esos dispositivos. No despierta un PC apagado o en hibernación, y algunos PC cortan la energía del Bluetooth al suspender. Junto con **Entrar al conectar un mando**, el PC despierta directamente en modo consola. +Los **perfiles por juego** dan a cada juego de Steam su propia resolución, HDR, límite de FPS y salida de audio. Con el juego en marcha, abre el menú de la sesión y elige **Perfil del juego → Guardar los ajustes actuales para…**: se guarda lo que usa la pantalla de juego en ese momento. La próxima vez que ese juego se abra durante una sesión, Console Mode aplica el perfil y, cuando el juego se cierra, la pantalla vuelve a estar como antes. El juego se detecta a través de Steam, tanto si se abre desde Big Picture como desde Playnite o la aplicación Xbox. Los perfiles guardados aparecen en Ajustes → **Perfiles por juego**, donde puedes borrarlos (en la interfaz Consola: Sistema → Al entrar en modo consola). + ## API de control local Los enlaces `consolemode://` se lanzan sin esperar respuesta. Las herramientas que necesitan una respuesta (un agente de control remoto que funciona como servicio de Windows, un plugin de Stream Deck que muestra si el modo consola está activo) pueden usar la canalización con nombre (named pipe) `\\.\pipe\ConsoleMode.Control` mientras la aplicación está abierta: envía una línea JSON y recibe otra. diff --git a/docs/GUIDE.fr-FR.md b/docs/GUIDE.fr-FR.md index fd50d0a..627fa42 100644 --- a/docs/GUIDE.fr-FR.md +++ b/docs/GUIDE.fr-FR.md @@ -31,6 +31,8 @@ Changer d'écran principal peut amener Windows à mélanger les icônes du burea **Réveiller le PC avec la manette** permet à l'adaptateur sans fil Xbox, au Bluetooth ou à une manette filaire de sortir le PC de la veille avec le bouton central de la manette. **Activer** demande l'autorisation d'administrateur à Windows et coche *Autoriser ce périphérique à sortir l'ordinateur du mode veille* sur ces périphériques. Un PC éteint ou en veille prolongée ne se réveille pas, et certains PC coupent le Bluetooth pendant la veille. Avec **Entrer à la connexion d'une manette**, le PC se réveille directement en mode console. +Les **profils par jeu** donnent à chaque jeu Steam sa propre résolution, son HDR, sa limite de FPS et sa sortie audio. Pendant que le jeu tourne, ouvrez le menu de la session et choisissez **Profil du jeu → Enregistrer les réglages actuels pour…** : ce qu'utilise l'écran de jeu à ce moment-là est enregistré. La prochaine fois que ce jeu démarre pendant une session, Console Mode applique le profil et, quand le jeu se ferme, l'écran revient à son état précédent. Le jeu est détecté via Steam, qu'il soit lancé depuis Big Picture, Playnite ou l'application Xbox. Les profils enregistrés sont listés dans Paramètres → **Profils par jeu**, où vous pouvez les supprimer (dans l'interface Console : Système → À l'entrée en mode console). + ## API de contrôle local Les liens `consolemode://` s'envoient sans attendre de réponse. Les outils qui ont besoin d'une réponse (un agent de contrôle à distance qui tourne comme service Windows, un plugin Stream Deck qui indique si le mode console est actif) peuvent utiliser le canal nommé `\\.\pipe\ConsoleMode.Control` tant que l'application tourne : envoyez une ligne JSON, recevez-en une en retour. diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 8d1242d..0c34e35 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -37,6 +37,8 @@ Changing the main display can make Windows reshuffle the desktop icons. **Put de **Wake the PC with the controller** lets the Xbox Wireless Adapter, the Bluetooth radio or a wired controller wake the PC from sleep with the controller's center button. **Turn on** asks Windows for administrator permission and ticks *Allow this device to wake the computer* on those devices. It can't wake a PC that is shut down or hibernating, and some PCs cut power to Bluetooth while asleep. Together with **Enter when a controller connects**, the PC wakes straight into console mode. +**Per-game profiles** give each Steam game its own resolution, HDR, FPS limit and audio output. With the game running, open the session menu and pick **Game profile → Save the current settings for…**: whatever the game screen uses at that moment is saved. Next time that game starts during a session, Console Mode applies it, and when the game closes the screen goes back to how it was. The game is detected from Steam, whether it was opened from Big Picture, Playnite or the Xbox app. The saved profiles are listed in Settings → **Per-game profiles**, where you can delete them (in the Console interface: System → When entering console mode). + ## Local control API `consolemode://` links fire and forget. Tools that need an answer — a remote-control agent running as a Windows service, a Stream Deck plugin showing whether console mode is on — can use the named pipe `\\.\pipe\ConsoleMode.Control` while the app is running: send one JSON line, get one back. diff --git a/docs/GUIDE.pt-BR.md b/docs/GUIDE.pt-BR.md index dacd004..c66abf3 100644 --- a/docs/GUIDE.pt-BR.md +++ b/docs/GUIDE.pt-BR.md @@ -37,6 +37,8 @@ Trocar a tela principal pode fazer o Windows embaralhar os ícones da área de t **Acordar o PC pelo controle** deixa o adaptador sem fio Xbox, o Bluetooth ou o controle no cabo acordarem o PC da suspensão pelo botão central do controle. **Ativar** pede permissão de administrador ao Windows e marca *Permitir que este dispositivo ative o computador* nesses dispositivos. Não acorda o PC desligado ou em hibernação, e alguns PCs cortam a energia do Bluetooth ao suspender. Junto com **Entrar ao conectar um controle**, o PC já acorda no modo console. +**Perfis por jogo** dão a cada jogo da Steam sua própria resolução, HDR, limite de FPS e saída de áudio. Com o jogo rodando, abra o menu da sessão e escolha **Perfil do jogo → Salvar os ajustes atuais para…**: o que a tela de jogo usa naquele momento fica salvo. Da próxima vez que esse jogo abrir durante uma sessão, o Console Mode aplica o perfil e, quando o jogo fecha, a tela volta a ser como era. O jogo é detectado pela Steam, seja ele aberto pelo Big Picture, pelo Playnite ou pelo app Xbox. Os perfis salvos ficam em Ajustes → **Perfis por jogo**, onde dá para apagá-los (na interface Console: Sistema → Ao entrar no modo console). + ## API de controle local Os links `consolemode://` não dão resposta. Ferramentas que precisam de uma — um agente de controle remoto rodando como serviço do Windows, um plugin de Stream Deck que mostra se o modo console está ligado — podem usar o named pipe `\\.\pipe\ConsoleMode.Control` com o app aberto: envie uma linha JSON e receba outra. diff --git a/docs/GUIDE.ru-RU.md b/docs/GUIDE.ru-RU.md index dd16d87..b618639 100644 --- a/docs/GUIDE.ru-RU.md +++ b/docs/GUIDE.ru-RU.md @@ -31,6 +31,8 @@ Параметр **«Пробуждать ПК геймпадом»** разрешает беспроводному адаптеру Xbox, Bluetooth или проводному геймпаду выводить ПК из спящего режима центральной кнопкой геймпада. Кнопка **«Включить»** запрашивает у Windows права администратора и отмечает у этих устройств *Разрешить этому устройству выводить компьютер из ждущего режима*. Выключенный ПК или ПК в режиме гибернации не проснётся, а некоторые ПК отключают питание Bluetooth во сне. Вместе с **«Входить при подключении геймпада»** ПК сразу проснётся в режиме консоли. +**Профили для игр** задают каждой игре Steam собственные разрешение, HDR, ограничение FPS и аудиовыход. Во время игры откройте меню сеанса и выберите **«Профиль игры» → «Сохранить текущие настройки для…»**: сохранится то, что игровой экран использует в этот момент. Когда эта игра в следующий раз запустится во время сеанса, Console Mode применит профиль, а после её закрытия экран вернётся в прежнее состояние. Игра определяется через Steam, независимо от того, запущена ли она из Big Picture, Playnite или приложения Xbox. Сохранённые профили перечислены в разделе «Параметры» → **«Профили для игр»**, где их можно удалить (в консольном интерфейсе: «Система» → «При входе в режим консоли»). + ## Локальный API управления Ссылки `consolemode://` срабатывают без ответа. Инструменты, которым нужен ответ (агент удалённого управления, работающий как служба Windows, плагин Stream Deck, показывающий, включён ли режим консоли), могут использовать именованный канал `\\.\pipe\ConsoleMode.Control`, пока приложение запущено: отправьте одну строку JSON и получите одну в ответ. diff --git a/docs/TESTING.md b/docs/TESTING.md index ba49cde..dc7814f 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -130,6 +130,19 @@ Pré-condições: PC com adaptador sem fio Xbox, Bluetooth ou controle no cabo; - [ ] Suspender o PC (Iniciar → Energia → Suspender) e apertar o botão Xbox/PS: o PC acorda. Anote a conexão (adaptador Xbox, Bluetooth, cabo) e o modelo do controle. Resultado: ______ - [ ] Com **Entrar ao conectar um controle** ligado e o app na bandeja: acordar pelo controle já entra no modo console. Resultado: ______ - [ ] Teclado e mouse não aparecem na lista e não são alterados. Resultado: ______ +## 1b3. Perfis por jogo (issue #69) + +Pré-condições: dois jogos da Steam instalados (de preferência um que aceite outra resolução sem reiniciar); RTSS instalado para o limite de FPS; sessão ativa. + +- [ ] Sem jogo rodando, o menu da sessão **não** mostra a linha "Perfil do jogo". Com um jogo aberto (pelo Big Picture), em até ~5 s a linha aparece com ": sem perfil". Resultado: ______ +- [ ] No menu, trocar resolução, HDR, FPS e saída de áudio; depois **Perfil do jogo → Salvar os ajustes atuais**: a linha passa a ": perfil salvo" e Ajustes → **Perfis por jogo** lista o jogo com o resumo certo. Resultado: ______ +- [ ] Fechar o jogo: a resolução, o HDR, o FPS e o áudio voltam ao que eram quando o jogo abriu. O log mostra `Perfil por jogo: … fechou; voltando a tela de antes`. Resultado: ______ +- [ ] Abrir o mesmo jogo de novo: o perfil é aplicado sozinho (log `aplicando o perfil de …`) e desfeito ao fechar. Resultado: ______ +- [ ] Abrir **outro** jogo sem perfil: nada muda. Trocar direto de um jogo com perfil para outro: o primeiro é desfeito antes. Resultado: ______ +- [ ] Jogo aberto pelo **Playnite** ou pelo **app Xbox** (jogo da Steam): o perfil também vale. Resultado: ______ +- [ ] **Voltar ao PC** com o jogo ainda aberto e perfil aplicado: a mesa volta exatamente como antes da sessão (resolução, HDR, FPS, áudio). Resultado: ______ +- [ ] A saída de áudio do perfil desconectada (fone desligado): o resto do perfil é aplicado e o log diz que a saída não está ativa. Resultado: ______ +- [ ] Apagar: pelo menu da sessão (Perfil do jogo → Apagar), em Ajustes (botão **Apagar**) e na aba Sistema → Ao entrar no modo console → Perfis por jogo. Sem perfis, a linha da aba Sistema fica desativada. Resultado: ______ ## 1c. Menu da sessão (atalho sugerido: Select + Y) diff --git a/src/ConsoleMode/Models/Models.cs b/src/ConsoleMode/Models/Models.cs index 0a93825..5e4f18e 100644 --- a/src/ConsoleMode/Models/Models.cs +++ b/src/ConsoleMode/Models/Models.cs @@ -102,6 +102,9 @@ 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(); + /// Settings applied while a given Steam game runs during a session (issue #69). + public List GameProfiles { 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. @@ -147,6 +150,31 @@ public sealed class TvControlConfig public bool IsEnabled => !string.IsNullOrWhiteSpace(Provider) && Provider != None; } +/// +/// One game's own settings, saved from the session menu while it runs. Every field left empty keeps +/// the session's value. Applied when the game starts, undone when it closes. +/// +public sealed class GameProfile +{ + public int SteamAppId { get; set; } + public string Name { get; set; } = ""; + public SavedDisplayMode? Mode { get; set; } + public bool? Hdr { get; set; } + /// 0 = no limit; null = leave the session's. + public int? FpsLimit { get; set; } + public string? AudioDeviceId { get; set; } + public string? AudioDeviceName { get; set; } +} + +/// What the game screen looked like when a game started, to go back to when it closes. +public sealed class GameBaseline +{ + public SavedDisplayMode? Mode { get; set; } + public bool Hdr { get; set; } + public int FpsLimit { get; set; } + public string? AudioDeviceId { get; set; } +} + public sealed class SavedDisplayMode { public int Width { get; set; } @@ -368,6 +396,13 @@ public sealed class ConsoleRuntimeState public string? BackupAudioId { get; set; } /// The desktop icons read before the session; null when they aren't restored. public List? DesktopIcons { get; set; } + /// Per-game profiles for this session; the session menu updates them as they are saved. + public List GameProfiles { get; set; } = []; + /// The Steam game running now (0 = none), and the screen as it was when it started. + public int RunningGameId { get; set; } + public GameBaseline? GameBaseline { get; set; } + /// A profile changed the screen for the running game; it is undone when the game closes. + public bool GameProfileApplied { get; set; } } public sealed class RtssBackup diff --git a/src/ConsoleMode/Resources/Strings.de-DE.json b/src/ConsoleMode/Resources/Strings.de-DE.json index 5d6241b..22686a5 100644 --- a/src/ConsoleMode/Resources/Strings.de-DE.json +++ b/src/ConsoleMode/Resources/Strings.de-DE.json @@ -135,6 +135,21 @@ "CloseSteamDescription": "Wenn du Big Picture verlässt, erhält Steam eine normale Aufforderung zum Schließen des Fensters und kann so in den Infobereich wechseln, ohne den Prozess zu beenden. Wenn ein Spiel läuft oder sein Status nicht ermittelt werden kann, bleibt das Fenster unverändert.", "RestoreIconsCard": "Desktopsymbole wieder an ihren Platz setzen", "RestoreIconsDescription": "Speichert vor der Sitzung, wo die Desktopsymbole liegen, und setzt sie bei der Rückkehr zum PC wieder dorthin, falls Windows sie beim Wechsel des Hauptbildschirms durcheinanderbringt. Bei aktivierter automatischer Anordnung passiert nichts.", + "GameProfilesCard": "Profile pro Spiel", + "GameProfilesDescription": "Eigene Auflösung, HDR, FPS-Limit und Audioausgabe für jedes Steam-Spiel. Zum Anlegen öffnest du das Sitzungsmenü, während das Spiel läuft, und wählst Spielprofil → Aktuelle Einstellungen speichern. Das Profil gilt, wenn das Spiel startet, und wird beim Schließen rückgängig gemacht.", + "GameProfilesEmpty": "Keine gespeicherten Profile", + "GameProfilesCount": "{0} gespeichert", + "GameProfilesPickerTitle": "Wähle das Profil zum Löschen", + "GameProfileRow": "Spielprofil", + "GameProfileNoGame": "Kein Steam-Spiel läuft", + "GameProfileNone": "{0}: kein Profil", + "GameProfileActive": "{0}: Profil gespeichert", + "GameProfileSave": "Aktuelle Einstellungen für {0} speichern", + "GameProfileRemove": "Profil von {0} löschen", + "GameProfileDelete": "Löschen", + "GameProfileHdrOn": "HDR an", + "GameProfileHdrOff": "HDR aus", + "GameProfileNothing": "Ändert nichts", "HideCursorCard": "Mauszeiger ausblenden", "HideCursorDescription": "Bleibt ausgeblendet, bis du diese Option deaktivierst oder zum PC zurückkehrst. Praktisch für Emulatoren und Spiele, bei denen der Zeiger mitten auf dem Bildschirm stehen bleibt.", "ControllerMouseRow": "Maus mit dem Controller steuern", diff --git a/src/ConsoleMode/Resources/Strings.en-US.json b/src/ConsoleMode/Resources/Strings.en-US.json index 3838759..53044f8 100644 --- a/src/ConsoleMode/Resources/Strings.en-US.json +++ b/src/ConsoleMode/Resources/Strings.en-US.json @@ -135,6 +135,21 @@ "CloseSteamDescription": "When you leave Big Picture, Steam receives a normal window-close request so it can move to the tray without exiting the process. If a game is running or its state cannot be checked, the window is left unchanged.", "RestoreIconsCard": "Put desktop icons back in place", "RestoreIconsDescription": "Saves where the desktop icons are before the session and puts them back when you return to the PC, in case Windows reshuffles them while the main display changes. Does nothing when auto arrange is on.", + "GameProfilesCard": "Per-game profiles", + "GameProfilesDescription": "Each Steam game's own resolution, HDR, FPS limit and audio output. To create one, open the session menu while the game runs and pick Game profile → Save the current settings. The profile applies when the game starts and is undone when it closes.", + "GameProfilesEmpty": "No saved profiles", + "GameProfilesCount": "{0} saved", + "GameProfilesPickerTitle": "Pick the profile to delete", + "GameProfileRow": "Game profile", + "GameProfileNoGame": "No Steam game running", + "GameProfileNone": "{0}: no profile", + "GameProfileActive": "{0}: profile saved", + "GameProfileSave": "Save the current settings for {0}", + "GameProfileRemove": "Delete the profile of {0}", + "GameProfileDelete": "Delete", + "GameProfileHdrOn": "HDR on", + "GameProfileHdrOff": "HDR off", + "GameProfileNothing": "Changes nothing", "HideCursorCard": "Hide the mouse pointer", "HideCursorDescription": "Stays hidden until you turn this off or go back to the PC. Handy for emulators and games that leave it in the middle of the screen.", "ControllerMouseRow": "Control the mouse with the controller", diff --git a/src/ConsoleMode/Resources/Strings.es-ES.json b/src/ConsoleMode/Resources/Strings.es-ES.json index ddc7f8a..c3b4aee 100644 --- a/src/ConsoleMode/Resources/Strings.es-ES.json +++ b/src/ConsoleMode/Resources/Strings.es-ES.json @@ -135,6 +135,21 @@ "CloseSteamDescription": "Al salir de Big Picture, Steam recibe una solicitud normal para cerrar la ventana y pasar a la bandeja sin finalizar el proceso. Si hay un juego en ejecución o no se puede comprobar su estado, la ventana no se modifica.", "RestoreIconsCard": "Devolver los iconos del escritorio a su sitio", "RestoreIconsDescription": "Guarda la posición de los iconos del escritorio antes de la sesión y los vuelve a colocar al volver al PC, por si Windows los reordena al cambiar la pantalla principal. No hace nada si la organización automática está activada.", + "GameProfilesCard": "Perfiles por juego", + "GameProfilesDescription": "Resolución, HDR, límite de FPS y salida de audio propios de cada juego de Steam. Para crear uno, abre el menú de la sesión con el juego en marcha y elige Perfil del juego → Guardar los ajustes actuales. El perfil se aplica cuando el juego se abre y se deshace cuando se cierra.", + "GameProfilesEmpty": "Ningún perfil guardado", + "GameProfilesCount": "{0} guardados", + "GameProfilesPickerTitle": "Elige el perfil que quieres borrar", + "GameProfileRow": "Perfil del juego", + "GameProfileNoGame": "Ningún juego de Steam en marcha", + "GameProfileNone": "{0}: sin perfil", + "GameProfileActive": "{0}: perfil guardado", + "GameProfileSave": "Guardar los ajustes actuales para {0}", + "GameProfileRemove": "Borrar el perfil de {0}", + "GameProfileDelete": "Borrar", + "GameProfileHdrOn": "HDR activado", + "GameProfileHdrOff": "HDR desactivado", + "GameProfileNothing": "No cambia nada", "HideCursorCard": "Ocultar el cursor del ratón", "HideCursorDescription": "Queda oculto hasta que lo desactives aquí o vuelvas al PC. Útil en emuladores y juegos que lo dejan en el centro de la pantalla.", "ControllerMouseRow": "Controlar el ratón con el mando", diff --git a/src/ConsoleMode/Resources/Strings.fr-FR.json b/src/ConsoleMode/Resources/Strings.fr-FR.json index cf6fb61..ba2283a 100644 --- a/src/ConsoleMode/Resources/Strings.fr-FR.json +++ b/src/ConsoleMode/Resources/Strings.fr-FR.json @@ -135,6 +135,21 @@ "CloseSteamDescription": "Quand vous quittez Big Picture, Steam reçoit une demande normale de fermeture de fenêtre pour qu'il passe dans la zone de notification sans quitter le processus. Si un jeu est en cours ou si son état ne peut pas être vérifié, la fenêtre n'est pas modifiée.", "RestoreIconsCard": "Remettre les icônes du bureau à leur place", "RestoreIconsDescription": "Enregistre la position des icônes du bureau avant la session et les remet en place au retour au PC, au cas où Windows les mélange en changeant d'écran principal. Sans effet si la réorganisation automatique est activée.", + "GameProfilesCard": "Profils par jeu", + "GameProfilesDescription": "Résolution, HDR, limite de FPS et sortie audio propres à chaque jeu Steam. Pour en créer un, ouvrez le menu de la session pendant que le jeu tourne et choisissez Profil du jeu → Enregistrer les réglages actuels. Le profil s'applique quand le jeu démarre et est annulé quand il se ferme.", + "GameProfilesEmpty": "Aucun profil enregistré", + "GameProfilesCount": "{0} enregistrés", + "GameProfilesPickerTitle": "Choisissez le profil à supprimer", + "GameProfileRow": "Profil du jeu", + "GameProfileNoGame": "Aucun jeu Steam en cours", + "GameProfileNone": "{0} : pas de profil", + "GameProfileActive": "{0} : profil enregistré", + "GameProfileSave": "Enregistrer les réglages actuels pour {0}", + "GameProfileRemove": "Supprimer le profil de {0}", + "GameProfileDelete": "Supprimer", + "GameProfileHdrOn": "HDR activé", + "GameProfileHdrOff": "HDR désactivé", + "GameProfileNothing": "Ne change rien", "HideCursorCard": "Masquer le pointeur de la souris", "HideCursorDescription": "Reste masqué jusqu'à ce que vous désactiviez cette option ou reveniez au PC. Pratique pour les émulateurs et les jeux qui le laissent au milieu de l'écran.", "ControllerMouseRow": "Contrôler la souris avec la manette", diff --git a/src/ConsoleMode/Resources/Strings.pt-BR.json b/src/ConsoleMode/Resources/Strings.pt-BR.json index a45891a..4c84e5b 100644 --- a/src/ConsoleMode/Resources/Strings.pt-BR.json +++ b/src/ConsoleMode/Resources/Strings.pt-BR.json @@ -135,6 +135,21 @@ "CloseSteamDescription": "Ao sair do Big Picture, envia o fechamento normal da janela da Steam para ela ir à bandeja, sem encerrar o processo. Se houver um jogo em execução ou não for possível verificar, a janela não é alterada.", "RestoreIconsCard": "Devolver os ícones da área de trabalho ao lugar", "RestoreIconsDescription": "Salva a posição dos ícones antes da sessão e os coloca de volta ao voltar ao PC, caso o Windows os embaralhe ao trocar a tela principal. Não faz nada quando a organização automática dos ícones está ligada.", + "GameProfilesCard": "Perfis por jogo", + "GameProfilesDescription": "Resolução, HDR, limite de FPS e saída de áudio próprios de cada jogo da Steam. Para criar, abra o menu da sessão com o jogo rodando e escolha Perfil do jogo → Salvar os ajustes atuais. O perfil vale quando o jogo abre e é desfeito quando ele fecha.", + "GameProfilesEmpty": "Nenhum perfil salvo", + "GameProfilesCount": "{0} salvos", + "GameProfilesPickerTitle": "Escolha o perfil a apagar", + "GameProfileRow": "Perfil do jogo", + "GameProfileNoGame": "Nenhum jogo da Steam rodando", + "GameProfileNone": "{0}: sem perfil", + "GameProfileActive": "{0}: perfil salvo", + "GameProfileSave": "Salvar os ajustes atuais para {0}", + "GameProfileRemove": "Apagar o perfil de {0}", + "GameProfileDelete": "Apagar", + "GameProfileHdrOn": "HDR ligado", + "GameProfileHdrOff": "HDR desligado", + "GameProfileNothing": "Não muda nada", "HideCursorCard": "Ocultar o cursor do mouse", "HideCursorDescription": "Fica oculto até você desligar aqui ou voltar ao PC. Útil em emuladores e jogos que deixam o cursor no meio da tela.", "ControllerMouseRow": "Controlar o mouse com o controle", diff --git a/src/ConsoleMode/Resources/Strings.ru-RU.json b/src/ConsoleMode/Resources/Strings.ru-RU.json index 6a602b0..0d42ea1 100644 --- a/src/ConsoleMode/Resources/Strings.ru-RU.json +++ b/src/ConsoleMode/Resources/Strings.ru-RU.json @@ -135,6 +135,21 @@ "CloseSteamDescription": "Когда вы выходите из Big Picture, Steam получает обычный запрос на закрытие окна и может свернуться в область уведомлений, не завершая процесс. Если запущена игра или её состояние не удаётся проверить, окно не трогается.", "RestoreIconsCard": "Возвращать значки рабочего стола на место", "RestoreIconsDescription": "Запоминает расположение значков рабочего стола перед сеансом и возвращает их при возврате к ПК, если Windows перемешает их при смене основного экрана. Ничего не делает, если включено автоматическое упорядочивание.", + "GameProfilesCard": "Профили для игр", + "GameProfilesDescription": "Собственные разрешение, HDR, ограничение FPS и аудиовыход для каждой игры Steam. Чтобы создать профиль, откройте меню сеанса во время игры и выберите «Профиль игры» → «Сохранить текущие настройки». Профиль применяется при запуске игры и отменяется при её закрытии.", + "GameProfilesEmpty": "Нет сохранённых профилей", + "GameProfilesCount": "Сохранено: {0}", + "GameProfilesPickerTitle": "Выберите профиль для удаления", + "GameProfileRow": "Профиль игры", + "GameProfileNoGame": "Игра Steam не запущена", + "GameProfileNone": "{0}: без профиля", + "GameProfileActive": "{0}: профиль сохранён", + "GameProfileSave": "Сохранить текущие настройки для {0}", + "GameProfileRemove": "Удалить профиль {0}", + "GameProfileDelete": "Удалить", + "GameProfileHdrOn": "HDR вкл.", + "GameProfileHdrOff": "HDR выкл.", + "GameProfileNothing": "Ничего не меняет", "HideCursorCard": "Скрыть указатель мыши", "HideCursorDescription": "Остаётся скрытым, пока вы не выключите этот параметр или не вернётесь к ПК. Удобно для эмуляторов и игр, которые оставляют его посреди экрана.", "ControllerMouseRow": "Управлять мышью с геймпада", diff --git a/src/ConsoleMode/Services/ConsoleEngine.GameProfiles.cs b/src/ConsoleMode/Services/ConsoleEngine.GameProfiles.cs new file mode 100644 index 0000000..55a5986 --- /dev/null +++ b/src/ConsoleMode/Services/ConsoleEngine.GameProfiles.cs @@ -0,0 +1,119 @@ +using ConsoleMode.Models; +using ConsoleMode.Native; + +namespace ConsoleMode.Services; + +// Per-game profiles (issue #69): while a session runs, Steam's running game is read on every Tick. +// When a game with a profile starts, its resolution, HDR, FPS limit and audio output are applied; +// when it closes (or another game starts), the screen goes back to how it was when it started. +public sealed partial class ConsoleEngine +{ + private void ResetGameProfileState() + { + State.RunningGameId = 0; + State.GameBaseline = null; + State.GameProfileApplied = false; + } + + private void TickGameProfile() + { + if (string.IsNullOrWhiteSpace(State.FocusMonitor) || State.RestoreInProgress) return; + var previous = State.RunningGameId; + var current = SteamSession.RunningAppId(); + var change = GameProfiles.Change(previous, current); + if (change == GameChange.None) return; + + if (change is GameChange.Ended or GameChange.Switched) EndGame(previous); + State.RunningGameId = current ?? 0; + if (change is GameChange.Started or GameChange.Switched) BeginGame(State.RunningGameId); + } + + private void BeginGame(int appId) + { + State.GameBaseline = ReadGameBaseline(); + State.GameProfileApplied = false; + if (GameProfiles.Find(State.GameProfiles, appId) is not { } profile || GameProfiles.IsEmpty(profile)) + { + AppLog.Write($"Perfil por jogo: {appId} começou, sem perfil"); + return; + } + AppLog.Write($"Perfil por jogo: aplicando o perfil de {profile.Name} ({appId})"); + Apply(profile.Mode, profile.Hdr, profile.FpsLimit, profile.AudioDeviceId); + State.GameProfileApplied = true; + } + + private void EndGame(int appId) + { + if (State.GameProfileApplied && State.GameBaseline is { } baseline) + { + AppLog.Write($"Perfil por jogo: {appId} fechou; voltando a tela de antes"); + Apply(baseline.Mode, baseline.Hdr, baseline.FpsLimit, baseline.AudioDeviceId); + } + State.GameBaseline = null; + State.GameProfileApplied = false; + } + + /// + /// The session menu saved a profile for the game running now: closing it goes back to how the + /// screen was when it started, as if the profile had been applied then. + /// + public void OnGameProfileSaved(List profiles) + { + State.GameProfiles = [.. profiles]; + if (State.RunningGameId > 0 && GameProfiles.Find(profiles, State.RunningGameId) is not null) + State.GameProfileApplied = true; + } + + /// The settings in effect now on the game screen. + public GameBaseline ReadGameBaseline() + { + var focus = State.FocusMonitor ?? ""; + var mode = NativeWindows.GetCurrentDisplayMode(focus); + return new GameBaseline + { + Mode = mode is null ? null : new SavedDisplayMode { Width = mode.Width, Height = mode.Height, Frequency = mode.Frequency }, + Hdr = Video.IsHdrOn(focus), + FpsLimit = State.FpsLimit, + AudioDeviceId = string.IsNullOrWhiteSpace(State.AudioDeviceId) ? Audio.GetDefaultId() : State.AudioDeviceId + }; + } + + /// Each part on its own: one that fails is logged and the others still apply. + private void Apply(SavedDisplayMode? mode, bool? hdr, int? fpsLimit, string? audioId) + { + var focus = State.FocusMonitor!; + if (mode is { Width: > 0, Height: > 0 }) + { + var current = NativeWindows.GetCurrentDisplayMode(focus); + if (current is null || current.Width != mode.Width || current.Height != mode.Height || current.Frequency != mode.Frequency) + Try("resolução", () => + { + Monitors.ApplyFocusMode(focus, mode); + Monitors.UpdateFocusRect(focus, State, true); + }); + } + if (hdr is { } on && Video.IsHdrOn(focus) != on) + Try("HDR", () => { if (!Video.SetHdrFromMenu(focus, on, State)) throw new InvalidOperationException(focus); }); + if (fpsLimit is { } fps && fps != State.FpsLimit && Rtss.IsReady) + Try("FPS", () => + { + var result = Rtss.SetLimit(fps, State); + if (!result.Success) throw new InvalidOperationException(result.Message); + }); + if (!string.IsNullOrWhiteSpace(audioId) && audioId != (State.AudioDeviceId ?? Audio.GetDefaultId())) + Try("áudio", () => + { + if (Audio.GetDevices(true).FirstOrDefault(d => d.FriendlyId == audioId) is not { IsActive: true }) + throw new InvalidOperationException($"saída {audioId} não está ativa"); + Audio.SetOutput(audioId); + State.AudioDeviceId = audioId; + State.AudioWatchComplete = true; // the auto-switch must not undo it + }); + } + + private static void Try(string what, Action action) + { + try { action(); } + catch (Exception ex) { AppLog.Write($"Perfil por jogo: {what}: {ex.Message}"); } + } +} diff --git a/src/ConsoleMode/Services/ConsoleEngine.cs b/src/ConsoleMode/Services/ConsoleEngine.cs index 8da6ab5..44bd4e2 100644 --- a/src/ConsoleMode/Services/ConsoleEngine.cs +++ b/src/ConsoleMode/Services/ConsoleEngine.cs @@ -4,7 +4,7 @@ namespace ConsoleMode.Services; -public sealed class ConsoleEngine +public sealed partial class ConsoleEngine { public ConsoleRuntimeState State { get; } = new(); public MonitorService Monitors { get; } = new(); @@ -71,6 +71,8 @@ public void Start(AppConfig config, MonitorInfo? focusInfo, Func +/// Pure rules for the per-game profiles (issue #69): noticing when a Steam game starts or closes, +/// keeping the list, finding a game's name, and the one-line summary the settings show. +/// +public static partial class GameProfiles +{ + /// What happened between two reads of Steam's running game. An unknown read (null) changes nothing. + public static GameChange Change(int previous, int? current) + { + if (current is not { } now || now == previous) return GameChange.None; + if (previous == 0) return GameChange.Started; + return now == 0 ? GameChange.Ended : GameChange.Switched; + } + + public static GameProfile? Find(IEnumerable? profiles, int appId) => + appId <= 0 || profiles is null ? null : profiles.FirstOrDefault(p => p.SteamAppId == appId); + + /// The list with this game's profile added or replaced, sorted by name. + public static List Upsert(IEnumerable? profiles, GameProfile profile) => + [.. (profiles ?? []).Where(p => p.SteamAppId != profile.SteamAppId).Append(profile) + .OrderBy(p => p.Name, StringComparer.CurrentCultureIgnoreCase)]; + + public static List Remove(IEnumerable? profiles, int appId) => + [.. (profiles ?? []).Where(p => p.SteamAppId != appId)]; + + /// Whether a profile would change anything at all. + public static bool IsEmpty(GameProfile profile) => + profile.Mode is null && profile.Hdr is null && profile.FpsLimit is null && string.IsNullOrWhiteSpace(profile.AudioDeviceId); + + [GeneratedRegex("\"name\"\\s+\"(?(?:[^\"\\\\]|\\\\.)*)\"", RegexOptions.IgnoreCase)] + private static partial Regex NameLine(); + + [GeneratedRegex("\"path\"\\s+\"(?(?:[^\"\\\\]|\\\\.)*)\"", RegexOptions.IgnoreCase)] + private static partial Regex PathLine(); + + /// The game's name from its steamapps/appmanifest_ID.acf, or null. + public static string? ParseManifestName(string? acf) + { + if (string.IsNullOrWhiteSpace(acf)) return null; + var match = NameLine().Match(acf); + var name = match.Success ? Unescape(match.Groups["v"].Value).Trim() : ""; + return name.Length > 0 ? name : null; + } + + /// Every Steam library folder listed in libraryfolders.vdf. + public static List ParseLibraryPaths(string? vdf) + { + if (string.IsNullOrWhiteSpace(vdf)) return []; + return [.. PathLine().Matches(vdf).Select(m => Unescape(m.Groups["v"].Value)).Where(p => p.Length > 0) + .Distinct(StringComparer.OrdinalIgnoreCase)]; + } + + /// "3840 × 2160 @ 120 Hz · HDR on · 60 FPS · LG TV": only what the profile changes. + public static string Summary(GameProfile profile, string hdrOn, string hdrOff, string noLimit, string nothing) + { + var parts = new List(); + if (profile.Mode is { Width: > 0, Height: > 0 } mode) + parts.Add(mode.Frequency > 0 ? $"{mode.Width} × {mode.Height} @ {mode.Frequency} Hz" : $"{mode.Width} × {mode.Height}"); + if (profile.Hdr is { } hdr) parts.Add(hdr ? hdrOn : hdrOff); + if (profile.FpsLimit is { } fps) parts.Add(fps > 0 ? $"{fps} FPS" : noLimit); + if (!string.IsNullOrWhiteSpace(profile.AudioDeviceName)) parts.Add(profile.AudioDeviceName!); + return parts.Count == 0 ? nothing : string.Join(" · ", parts); + } + + private static string Unescape(string value) => value.Replace("\\\\", "\\").Replace("\\\"", "\""); +} diff --git a/src/ConsoleMode/Services/LocalizationService.cs b/src/ConsoleMode/Services/LocalizationService.cs index 0ed2f18..3dc542f 100644 --- a/src/ConsoleMode/Services/LocalizationService.cs +++ b/src/ConsoleMode/Services/LocalizationService.cs @@ -259,6 +259,9 @@ internal void NotifyAll() public string CloseSteamDescription => LocalizationService.Get(nameof(CloseSteamDescription)); public string RestoreIconsCard => LocalizationService.Get(nameof(RestoreIconsCard)); public string RestoreIconsDescription => LocalizationService.Get(nameof(RestoreIconsDescription)); + public string GameProfilesCard => LocalizationService.Get(nameof(GameProfilesCard)); + public string GameProfilesDescription => LocalizationService.Get(nameof(GameProfilesDescription)); + public string GameProfileRow => LocalizationService.Get(nameof(GameProfileRow)); public string HideCursorCard => LocalizationService.Get(nameof(HideCursorCard)); public string HideCursorDescription => LocalizationService.Get(nameof(HideCursorDescription)); public string ControllerMouseRow => LocalizationService.Get(nameof(ControllerMouseRow)); diff --git a/src/ConsoleMode/Services/SteamSession.cs b/src/ConsoleMode/Services/SteamSession.cs index 3d2d4ad..ffd893a 100644 --- a/src/ConsoleMode/Services/SteamSession.cs +++ b/src/ConsoleMode/Services/SteamSession.cs @@ -32,6 +32,33 @@ public static bool IsRunning() } } + /// + /// A game's name: Steam keeps it in the registry for most games, and always in the + /// appmanifest of the library it is installed in. Falls back to "Steam app ID". + /// + public static string GameName(int appId) + { + try + { + using var key = Registry.CurrentUser.OpenSubKey($@"{SteamKey}\Apps\{appId}"); + if (key?.GetValue("Name") is string name && !string.IsNullOrWhiteSpace(name)) return name.Trim(); + + var steam = Path.GetDirectoryName(FindSteamExe() ?? ""); + if (!string.IsNullOrWhiteSpace(steam)) + { + var vdf = Path.Combine(steam, "steamapps", "libraryfolders.vdf"); + var libraries = File.Exists(vdf) ? GameProfiles.ParseLibraryPaths(File.ReadAllText(vdf)) : []; + foreach (var library in libraries.Prepend(steam)) + { + var manifest = Path.Combine(library, "steamapps", $"appmanifest_{appId}.acf"); + if (File.Exists(manifest) && GameProfiles.ParseManifestName(File.ReadAllText(manifest)) is { } found) return found; + } + } + } + catch (Exception ex) { AppLog.Write($"Steam: nome do jogo {appId}: {ex.Message}"); } + return $"Steam app {appId}"; + } + public static string? FindSteamExe() { try diff --git a/src/ConsoleMode/SessionMenuWindow.xaml b/src/ConsoleMode/SessionMenuWindow.xaml index 653939a..01f9b0e 100644 --- a/src/ConsoleMode/SessionMenuWindow.xaml +++ b/src/ConsoleMode/SessionMenuWindow.xaml @@ -280,6 +280,19 @@ + + + +