diff --git a/CHANGELOG.en-US.md b/CHANGELOG.en-US.md index 762dd26..0c3aa4e 100644 --- a/CHANGELOG.en-US.md +++ b/CHANGELOG.en-US.md @@ -5,6 +5,7 @@ English (US) release notes, mirroring CHANGELOG.md (Brazilian Portuguese). Befor ## [Unreleased] ### What's new - 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) ## [1.7.0-alpha.2] ### What's new diff --git a/CHANGELOG.md b/CHANGELOG.md index 9900063..9549677 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ Notas em português do Brasil; a versão em inglês (Estados Unidos) fica em `CH ## [Unreleased] ### Novidades - 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) ## [1.7.0-alpha.2] ### Novidades diff --git a/docs/GUIDE.de-DE.md b/docs/GUIDE.de-DE.md index ef431c2..f69016d 100644 --- a/docs/GUIDE.de-DE.md +++ b/docs/GUIDE.de-DE.md @@ -29,6 +29,8 @@ Bei der Rückkehr aus Big Picture schließt **Steam beim Zurückkehren zum PC in Ein Wechsel des Hauptbildschirms kann Windows dazu bringen, die Desktopsymbole neu anzuordnen. **Desktopsymbole wieder an ihren Platz setzen** (standardmäßig an) speichert vor der Sitzung, wo sie liegen, und setzt sie nach der Wiederherstellung wieder dorthin. Ist auf dem Desktop **Symbole automatisch anordnen** aktiv, passiert nichts, weil Windows sie dann selbst anordnet. +**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 9a6fbac..d50ec65 100644 --- a/docs/GUIDE.es-ES.md +++ b/docs/GUIDE.es-ES.md @@ -29,6 +29,8 @@ Al volver de Big Picture, **Enviar Steam a la bandeja al volver al PC** cierra l Cambiar la pantalla principal puede hacer que Windows reordene los iconos del escritorio. **Devolver los iconos del escritorio a su sitio** (activado por defecto) guarda su posición antes de la sesión y los vuelve a colocar después de restaurar el escritorio. No hace nada si **Organizar iconos automáticamente** está activado en el escritorio, porque entonces Windows los coloca por sí mismo. +**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 9612288..fd50d0a 100644 --- a/docs/GUIDE.fr-FR.md +++ b/docs/GUIDE.fr-FR.md @@ -29,6 +29,8 @@ Au retour de Big Picture, **Réduire Steam dans la zone de notification au retou Changer d'écran principal peut amener Windows à mélanger les icônes du bureau. **Remettre les icônes du bureau à leur place** (activé par défaut) enregistre leur position avant la session et les remet en place une fois le bureau restauré. Sans effet si **Réorganiser automatiquement les icônes** est activé sur le bureau, car Windows les place alors lui-même. +**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 4b8774a..8d1242d 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -35,6 +35,8 @@ When returning from Big Picture, **Send Steam to the tray when going back to the Changing the main display can make Windows reshuffle the desktop icons. **Put desktop icons back in place** (on by default) saves where they are before the session and puts them back after the desk is restored. It does nothing when the desktop's **Auto arrange icons** is on, since Windows lays them out itself then. +**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 b25d457..dacd004 100644 --- a/docs/GUIDE.pt-BR.md +++ b/docs/GUIDE.pt-BR.md @@ -35,6 +35,8 @@ Ao voltar do Big Picture, **Mandar a Steam para a bandeja ao voltar ao PC** fech Trocar a tela principal pode fazer o Windows embaralhar os ícones da área de trabalho. **Devolver os ícones da área de trabalho ao lugar** (ligado por padrão) salva a posição deles antes da sessão e os coloca de volta depois que a mesa é restaurada. Não faz nada quando **Organizar ícones automaticamente** está ligado na área de trabalho, porque aí o próprio Windows os arruma. +**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 38a6f16..dd16d87 100644 --- a/docs/GUIDE.ru-RU.md +++ b/docs/GUIDE.ru-RU.md @@ -29,6 +29,8 @@ При смене основного экрана Windows может перемешать значки рабочего стола. Параметр **«Возвращать значки рабочего стола на место»** (включён по умолчанию) запоминает их расположение перед сеансом и возвращает значки после восстановления рабочего места. Если на рабочем столе включено **«Упорядочить значки автоматически»**, параметр ничего не делает: Windows расставляет их сам. +Параметр **«Пробуждать ПК геймпадом»** разрешает беспроводному адаптеру Xbox, Bluetooth или проводному геймпаду выводить ПК из спящего режима центральной кнопкой геймпада. Кнопка **«Включить»** запрашивает у Windows права администратора и отмечает у этих устройств *Разрешить этому устройству выводить компьютер из ждущего режима*. Выключенный ПК или ПК в режиме гибернации не проснётся, а некоторые ПК отключают питание Bluetooth во сне. Вместе с **«Входить при подключении геймпада»** ПК сразу проснётся в режиме консоли. + ## Локальный API управления Ссылки `consolemode://` срабатывают без ответа. Инструменты, которым нужен ответ (агент удалённого управления, работающий как служба Windows, плагин Stream Deck, показывающий, включён ли режим консоли), могут использовать именованный канал `\\.\pipe\ConsoleMode.Control`, пока приложение запущено: отправьте одну строку JSON и получите одну в ответ. diff --git a/docs/TESTING.md b/docs/TESTING.md index 94bd52d..f6be40c 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -119,6 +119,18 @@ 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: ______ +- [ ] Clicar em **Ativar**, desconectar o adaptador ou o controle com o UAC aberto e depois aceitar: aparece o aviso de que o dispositivo não foi encontrado (não "Pronto…"), e o log mostra o código 2. 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 3d67f7a..5d6241b 100644 --- a/src/ConsoleMode/Resources/Strings.de-DE.json +++ b/src/ConsoleMode/Resources/Strings.de-DE.json @@ -141,6 +141,19 @@ "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.", + "ControllerWakeGone": "Das Gerät war beim Einschalten nicht mehr da (wurde es getrennt?). Schließe es wieder an und versuche es erneut.", + "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 e786646..3838759 100644 --- a/src/ConsoleMode/Resources/Strings.en-US.json +++ b/src/ConsoleMode/Resources/Strings.en-US.json @@ -141,6 +141,19 @@ "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.", + "ControllerWakeGone": "The device wasn't there when turning it on (was it unplugged?). Plug it back in and try again.", + "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 c77c569..ddc7f8a 100644 --- a/src/ConsoleMode/Resources/Strings.es-ES.json +++ b/src/ConsoleMode/Resources/Strings.es-ES.json @@ -141,6 +141,19 @@ "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.", + "ControllerWakeGone": "No se encontró el dispositivo al activarlo (¿se desconectó?). Vuelve a conectarlo e inténtalo de nuevo.", + "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 6f40641..cf6fb61 100644 --- a/src/ConsoleMode/Resources/Strings.fr-FR.json +++ b/src/ConsoleMode/Resources/Strings.fr-FR.json @@ -141,6 +141,19 @@ "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.", + "ControllerWakeGone": "L'appareil était introuvable au moment de l'activer (a-t-il été débranché ?). Rebranchez-le et réessayez.", + "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 0d622ea..a45891a 100644 --- a/src/ConsoleMode/Resources/Strings.pt-BR.json +++ b/src/ConsoleMode/Resources/Strings.pt-BR.json @@ -141,6 +141,19 @@ "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.", + "ControllerWakeGone": "O dispositivo não foi encontrado na hora de ativar (foi desconectado?). Conecte-o de novo e tente outra vez.", + "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 05fe910..6a602b0 100644 --- a/src/ConsoleMode/Resources/Strings.ru-RU.json +++ b/src/ConsoleMode/Resources/Strings.ru-RU.json @@ -141,6 +141,19 @@ "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": "Не удалось включить. Подробности в журнале.", + "ControllerWakeGone": "Устройство не найдено в момент включения (его отключили?). Подключите его снова и повторите попытку.", + "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..b2950f0 --- /dev/null +++ b/src/ConsoleMode/Services/ControllerWake.cs @@ -0,0 +1,132 @@ +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 + """; + + /// Exit code of when none of the devices is there any more (unplugged meanwhile). + public const int NotFoundExitCode = 2; + + /// + /// Turns on "may wake the computer" for the given WMI entries (needs an elevated PowerShell). Exits with + /// when none of them is found, instead of succeeding without changing anything. + /// + public static string EnableScript(IEnumerable instanceNames) + { + var quoted = string.Join(",", instanceNames.Select(n => "'" + n.Replace("'", "''") + "'")); + return "$ErrorActionPreference = 'Stop'\n" + + $"$ids = @({quoted})\n" + + "$found = @(Get-CimInstance -Namespace root\\wmi -ClassName MSPower_DeviceWakeEnable | Where-Object { $ids -contains $_.InstanceName })\n" + + $"if ($found.Count -eq 0) {{ exit {NotFoundExitCode} }}\n" + + "$found | Set-CimInstance -Property @{ Enable = $true }\n"; + } + + /// + /// The devices that were meant to be turned on and, read again afterwards, still can't wake the PC + /// (or are gone). Empty means the change really took. + /// + public static List StillOff(IEnumerable attempted, IReadOnlyCollection? after) + { + if (after is null) return [.. attempted]; + var armed = after.Where(d => d.Armed).Select(d => d.InstanceName).ToHashSet(StringComparer.OrdinalIgnoreCase); + return [.. attempted.Where(d => !armed.Contains(d.InstanceName))]; + } + + /// 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..6e5d131 --- /dev/null +++ b/src/ConsoleMode/Services/ControllerWakeService.cs @@ -0,0 +1,73 @@ +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, NotFound } + + /// 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 switch + { + 0 => EnableResult.Done, + ControllerWake.NotFoundExitCode => EnableResult.NotFound, + _ => 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 8a45ec8..0ed2f18 100644 --- a/src/ConsoleMode/Services/LocalizationService.cs +++ b/src/ConsoleMode/Services/LocalizationService.cs @@ -264,6 +264,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 27c074e..337f396 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..f4b82db --- /dev/null +++ b/src/ConsoleMode/ViewModels/MainViewModel.ControllerWake.cs @@ -0,0 +1,98 @@ +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)); + CanEnableControllerWake = true; + await RefreshControllerWakeAsync(); + + // PowerShell saying it's done isn't proof: read the devices again and check they really can wake the PC. + if (result == ControllerWakeService.EnableResult.Done && ControllerWake.StillOff(off, _wakeDevices) is { Count: > 0 } stillOff) + { + AppLog.Write($"Acordar pelo controle: ainda desligado depois de ativar: {Names(stillOff)}"); + result = _wakeDevices is null ? ControllerWakeService.EnableResult.Failed : ControllerWakeService.EnableResult.NotFound; + } + + switch (result) + { + case ControllerWakeService.EnableResult.Done: + SetStatus(LocalizationService.Get("ControllerWakeEnabled"), InfoBarSeverity.Success); + break; + case ControllerWakeService.EnableResult.Canceled: + SetStatus(LocalizationService.Get("ControllerWakeCanceled"), InfoBarSeverity.Warning); + break; + case ControllerWakeService.EnableResult.NotFound: + SetStatus(LocalizationService.Get("ControllerWakeGone"), InfoBarSeverity.Warning); + break; + default: + SetStatus(LocalizationService.Get("ControllerWakeFailed"), InfoBarSeverity.Error); + break; + } + } +} diff --git a/src/ConsoleMode/ViewModels/MainViewModel.cs b/src/ConsoleMode/ViewModels/MainViewModel.cs index 608b69f..e35ba4b 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 a1fe11c..2d17f46 100644 --- a/src/ConsoleMode/Views/ConsoleHomeView.xaml +++ b/src/ConsoleMode/Views/ConsoleHomeView.xaml @@ -683,6 +683,13 @@ +