From da60d884152b2248a602ee2ecf444c95fe4ad619 Mon Sep 17 00:00:00 2001 From: Filipe Moreira Date: Wed, 21 Oct 2026 10:44:23 -0300 Subject: [PATCH 1/3] feat: let the controller wake the PC from sleep Settings gets a "Wake the PC with the controller" card (and a row in the console System tab) that lists the controller's adapters that can wake the PC (Xbox Wireless Adapter, Bluetooth radio, wired controllers), told apart by instance id through WMI MSPower_DeviceWakeEnable, and turns "Allow this device to wake the computer" on for them through an elevated PowerShell after the UAC prompt. Keyboards, mice and network cards are left alone. Closes #155 Co-Authored-By: Claude Opus 5.5 --- docs/GUIDE.de-DE.md | 2 + docs/GUIDE.es-ES.md | 2 + docs/GUIDE.fr-FR.md | 2 + docs/GUIDE.md | 2 + docs/GUIDE.pt-BR.md | 2 + docs/GUIDE.ru-RU.md | 2 + docs/TESTING.md | 11 ++ src/ConsoleMode/Resources/Strings.de-DE.json | 12 ++ src/ConsoleMode/Resources/Strings.en-US.json | 12 ++ src/ConsoleMode/Resources/Strings.es-ES.json | 12 ++ src/ConsoleMode/Resources/Strings.fr-FR.json | 12 ++ src/ConsoleMode/Resources/Strings.pt-BR.json | 12 ++ src/ConsoleMode/Resources/Strings.ru-RU.json | 12 ++ src/ConsoleMode/Services/ControllerWake.cs | 113 ++++++++++++++++++ .../Services/ControllerWakeService.cs | 68 +++++++++++ .../Services/LocalizationService.cs | 3 + .../ViewModels/MainViewModel.ConsoleUi.cs | 1 + .../MainViewModel.ControllerWake.cs | 87 ++++++++++++++ src/ConsoleMode/ViewModels/MainViewModel.cs | 2 + src/ConsoleMode/Views/ConsoleHomeView.xaml | 7 ++ src/ConsoleMode/Views/SettingsView.xaml | 13 ++ .../ConsoleMode.Tests.csproj | 1 + .../ConsoleMode.Tests/ControllerWakeTests.cs | 72 +++++++++++ 23 files changed, 462 insertions(+) create mode 100644 src/ConsoleMode/Services/ControllerWake.cs create mode 100644 src/ConsoleMode/Services/ControllerWakeService.cs create mode 100644 src/ConsoleMode/ViewModels/MainViewModel.ControllerWake.cs create mode 100644 tests/ConsoleMode.Tests/ControllerWakeTests.cs diff --git a/docs/GUIDE.de-DE.md b/docs/GUIDE.de-DE.md index 3a55462..a83a73a 100644 --- a/docs/GUIDE.de-DE.md +++ b/docs/GUIDE.de-DE.md @@ -27,6 +27,8 @@ Die Registerkarte **System** bietet dieselben Einstellungen wie der Desktopmodus Bei der Rückkehr aus Big Picture schließt **Steam beim Zurückkehren zum PC in den Infobereich minimieren** das Client-Fenster, während Steam weiterläuft. Ist die Option aus, bleibt der Desktop-Client geöffnet. Steam-Fenster werden nicht angetastet, wenn ein Spiel läuft oder sich sein Zustand nicht prüfen lässt. +**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. + ## 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 43cced6..c4b1fc7 100644 --- a/docs/GUIDE.es-ES.md +++ b/docs/GUIDE.es-ES.md @@ -27,6 +27,8 @@ Abre la acción del atajo que quieras configurar, elige **Definir** o **Cambiar* Al volver de Big Picture, **Enviar Steam a la bandeja al volver al PC** cierra la ventana del cliente y deja Steam en marcha. Con la opción desactivada, el cliente de escritorio se queda abierto. Las ventanas de Steam no se tocan si hay un juego en marcha o si no se puede comprobar su estado. +**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. + ## 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 5060ac1..592598d 100644 --- a/docs/GUIDE.fr-FR.md +++ b/docs/GUIDE.fr-FR.md @@ -27,6 +27,8 @@ Ouvrez l'action de raccourci à configurer, choisissez **Définir** ou **Modifie Au retour de Big Picture, **Réduire Steam dans la zone de notification au retour au PC** ferme la fenêtre du client tout en laissant Steam en marche. Si l'option est désactivée, le client de bureau reste ouvert. Les fenêtres de Steam ne sont pas touchées quand un jeu est en cours ou quand son état ne peut pas être vérifié. +**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. + ## 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 f493c78..e908c5e 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -33,6 +33,8 @@ Open the shortcut action you want to configure, choose **Set** or **Change**, ho When returning from Big Picture, **Send Steam to the tray when going back to the PC** closes the client window while keeping Steam running. With the option off, the desktop client is left open. Steam windows are left alone when a game is running or its state cannot be checked. +**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. + ## 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 8a9ce9e..6df1753 100644 --- a/docs/GUIDE.pt-BR.md +++ b/docs/GUIDE.pt-BR.md @@ -33,6 +33,8 @@ Abra a ação de atalho que deseja configurar, escolha **Definir** ou **Alterar* Ao voltar do Big Picture, **Mandar a Steam para a bandeja ao voltar ao PC** fecha a janela do cliente e mantém a Steam em execução. Com a opção desligada, o cliente desktop fica aberto. As janelas da Steam são preservadas quando há jogo rodando ou não é possível verificar esse estado. +**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. + ## 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 9457df8..c23b42b 100644 --- a/docs/GUIDE.ru-RU.md +++ b/docs/GUIDE.ru-RU.md @@ -27,6 +27,8 @@ При возврате из Big Picture параметр **«Сворачивать Steam в область уведомлений при возврате к ПК»** закрывает окно клиента, но Steam продолжает работать. Если параметр выключен, клиент на рабочем столе остаётся открытым. Окна Steam не трогаются, если запущена игра или её состояние не удаётся проверить. +Параметр **«Пробуждать ПК геймпадом»** разрешает беспроводному адаптеру Xbox, Bluetooth или проводному геймпаду выводить ПК из спящего режима центральной кнопкой геймпада. Кнопка **«Включить»** запрашивает у Windows права администратора и отмечает у этих устройств *Разрешить этому устройству выводить компьютер из ждущего режима*. Выключенный ПК или ПК в режиме гибернации не проснётся, а некоторые ПК отключают питание Bluetooth во сне. Вместе с **«Входить при подключении геймпада»** ПК сразу проснётся в режиме консоли. + ## Локальный API управления Ссылки `consolemode://` срабатывают без ответа. Инструменты, которым нужен ответ (агент удалённого управления, работающий как служба Windows, плагин Stream Deck, показывающий, включён ли режим консоли), могут использовать именованный канал `\\.\pipe\ConsoleMode.Control`, пока приложение запущено: отправьте одну строку JSON и получите одну в ответ. diff --git a/docs/TESTING.md b/docs/TESTING.md index 6129468..96ddc08 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -119,6 +119,17 @@ Pré-condições: Ajustes → "Entrar ao conectar um controle" **ligado**; app n - [ ] O log mostra `Controle conectado: ; auto-start sim/não` a cada conexão. Resultado: ______ - [ ] Com a opção **desligada** (padrão), nada disso acontece. Resultado: ______ +## 1b2. Acordar o PC pelo controle (issue #155) + +Pré-condições: PC com adaptador sem fio Xbox, Bluetooth ou controle no cabo; a suspensão (não hibernação) habilitada. + +- [ ] Ajustes → **Acordar o PC pelo controle**: a linha de status lista o adaptador/Bluetooth/controle e diz se já pode acordar o PC. Num PC sem nenhum deles, diz que nenhum dispositivo pode e a aba Sistema do modo Console mostra "Indisponível". Resultado: ______ +- [ ] **Ativar** abre o pedido de administrador (UAC); aceitando, aparece "Pronto…" e o Gerenciador de Dispositivos → (adaptador/rádio Bluetooth) → Gerenciamento de Energia mostra *Permitir que este dispositivo ative o computador* marcado. Resultado: ______ +- [ ] Recusar o UAC: aviso de que nada foi alterado; nenhum dispositivo muda. Resultado: ______ +- [ ] 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: ______ + ## 1c. Menu da sessão (atalho sugerido: Select + Y) ### Tela cheia estilo Steam (Shift+Tab), prévia e janelas diff --git a/src/ConsoleMode/Resources/Strings.de-DE.json b/src/ConsoleMode/Resources/Strings.de-DE.json index 435d76b..e249a25 100644 --- a/src/ConsoleMode/Resources/Strings.de-DE.json +++ b/src/ConsoleMode/Resources/Strings.de-DE.json @@ -139,6 +139,18 @@ "ControllerMouseHint": "Linker Stick bewegt · {0} klickt · {0} zweimal: Rechtsklick · rechter Stick scrollt", "AutoStartControllerCard": "Beim Verbinden eines Controllers starten", "AutoStartControllerDescription": "Wenn die App im Infobereich läuft, startet das Einschalten oder Anschließen eines Controllers den Konsolenmodus. Die ersten 15 Sekunden nach dem Öffnen und 30 Sekunden nach der Wiederherstellung werden ignoriert.", + "ControllerWakeCard": "PC mit dem Controller aufwecken", + "ControllerWakeDescription": "Erlaubt dem Xbox Wireless Adapter, Bluetooth oder einem Controller am Kabel, den PC aus dem Energiesparmodus zu wecken, wenn du die mittlere Taste des Controllers drückst. Windows fragt nach Administratorrechten. Ein ausgeschalteter PC oder einer im Ruhezustand wacht nicht auf, und manche PCs schalten Bluetooth im Energiesparmodus ab. Mit Beim Verbinden eines Controllers starten wacht der PC direkt im Konsolenmodus auf.", + "ControllerWakeButton": "Einschalten", + "ControllerWakeChecking": "Geräte werden geprüft…", + "ControllerWakeReady": "Bereit: {0} kann den PC aufwecken.", + "ControllerWakeOff": "Kann den PC noch nicht aufwecken: {0}.", + "ControllerWakeNone": "Kein Controller-Adapter und kein Bluetooth dieses PCs kann ihn aufwecken. Schließe den Adapter oder den Controller an und versuche es erneut.", + "ControllerWakeUnknown": "Die Geräte konnten nicht geprüft werden.", + "ControllerWakeEnabled": "Fertig. Versetze den PC in den Energiesparmodus und drücke die mittlere Taste des Controllers, um es zu testen.", + "ControllerWakeCanceled": "Windows hat keine Berechtigung erhalten; nichts wurde geändert.", + "ControllerWakeFailed": "Konnte nicht eingeschaltet werden. Details stehen im Protokoll.", + "ControllerWakeUnavailable": "Nicht verfügbar", "HomeButtonShortPressCard": "Kurzer Druck auf die Xbox-Taste", "HomeButtonShortPressDescription": "Einfach drücken, nicht gedrückt halten. Deaktiviert die Controller-Tastenkombination für die Game Bar in Windows (Win+G funktioniert weiterhin).", "HomeButtonSteamHint": "Steam ist geöffnet und verwendet ebenfalls die Xbox-Taste. Deaktiviere in Steam die Option „Guide-Taste fokussiert Steam“, damit der kurze Tastendruck funktioniert.", diff --git a/src/ConsoleMode/Resources/Strings.en-US.json b/src/ConsoleMode/Resources/Strings.en-US.json index 5945df9..cac81a5 100644 --- a/src/ConsoleMode/Resources/Strings.en-US.json +++ b/src/ConsoleMode/Resources/Strings.en-US.json @@ -139,6 +139,18 @@ "ControllerMouseHint": "Left stick moves · {0} clicks · {0} twice: right click · right stick scrolls", "AutoStartControllerCard": "Enter when a controller connects", "AutoStartControllerDescription": "With the app in the tray, turning on or plugging in a controller enters console mode. Ignores the first 15 s after opening and 30 s after restoring.", + "ControllerWakeCard": "Wake the PC with the controller", + "ControllerWakeDescription": "Lets the Xbox Wireless Adapter, Bluetooth or a wired controller wake the PC from sleep when you press the controller's center button. Windows asks for administrator permission. It can't wake a PC that is shut down or hibernating, and some PCs cut power to Bluetooth while asleep. With Enter when a controller connects on, the PC wakes straight into console mode.", + "ControllerWakeButton": "Turn on", + "ControllerWakeChecking": "Checking the devices…", + "ControllerWakeReady": "Ready: {0} can wake the PC.", + "ControllerWakeOff": "Can't wake the PC yet: {0}.", + "ControllerWakeNone": "No controller adapter or Bluetooth on this PC can wake it. Connect the adapter or the controller and try again.", + "ControllerWakeUnknown": "Couldn't check the devices.", + "ControllerWakeEnabled": "Done. Put the PC to sleep and press the controller's center button to try it.", + "ControllerWakeCanceled": "Windows didn't get permission; nothing changed.", + "ControllerWakeFailed": "Couldn't turn it on. The details are in the log.", + "ControllerWakeUnavailable": "Unavailable", "HomeButtonShortPressCard": "Short press of the Xbox button", "HomeButtonShortPressDescription": "Just press it, no holding. Turns off the controller shortcut for Game Bar in Windows (Win+G keeps working).", "HomeButtonSteamHint": "Steam is open and also uses the Xbox button. In Steam, turn off \"Guide button focuses Steam\" for the short press to work.", diff --git a/src/ConsoleMode/Resources/Strings.es-ES.json b/src/ConsoleMode/Resources/Strings.es-ES.json index 6b5da4c..9df495a 100644 --- a/src/ConsoleMode/Resources/Strings.es-ES.json +++ b/src/ConsoleMode/Resources/Strings.es-ES.json @@ -139,6 +139,18 @@ "ControllerMouseHint": "Stick izquierdo mueve · {0} hace clic · {0} dos veces: clic derecho · stick derecho desplaza", "AutoStartControllerCard": "Entrar al conectar un mando", "AutoStartControllerDescription": "Con la aplicación en la bandeja, encender o conectar un mando entra en modo consola. Ignora los primeros 15 s tras abrir y 30 s tras restaurar.", + "ControllerWakeCard": "Despertar el PC con el mando", + "ControllerWakeDescription": "Permite que el adaptador inalámbrico Xbox, el Bluetooth o un mando con cable despierten el PC de la suspensión al pulsar el botón central del mando. Windows pide permiso de administrador. No despierta un PC apagado o en hibernación, y algunos PC cortan la energía del Bluetooth al suspender. Con Entrar al conectar un mando activado, el PC despierta directamente en modo consola.", + "ControllerWakeButton": "Activar", + "ControllerWakeChecking": "Comprobando los dispositivos…", + "ControllerWakeReady": "Listo: {0} puede despertar el PC.", + "ControllerWakeOff": "Todavía no puede despertar el PC: {0}.", + "ControllerWakeNone": "Ningún adaptador de mando ni Bluetooth de este PC puede despertarlo. Conecta el adaptador o el mando y vuelve a intentarlo.", + "ControllerWakeUnknown": "No se pudieron comprobar los dispositivos.", + "ControllerWakeEnabled": "Listo. Suspende el PC y pulsa el botón central del mando para probarlo.", + "ControllerWakeCanceled": "Windows no recibió el permiso; no se ha cambiado nada.", + "ControllerWakeFailed": "No se pudo activar. Los detalles están en el registro.", + "ControllerWakeUnavailable": "No disponible", "HomeButtonShortPressCard": "Pulsación corta del botón Xbox", "HomeButtonShortPressDescription": "Basta con pulsar, sin mantener. Desactiva el atajo del mando para la Game Bar en Windows (Win+G sigue funcionando).", "HomeButtonSteamHint": "Steam está abierto y también usa el botón Xbox. En Steam, desactiva \"El botón Guía enfoca Steam\" para que la pulsación corta funcione.", diff --git a/src/ConsoleMode/Resources/Strings.fr-FR.json b/src/ConsoleMode/Resources/Strings.fr-FR.json index 88328f2..101cd78 100644 --- a/src/ConsoleMode/Resources/Strings.fr-FR.json +++ b/src/ConsoleMode/Resources/Strings.fr-FR.json @@ -139,6 +139,18 @@ "ControllerMouseHint": "Stick gauche : déplacer · {0} : clic · {0} deux fois : clic droit · stick droit : défiler", "AutoStartControllerCard": "Entrer à la connexion d'une manette", "AutoStartControllerDescription": "Avec l'application dans la zone de notification, allumer ou brancher une manette lance le mode console. Ignoré pendant les 15 s suivant l'ouverture et les 30 s suivant une restauration.", + "ControllerWakeCard": "Réveiller le PC avec la manette", + "ControllerWakeDescription": "Permet à l'adaptateur sans fil Xbox, au Bluetooth ou à une manette filaire de sortir le PC de la veille quand vous appuyez sur le bouton central de la manette. Windows demande l'autorisation d'administrateur. 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 activé, le PC se réveille directement en mode console.", + "ControllerWakeButton": "Activer", + "ControllerWakeChecking": "Vérification des périphériques…", + "ControllerWakeReady": "Prêt : {0} peut réveiller le PC.", + "ControllerWakeOff": "Ne peut pas encore réveiller le PC : {0}.", + "ControllerWakeNone": "Aucun adaptateur de manette ni Bluetooth de ce PC ne peut le réveiller. Branchez l'adaptateur ou la manette et réessayez.", + "ControllerWakeUnknown": "Impossible de vérifier les périphériques.", + "ControllerWakeEnabled": "C'est fait. Mettez le PC en veille et appuyez sur le bouton central de la manette pour essayer.", + "ControllerWakeCanceled": "Windows n'a pas reçu l'autorisation ; rien n'a été modifié.", + "ControllerWakeFailed": "Impossible d'activer. Les détails sont dans le journal.", + "ControllerWakeUnavailable": "Indisponible", "HomeButtonShortPressCard": "Appui court sur le bouton Xbox", "HomeButtonShortPressDescription": "Un simple appui, sans maintenir. Désactive le raccourci manette de la Game Bar dans Windows (Win+G continue de fonctionner).", "HomeButtonSteamHint": "Steam est ouvert et utilise aussi le bouton Xbox. Dans Steam, désactivez \"Le bouton Guide met Steam au premier plan\" pour que l'appui court fonctionne.", diff --git a/src/ConsoleMode/Resources/Strings.pt-BR.json b/src/ConsoleMode/Resources/Strings.pt-BR.json index dd0986b..e9e98d6 100644 --- a/src/ConsoleMode/Resources/Strings.pt-BR.json +++ b/src/ConsoleMode/Resources/Strings.pt-BR.json @@ -139,6 +139,18 @@ "ControllerMouseHint": "Analógico esquerdo move · {0} clica · {0} duas vezes: botão direito · analógico direito rola", "AutoStartControllerCard": "Entrar ao conectar um controle", "AutoStartControllerDescription": "Com o app na bandeja, ligar ou conectar um controle entra no modo console. Ignora os primeiros 15 s após abrir e 30 s após restaurar.", + "ControllerWakeCard": "Acordar o PC pelo controle", + "ControllerWakeDescription": "Deixa o adaptador sem fio Xbox, o Bluetooth ou o controle no cabo acordarem o PC da suspensão quando você aperta o botão central do controle. O Windows pede permissão de administrador. Não acorda o PC desligado ou em hibernação, e alguns PCs cortam a energia do Bluetooth ao suspender. Com Entrar ao conectar um controle ligado, o PC já acorda no modo console.", + "ControllerWakeButton": "Ativar", + "ControllerWakeChecking": "Verificando os dispositivos…", + "ControllerWakeReady": "Pronto: {0} pode acordar o PC.", + "ControllerWakeOff": "Ainda não pode acordar o PC: {0}.", + "ControllerWakeNone": "Nenhum adaptador de controle ou Bluetooth deste PC pode acordá-lo. Conecte o adaptador ou o controle e tente de novo.", + "ControllerWakeUnknown": "Não foi possível verificar os dispositivos.", + "ControllerWakeEnabled": "Pronto. Suspenda o PC e aperte o botão central do controle para testar.", + "ControllerWakeCanceled": "O Windows não recebeu a permissão; nada foi alterado.", + "ControllerWakeFailed": "Não foi possível ativar. Os detalhes estão no log.", + "ControllerWakeUnavailable": "Indisponível", "HomeButtonShortPressCard": "Toque curto no botão Xbox", "HomeButtonShortPressDescription": "Basta apertar, sem segurar. Desliga o atalho do controle para a Game Bar no Windows (Win+G continua funcionando).", "HomeButtonSteamHint": "A Steam está aberta e também usa o botão Xbox. Na Steam, desligue \"Botão Guide foca a Steam\" para o toque curto funcionar.", diff --git a/src/ConsoleMode/Resources/Strings.ru-RU.json b/src/ConsoleMode/Resources/Strings.ru-RU.json index 93468b9..701b324 100644 --- a/src/ConsoleMode/Resources/Strings.ru-RU.json +++ b/src/ConsoleMode/Resources/Strings.ru-RU.json @@ -139,6 +139,18 @@ "ControllerMouseHint": "Левый стик — перемещение · {0} — щелчок · {0} дважды — правый щелчок · правый стик — прокрутка", "AutoStartControllerCard": "Входить при подключении геймпада", "AutoStartControllerDescription": "Когда приложение в области уведомлений, включение или подключение геймпада запускает режим консоли. Не срабатывает первые 15 с после запуска и 30 с после восстановления.", + "ControllerWakeCard": "Пробуждать ПК геймпадом", + "ControllerWakeDescription": "Разрешает беспроводному адаптеру Xbox, Bluetooth или проводному геймпаду выводить ПК из спящего режима по нажатию центральной кнопки геймпада. Windows запросит права администратора. Выключенный ПК или ПК в режиме гибернации не проснётся, а некоторые ПК отключают питание Bluetooth во сне. Если включено «Входить при подключении геймпада», ПК сразу проснётся в режиме консоли.", + "ControllerWakeButton": "Включить", + "ControllerWakeChecking": "Проверка устройств…", + "ControllerWakeReady": "Готово: {0} может пробудить ПК.", + "ControllerWakeOff": "Пока не может пробудить ПК: {0}.", + "ControllerWakeNone": "Ни адаптер геймпада, ни Bluetooth этого ПК не могут его пробудить. Подключите адаптер или геймпад и попробуйте снова.", + "ControllerWakeUnknown": "Не удалось проверить устройства.", + "ControllerWakeEnabled": "Готово. Переведите ПК в спящий режим и нажмите центральную кнопку геймпада, чтобы проверить.", + "ControllerWakeCanceled": "Windows не получила разрешения; ничего не изменено.", + "ControllerWakeFailed": "Не удалось включить. Подробности в журнале.", + "ControllerWakeUnavailable": "Недоступно", "HomeButtonShortPressCard": "Короткое нажатие кнопки Xbox", "HomeButtonShortPressDescription": "Достаточно нажать, удерживать не нужно. Отключает открытие Game Bar с геймпада в Windows (Win+G продолжает работать).", "HomeButtonSteamHint": "Steam открыт и тоже использует кнопку Xbox. Чтобы короткое нажатие работало, отключите в Steam параметр «Кнопка Guide переключает на Steam».", diff --git a/src/ConsoleMode/Services/ControllerWake.cs b/src/ConsoleMode/Services/ControllerWake.cs new file mode 100644 index 0000000..7897a38 --- /dev/null +++ b/src/ConsoleMode/Services/ControllerWake.cs @@ -0,0 +1,113 @@ +using System.Text; +using System.Text.Json; + +namespace ConsoleMode.Services; + +public enum WakeDeviceKind { None, XboxAdapter, Bluetooth, Controller } + +/// A device Windows can let wake the PC (WMI MSPower_DeviceWakeEnable) and whether it may now. +public sealed record WakeDevice(string InstanceName, string Name, string PnpClass, bool Armed) +{ + public WakeDeviceKind Kind => ControllerWake.Classify(InstanceName, PnpClass); +} + +/// +/// Waking the PC from sleep with the controller (issue #155): what wakes it is the device the +/// controller talks through (the Xbox Wireless Adapter, the Bluetooth radio, or the controller +/// itself on a cable), and Windows only lets it once "Allow this device to wake the computer" is on. +/// Devices are told apart by their instance id, which, unlike the name, isn't translated. +/// +public static class ControllerWake +{ + // Xbox Wireless Adapter for Windows: the original, the slim one, and the newer revisions. + private static readonly string[] XboxAdapterIds = ["PID_02E6", "PID_02FE", "PID_02F9", "PID_091E"]; + + // Sony, Nintendo, 8BitDo, Valve, Logitech gamepads, PowerA, PDP, Hori, Nacon. Xbox pads are + // found by their class instead: Microsoft also makes the keyboards and mice. + private static readonly string[] GamepadVendors = + ["VID_054C", "VID_057E", "VID_2DC8", "VID_28DE", "VID_046D&PID_C2", "VID_20D6", "VID_0E6F", "VID_0F0D", "VID_146B"]; + + public static WakeDeviceKind Classify(string? instanceName, string? pnpClass) + { + var id = (instanceName ?? "").ToUpperInvariant(); + var cls = pnpClass ?? ""; + if (id.Length == 0) return WakeDeviceKind.None; + + if (id.StartsWith(@"USB\VID_045E&", StringComparison.Ordinal) && XboxAdapterIds.Any(id.Contains)) + return WakeDeviceKind.XboxAdapter; + + // The radio itself, not the devices paired through it (BTHENUM\…, BTHLE\…). + if (cls.Equals("Bluetooth", StringComparison.OrdinalIgnoreCase) && (id.StartsWith(@"USB\", StringComparison.Ordinal) || id.StartsWith(@"PCI\", StringComparison.Ordinal))) + return WakeDeviceKind.Bluetooth; + + // XInput pads show up as HID collections marked IG_; Xbox pads on a cable as their own class. + if (id.Contains("&IG_", StringComparison.Ordinal) || cls.Equals("XnaComposite", StringComparison.OrdinalIgnoreCase) + || cls.Equals("XboxComposite", StringComparison.OrdinalIgnoreCase)) + return WakeDeviceKind.Controller; + if ((id.StartsWith(@"USB\", StringComparison.Ordinal) || id.StartsWith(@"HID\", StringComparison.Ordinal)) + && GamepadVendors.Any(id.Contains)) + return WakeDeviceKind.Controller; + + return WakeDeviceKind.None; + } + + /// The controller-related devices, the adapter first, then Bluetooth, then controllers. + public static List Relevant(IEnumerable devices) => + [.. devices.Where(d => d.Kind != WakeDeviceKind.None).OrderBy(d => d.Kind).ThenBy(d => d.Name, StringComparer.CurrentCultureIgnoreCase)]; + + /// Reads the JSON the query script prints (one object or an array). + public static List Parse(string? json) + { + var list = new List(); + if (string.IsNullOrWhiteSpace(json)) return list; + using var doc = JsonDocument.Parse(json); + var items = doc.RootElement.ValueKind == JsonValueKind.Array ? doc.RootElement.EnumerateArray().ToList() : [doc.RootElement]; + foreach (var item in items) + { + if (item.ValueKind != JsonValueKind.Object) continue; + var instance = Text(item, "InstanceName"); + if (string.IsNullOrWhiteSpace(instance)) continue; + var armed = item.TryGetProperty("Enable", out var enable) && enable.ValueKind == JsonValueKind.True; + var name = Text(item, "Name"); + list.Add(new WakeDevice(instance, string.IsNullOrWhiteSpace(name) ? DeviceId(instance) : name, Text(item, "PnpClass"), armed)); + } + return list; + } + + /// WMI names wake entries after the device with an "_N" suffix. + public static string DeviceId(string instanceName) + { + var cut = instanceName.LastIndexOf('_'); + return cut > 0 && cut < instanceName.Length - 1 && instanceName[(cut + 1)..].All(char.IsAsciiDigit) + ? instanceName[..cut] + : instanceName; + } + + /// Lists every device that can wake the PC, with its name and class, as JSON. + public const string QueryScript = """ + [Console]::OutputEncoding = [Text.Encoding]::UTF8 + $ErrorActionPreference = 'Stop' + $pnp = @{} + Get-CimInstance Win32_PnPEntity -Property DeviceID,Name,PNPClass | ForEach-Object { $pnp[$_.DeviceID] = $_ } + $rows = @(Get-CimInstance -Namespace root\wmi -ClassName MSPower_DeviceWakeEnable | ForEach-Object { + $d = $pnp[($_.InstanceName -replace '_\d+$', '')] + [pscustomobject]@{ InstanceName = $_.InstanceName; Name = $d.Name; PnpClass = $d.PNPClass; Enable = [bool]$_.Enable } + }) + ConvertTo-Json -InputObject $rows -Compress + """; + + /// Turns on "may wake the computer" for the given WMI entries (needs an elevated PowerShell). + public static string EnableScript(IEnumerable instanceNames) + { + var quoted = string.Join(",", instanceNames.Select(n => "'" + n.Replace("'", "''") + "'")); + return "$ErrorActionPreference = 'Stop'\n" + + $"$ids = @({quoted})\n" + + "Get-CimInstance -Namespace root\\wmi -ClassName MSPower_DeviceWakeEnable | Where-Object { $ids -contains $_.InstanceName } | Set-CimInstance -Property @{ Enable = $true }\n"; + } + + /// The argument for powershell -EncodedCommand (UTF-16LE in Base64). + public static string Encode(string script) => Convert.ToBase64String(Encoding.Unicode.GetBytes(script)); + + private static string Text(JsonElement item, string name) => + item.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() ?? "" : ""; +} diff --git a/src/ConsoleMode/Services/ControllerWakeService.cs b/src/ConsoleMode/Services/ControllerWakeService.cs new file mode 100644 index 0000000..de15036 --- /dev/null +++ b/src/ConsoleMode/Services/ControllerWakeService.cs @@ -0,0 +1,68 @@ +using System.ComponentModel; +using System.Diagnostics; + +namespace ConsoleMode.Services; + +/// +/// Reads and turns on "Allow this device to wake the computer" for the controller's adapters +/// (issue #155). Reading needs no rights; turning it on runs an elevated PowerShell, so Windows asks first. +/// +public static class ControllerWakeService +{ + private const string PowerShell = "powershell.exe"; + + /// The controller-related devices that can wake the PC, or null when they couldn't be read. + public static List? Read() + { + try + { + var json = ProcessRunner.RunCapture(PowerShell, + ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", ControllerWake.Encode(ControllerWake.QueryScript)], + timeoutMs: 20000); + return ControllerWake.Relevant(ControllerWake.Parse(json)); + } + catch (Exception ex) + { + AppLog.Write($"Acordar pelo controle: leitura falhou: {ex.Message}"); + return null; + } + } + + public enum EnableResult { Done, Canceled, Failed } + + /// Lets the given devices wake the PC. Shows the UAC prompt; blocks until PowerShell exits. + public static EnableResult Enable(IReadOnlyCollection devices) + { + if (devices.Count == 0) return EnableResult.Done; + var script = ControllerWake.EnableScript(devices.Select(d => d.InstanceName)); + try + { + using var process = Process.Start(new ProcessStartInfo + { + FileName = PowerShell, + Arguments = $"-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -EncodedCommand {ControllerWake.Encode(script)}", + UseShellExecute = true, + Verb = "runas", + WindowStyle = ProcessWindowStyle.Hidden + }); + if (process is null) return EnableResult.Failed; + if (!process.WaitForExit(30000)) + { + AppLog.Write("Acordar pelo controle: o PowerShell não terminou em 30 s"); + return EnableResult.Failed; + } + AppLog.Write($"Acordar pelo controle: {string.Join(", ", devices.Select(d => d.Name))} => {process.ExitCode}"); + return process.ExitCode == 0 ? EnableResult.Done : EnableResult.Failed; + } + catch (Win32Exception ex) when (ex.NativeErrorCode == 1223) + { + AppLog.Write("Acordar pelo controle: permissão de administrador recusada"); + return EnableResult.Canceled; + } + catch (Exception ex) + { + AppLog.Write($"Acordar pelo controle: {ex.Message}"); + return EnableResult.Failed; + } + } +} diff --git a/src/ConsoleMode/Services/LocalizationService.cs b/src/ConsoleMode/Services/LocalizationService.cs index 67cb87e..d74f727 100644 --- a/src/ConsoleMode/Services/LocalizationService.cs +++ b/src/ConsoleMode/Services/LocalizationService.cs @@ -262,6 +262,9 @@ internal void NotifyAll() public string ControllerMouseRow => LocalizationService.Get(nameof(ControllerMouseRow)); public string AutoStartControllerCard => LocalizationService.Get(nameof(AutoStartControllerCard)); public string AutoStartControllerDescription => LocalizationService.Get(nameof(AutoStartControllerDescription)); + public string ControllerWakeCard => LocalizationService.Get(nameof(ControllerWakeCard)); + public string ControllerWakeDescription => LocalizationService.Get(nameof(ControllerWakeDescription)); + public string ControllerWakeButton => LocalizationService.Get(nameof(ControllerWakeButton)); public string NotifyUpdatesCard => LocalizationService.Get(nameof(NotifyUpdatesCard)); public string NotifyUpdatesDescription => LocalizationService.Get(nameof(NotifyUpdatesDescription)); public string BetaUpdatesCard => LocalizationService.Get(nameof(BetaUpdatesCard)); diff --git a/src/ConsoleMode/ViewModels/MainViewModel.ConsoleUi.cs b/src/ConsoleMode/ViewModels/MainViewModel.ConsoleUi.cs index 4037589..7eb73f9 100644 --- a/src/ConsoleMode/ViewModels/MainViewModel.ConsoleUi.cs +++ b/src/ConsoleMode/ViewModels/MainViewModel.ConsoleUi.cs @@ -256,6 +256,7 @@ private void CycleSetting(string spec) case "exitshortcut": ToggleSuggestedShortcut(ShortcutSlot.Exit); break; case "shortpress": HomeButtonShortPress = !HomeButtonShortPress; break; case "autostart": AutoStartOnController = !AutoStartOnController; break; + case "controllerwake": _ = EnableControllerWakeAsync(); break; case "sounds": InterfaceSounds = !InterfaceSounds; break; case "background": CycleBackgroundMode(); break; case "backgroundimage": PickBackgroundImage(); break; diff --git a/src/ConsoleMode/ViewModels/MainViewModel.ControllerWake.cs b/src/ConsoleMode/ViewModels/MainViewModel.ControllerWake.cs new file mode 100644 index 0000000..3c0afd6 --- /dev/null +++ b/src/ConsoleMode/ViewModels/MainViewModel.ControllerWake.cs @@ -0,0 +1,87 @@ +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using ConsoleMode.Services; +using Microsoft.UI.Xaml.Controls; + +namespace ConsoleMode.ViewModels; + +// Waking the PC from sleep with the controller (issue #155): shows which of the controller's +// adapters may wake it and turns the rest on (Windows asks for administrator rights). +public partial class MainViewModel +{ + private List? _wakeDevices; + private bool _wakeChecked; + + [ObservableProperty] private string _controllerWakeStatus = ""; + /// Short value for the console row: on, the button's verb, or unavailable. + [ObservableProperty] private string _controllerWakeValue = ""; + [ObservableProperty] private bool _canEnableControllerWake = true; + + private async Task RefreshControllerWakeAsync() + { + CanEnableControllerWake = false; + ControllerWakeStatus = LocalizationService.Get("ControllerWakeChecking"); + ControllerWakeValue = ControllerWakeStatus; + _wakeDevices = await Task.Run(ControllerWakeService.Read); + _wakeChecked = true; + CanEnableControllerWake = true; + RefreshControllerWakeText(); + } + + private void RefreshControllerWakeText() + { + if (!_wakeChecked) return; + if (_wakeDevices is null) + { + ControllerWakeStatus = LocalizationService.Get("ControllerWakeUnknown"); + ControllerWakeValue = LocalizationService.Get("ControllerWakeUnavailable"); + return; + } + if (_wakeDevices.Count == 0) + { + ControllerWakeStatus = LocalizationService.Get("ControllerWakeNone"); + ControllerWakeValue = LocalizationService.Get("ControllerWakeUnavailable"); + return; + } + var off = _wakeDevices.Where(d => !d.Armed).ToList(); + ControllerWakeStatus = off.Count == 0 + ? LocalizationService.Get("ControllerWakeReady", Names(_wakeDevices)) + : LocalizationService.Get("ControllerWakeOff", Names(off)); + ControllerWakeValue = LocalizationService.Get(off.Count == 0 ? "ToggleOn" : "ControllerWakeButton"); + } + + private static string Names(IEnumerable devices) => + string.Join(", ", devices.Select(d => d.Name).Distinct(StringComparer.CurrentCultureIgnoreCase).Take(3)); + + /// Reads the devices again (an adapter may have been plugged in since) and turns on the ones still off. + [RelayCommand] + private async Task EnableControllerWakeAsync() + { + if (!CanEnableControllerWake) return; + await RefreshControllerWakeAsync(); + var off = _wakeDevices?.Where(d => !d.Armed).ToList(); + if (off is not { Count: > 0 }) + { + // Nothing to turn on: say why (the console row only shows a word). + SetStatus(ControllerWakeStatus, _wakeDevices is { Count: > 0 } ? InfoBarSeverity.Success : InfoBarSeverity.Warning); + return; + } + + CanEnableControllerWake = false; + var result = await Task.Run(() => ControllerWakeService.Enable(off)); + switch (result) + { + case ControllerWakeService.EnableResult.Done: + SetStatus(LocalizationService.Get("ControllerWakeEnabled"), InfoBarSeverity.Success); + break; + case ControllerWakeService.EnableResult.Canceled: + SetStatus(LocalizationService.Get("ControllerWakeCanceled"), InfoBarSeverity.Warning); + break; + default: + SetStatus(LocalizationService.Get("ControllerWakeFailed"), InfoBarSeverity.Error); + break; + } + CanEnableControllerWake = true; + await RefreshControllerWakeAsync(); + } +} diff --git a/src/ConsoleMode/ViewModels/MainViewModel.cs b/src/ConsoleMode/ViewModels/MainViewModel.cs index ff48274..6b56a91 100644 --- a/src/ConsoleMode/ViewModels/MainViewModel.cs +++ b/src/ConsoleMode/ViewModels/MainViewModel.cs @@ -134,6 +134,7 @@ public async Task InitializeAsync(bool interactive = true) _ = RecheckControllerAsync(); StartBatteryPolling(); _ = RefreshBackgroundAsync(); + _ = RefreshControllerWakeAsync(); // The tour points at desktop controls; the console interface explains itself. if (interactive && HasMonitors && !_loadedConfig.TourDone && !IsConsoleUi) StartTour(); else if (interactive) RequestShortcutOnboarding(); @@ -156,6 +157,7 @@ private void OnLanguageChanged(object? sender, EventArgs e) foreach (var monitor in Monitors) monitor.RefreshLocalizedText(); UpdateSummary(); RefreshUpdateStrings(); + RefreshControllerWakeText(); RefreshConsoleTexts(); } diff --git a/src/ConsoleMode/Views/ConsoleHomeView.xaml b/src/ConsoleMode/Views/ConsoleHomeView.xaml index 12c494b..222e215 100644 --- a/src/ConsoleMode/Views/ConsoleHomeView.xaml +++ b/src/ConsoleMode/Views/ConsoleHomeView.xaml @@ -677,6 +677,13 @@ +