diff --git a/CHANGELOG.en-US.md b/CHANGELOG.en-US.md index 7d3a1571..32dfa45b 100644 --- a/CHANGELOG.en-US.md +++ b/CHANGELOG.en-US.md @@ -3,6 +3,8 @@ English (US) release notes, mirroring CHANGELOG.md (Brazilian Portuguese). Before publishing a version, add a `## [VERSION]` section to **both** files: the workflow publishes the section matching the tag from each one and fails if either is missing. ## [Unreleased] +### What's new +- **Task View shortcut**: a controller shortcut that does what Win + Tab does, opening Windows' Task View with all your windows, in a session or not. While it is open, the D-pad or the stick picks a window, A opens it and B closes it: Windows itself does that with an Xbox controller, and Console Mode with a PlayStation one (option **Move around Task View with a PlayStation controller**, on by default). It comes on as **Select + X** (change it or turn it off in System → Controller; the Xbox button alone, held, works too). The first three times, a notice slides into the corner with the buttons and the view opens right after, since nothing shows on top of it. (#188) ### Fixes - Guided tour: the **Skip tutorial** and **Back** buttons no longer cut off the bottom of the letters, and they are as tall as **Next**. (#187) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0999fdc7..0185eed2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,8 @@ Notas em português do Brasil; a versão em inglês (Estados Unidos) fica em `CHANGELOG.en-US.md`. Antes de publicar uma versão, adicione uma seção `## [VERSÃO]` com o changelog daquela versão **nos dois arquivos**. O workflow publica as duas seções correspondentes à tag na mesma release e falha se faltar alguma. ## [Unreleased] +### Novidades +- **Atalho para a visão de tarefas**: um atalho do controle que faz o mesmo que Win + Tab, abrindo a visão de tarefas do Windows com todas as janelas, numa sessão ou fora dela. Com ela aberta, o direcional ou o analógico escolhe a janela, A abre e B fecha: com controle Xbox quem faz isso é o próprio Windows, e com controle PlayStation é o Console Mode (opção **Navegar na visão de tarefas com controle PlayStation**, ligada por padrão). Já vem ligado com **Select + X** (troque ou desligue em Sistema → Controle; o botão Xbox sozinho, segurado, também serve). Nas três primeiras vezes, um aviso desliza no canto mostrando os botões e a visão abre logo depois, já que nada aparece por cima dela. (#188) ### Correções - Tour guiado: os botões **Pular tutorial** e **Voltar** não cortam mais a parte de baixo das letras e ficam da mesma altura que **Próximo**. (#187) diff --git a/docs/GUIDE.de-DE.md b/docs/GUIDE.de-DE.md index 0de318b3..e361f4fc 100644 --- a/docs/GUIDE.de-DE.md +++ b/docs/GUIDE.de-DE.md @@ -21,6 +21,8 @@ Das Sitzungsmenü bietet zwei Wege hinaus. **Zurück zum PC** beendet die Sitzun Das Menü funktioniert auch **außerhalb des Konsolenmodus**, um den PC vom Sofa aus zu bedienen, ohne etwas zu starten: Solange Console Mode geöffnet ist (auch nur im Infobereich), öffnen es die Menü-Tastenkombination, das Symbol im Infobereich oder `consolemode://menu` auf dem Spielbildschirm, wenn er eingeschaltet ist, sonst auf dem Hauptbildschirm. Dort kannst du Fenster wechseln, Lautstärke, Auflösung, Audioausgabe und HDR ändern, ControlFS und JoyChromium öffnen, den Mauszeiger ausblenden und die Maus mit dem Controller steuern. Was du änderst, bleibt so, bis du es wieder änderst, denn es gibt keine Sitzung zum Rückgängigmachen; FPS-Begrenzung und FPS-Anzeige erscheinen nur in einer Sitzung. Stört die Tastenkombination in einem Spiel, schalte **System → Controller → Sitzungsmenü außerhalb des Konsolenmodus** aus (über den Infobereich öffnet sich das Menü weiterhin). +Die **Tastenkombination für „Aktive Anwendungen“** macht mit dem Controller, was Win + Tab macht: Sie öffnet die Windows-Ansicht mit allen offenen Fenstern, in einer Sitzung oder außerhalb. Solange sie offen ist, wählen Steuerkreuz oder linker Stick ein Fenster (Halten wiederholt), **A** öffnet es und **B** schließt die Ansicht; die Tastenkombination schließt sie ebenfalls. Sie ist von Anfang an auf **Select + X** gesetzt; ändere oder deaktiviere sie unter **System → Controller → Controller-Tastenkombination für „Aktive Anwendungen“** (auch die Xbox-Taste allein geht, gehalten, wenn sie nicht die Kombination zum Öffnen von Console Mode ist). Die ersten drei Male zeigt ein Hinweis die Tasten, bevor die Ansicht aufgeht, denn über ihr erscheint nichts. Mit einem Xbox-Controller bewegt Windows die Auswahl selbst; mit einem PlayStation-Controller, den Windows dort nicht versteht, übernimmt das Console Mode (schalte **„Aktive Anwendungen“ mit einem PlayStation-Controller bedienen** aus, wenn du DS4Windows oder Steam Input nutzt und sich Eingaben wiederholen). + ## Die Oberfläche Console Mode hat eine einzige Oberfläche, gestaltet wie die einer Konsole: Sie füllt den Bildschirm und funktioniert mit einem Xbox- oder PlayStation-Controller, der Maus oder der Tastatur (klicke auf eine Registerkarte oder nutze Bild auf / Bild ab; Eingabe und Esc wirken wie A und B). Beim ersten Öffnen führt dich eine Tour durch die Registerkarten, die Launcher, die Spielen-Schaltfläche, die Bildschirme, die Schnelleinstellungen und die Controller-Tastenkombinationen; **A** geht weiter, **B** überspringt sie. Um sie erneut zu sehen: **System → App → Tutorial**. Während die App lädt, zeigt sie ein Intro mit dem Logo und einem Startsound; jede Taste überspringt es, ab und zu kommt als Überraschung eines im Stil der Xbox 360 oder der PS4 mit dem Sound der Konsole; unter **System → App** wählst du einen Stil (damit enden die Überraschungen), siehst es sofort an und schaltest das Intro oder nur seinen Sound aus. diff --git a/docs/GUIDE.es-ES.md b/docs/GUIDE.es-ES.md index 2d126474..fe286345 100644 --- a/docs/GUIDE.es-ES.md +++ b/docs/GUIDE.es-ES.md @@ -21,6 +21,8 @@ El menú de la sesión tiene dos salidas. **Volver al PC** termina la sesión y El menú también funciona **fuera del modo consola**, para usar el PC desde el sofá sin iniciar nada: con Console Mode abierto (aunque sea solo en la bandeja), el atajo del menú, el icono de la bandeja o `consolemode://menu` lo abren en la pantalla de juego, si está encendida, o en la principal. Ahí puedes cambiar de ventana, ajustar el volumen, la resolución, la salida de audio y el HDR, abrir ControlFS y JoyChromium, ocultar el cursor y mover el ratón con el mando. Lo que cambies queda así hasta que lo cambies de nuevo, porque no hay sesión que deshacer; el límite y el contador de FPS solo aparecen en una sesión. Si el atajo molesta en algún juego, desactiva **Sistema → Mando → Menú de la sesión fuera del modo consola** (la bandeja sigue abriendo el menú). +El **atajo de la vista de tareas** hace desde el mando lo que hace Win + Tab: abre la vista de tareas de Windows con todas las ventanas abiertas, dentro o fuera de una sesión. Con ella abierta, la cruceta o el joystick izquierdo eligen la ventana (mantener repite), **A** la abre y **B** cierra la vista; el atajo otra vez también la cierra. Viene activado con **Select + X**; cámbialo o desactívalo en **Sistema → Mando → Atajo del mando para la vista de tareas** (el botón Xbox solo también sirve, mantenido, si no es el atajo para abrir Console Mode). Las tres primeras veces, un aviso muestra los botones antes de que se abra la vista, porque nada aparece encima de ella. Con un mando de Xbox, la selección la mueve el propio Windows; con uno de PlayStation, que Windows no entiende ahí, lo hace Console Mode (desactiva **Moverse por la vista de tareas con un mando de PlayStation** si usas DS4Windows o Steam Input y los movimientos se repiten). + ## La interfaz Console Mode tiene una sola interfaz, hecha como la de una consola: ocupa toda la pantalla y funciona con un mando de Xbox o PlayStation, el ratón o el teclado (haz clic en una pestaña o usa Re Pág / Av Pág; Intro y Esc hacen de A y B). La primera vez que la abres, un recorrido guiado pasa por las pestañas, los lanzadores, el botón de jugar, las pantallas, los ajustes rápidos y los atajos del mando; **A** avanza y **B** lo salta. Para volver a verlo: **Sistema → Aplicación → Tutorial**. Mientras carga, la aplicación muestra una apertura con el logotipo y un sonido de entrada; cualquier botón la salta, de vez en cuando, por sorpresa, es una inspirada en la Xbox 360 o en la PS4, con el sonido de la consola; **Sistema → Aplicación** elige un estilo (lo que acaba con las sorpresas), la muestra al momento y desactiva la apertura o solo su sonido. diff --git a/docs/GUIDE.fr-FR.md b/docs/GUIDE.fr-FR.md index f3264a23..8a5447ba 100644 --- a/docs/GUIDE.fr-FR.md +++ b/docs/GUIDE.fr-FR.md @@ -21,6 +21,8 @@ Le menu de session propose deux sorties. **Retour au PC** termine la session et Le menu fonctionne aussi **hors du mode console**, pour utiliser le PC depuis le canapé sans rien lancer : tant que Console Mode est ouvert (même seulement dans la zone de notification), le raccourci du menu, l'icône de la zone de notification ou `consolemode://menu` l'ouvrent sur l'écran de jeu s'il est allumé, sinon sur l'écran principal. Vous pouvez y changer de fenêtre, régler le volume, la résolution, la sortie audio et le HDR, ouvrir ControlFS et JoyChromium, masquer le pointeur et piloter la souris à la manette. Ce que vous changez reste ainsi jusqu'à ce que vous le changiez de nouveau, car il n'y a pas de session à annuler ; la limite et le compteur de FPS n'apparaissent que pendant une session. Si le raccourci gêne dans un jeu, désactivez **Système → Manette → Menu de session hors du mode console** (l'icône de la zone de notification ouvre toujours le menu). +Le **raccourci de l'affichage des tâches** fait à la manette ce que fait Win + Tab : il ouvre l'affichage des tâches de Windows avec toutes les fenêtres ouvertes, en session ou non. Tant qu'il est ouvert, la croix ou le stick gauche choisit la fenêtre (maintenir répète), **A** l'ouvre et **B** ferme l'affichage ; le raccourci le ferme aussi. Il est activé d'origine sur **Select + X** ; changez-le ou désactivez-le dans **Système → Manette → Raccourci manette pour l'affichage des tâches** (le bouton Xbox seul marche aussi, maintenu, s'il n'est pas le raccourci pour ouvrir Console Mode). Les trois premières fois, un avis montre les boutons avant l'ouverture de l'affichage, car rien n'apparaît par-dessus. Avec une manette Xbox, c'est Windows qui déplace la sélection ; avec une manette PlayStation, que Windows ne comprend pas à cet endroit, c'est Console Mode (désactivez **Naviguer dans l'affichage des tâches avec une manette PlayStation** si vous utilisez DS4Windows ou Steam Input et que les commandes se répètent). + ## L'interface Console Mode a une seule interface, conçue comme celle d'une console : elle occupe tout l'écran et marche avec une manette Xbox ou PlayStation, la souris ou le clavier (cliquez sur un onglet ou utilisez Page précédente / Page suivante ; Entrée et Échap font office de A et B). À la première ouverture, une visite guidée passe par les onglets, les lanceurs, le bouton Jouer, les écrans, les réglages rapides et les raccourcis manette ; **A** avance, **B** la passe. Pour la revoir : **Système → Application → Tutoriel**. Pendant le chargement, l'application affiche une ouverture avec son logo et un son d'entrée ; n'importe quel bouton la passe, de temps en temps, par surprise, c'est une inspirée de la Xbox 360 ou de la PS4, avec le son de la console ; **Système → Application** choisit un style (ce qui met fin aux surprises), la montre tout de suite et désactive l'ouverture ou seulement son son. diff --git a/docs/GUIDE.md b/docs/GUIDE.md index bbc250ad..35745c70 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -25,6 +25,8 @@ The session menu has two ways out. **Back to the PC** ends the session and puts The menu also works **outside console mode**, to use the PC from the couch without starting anything: with Console Mode open (even just in the tray), the menu shortcut, the tray icon or `consolemode://menu` opens it on the game screen, if it is on, or on the primary one. There you can switch windows, change the volume, resolution, audio output and HDR, open ControlFS and JoyChromium, hide the pointer and drive the mouse with the controller. What you change stays that way until changed again, since there is no session to undo; the FPS limit and counter only show in a session. If the shortcut gets in the way in a game, turn off **System → Controller → Session menu outside console mode** (the tray still opens the menu). +The **Task View shortcut** does from the controller what Win + Tab does: it opens Windows' Task View with all your open windows, in a session or not. While it is open, the D-pad or the left stick picks a window (holding repeats), **A** opens it and **B** closes the view; the shortcut again closes it too. It comes on as **Select + X**; change it or turn it off in **System → Controller → Controller shortcut for Task View** (the Xbox button alone works too, held, if it isn't the open-Console-Mode shortcut). The first three times, a notice shows the buttons before the view opens, since nothing shows on top of it. With an Xbox controller, Windows itself moves the selection; with a PlayStation controller, which Windows doesn't understand there, Console Mode does (turn off **Move around Task View with a PlayStation controller** if you use DS4Windows or Steam Input and moves repeat). + ## The interface Console Mode has one interface, made like a console's: it fills the screen and works with an Xbox or PlayStation controller, the mouse or the keyboard (click a tab or use Page Up / Page Down; Enter and Esc work as A and B). The first time you open it, a guided tour walks through the tabs, the launchers, the play button, the screens, the quick settings and the controller shortcuts; **A** goes on, **B** skips it. To see it again: **System → App → Tutorial**. While the app loads it shows an opening with its logo and an entrance sound; any button skips it, now and then it is, as a surprise, one inspired by the Xbox 360 or the PS4, with that console's sound; **System → App** picks a style (which ends the surprises), plays it right away, and turns it off, or just its sound. diff --git a/docs/GUIDE.pt-BR.md b/docs/GUIDE.pt-BR.md index e9cf61ba..568d8b10 100644 --- a/docs/GUIDE.pt-BR.md +++ b/docs/GUIDE.pt-BR.md @@ -25,6 +25,8 @@ No menu da sessão há duas saídas. **Voltar ao PC** encerra a sessão e devolv O menu também funciona **fora do modo console**, para usar o PC do sofá sem iniciar nada: com o Console Mode aberto (mesmo só na bandeja), o atalho do menu, o ícone da bandeja ou `consolemode://menu` o abrem na tela de jogo, se ela estiver ligada, ou na principal. Ali dá para trocar de janela, mexer no volume, na resolução, na saída de áudio e no HDR, abrir o ControlFS e o JoyChromium, esconder o cursor e controlar o mouse com o controle. O que você muda fica assim até ser trocado de novo, já que não há sessão para desfazer; o limite e o contador de FPS só aparecem numa sessão. Se o atalho atrapalhar algum jogo, desligue **Sistema → Controle → Menu da sessão fora do modo console** (a bandeja continua abrindo o menu). +O **atalho da visão de tarefas** faz pelo controle o que o Win + Tab faz: abre a visão de tarefas do Windows com todas as janelas abertas, numa sessão ou fora dela. Com ela aberta, o direcional ou o analógico esquerdo escolhe a janela (segurar repete), **A** abre e **B** fecha; o atalho de novo também fecha. Ele já vem ligado com **Select + X**; troque ou desligue em **Sistema → Controle → Atalho do controle para a visão de tarefas** (o botão Xbox sozinho também serve, segurado, se não estiver no atalho de abrir o Console Mode). Nas três primeiras vezes, um aviso mostra os botões antes de a visão abrir, porque nada aparece por cima dela. Com controle Xbox, quem move a seleção é o próprio Windows; com controle PlayStation, que o Windows não entende ali, é o Console Mode (desligue em **Navegar na visão de tarefas com controle PlayStation** se usar DS4Windows ou o Steam Input e os comandos se repetirem). + ## A interface O Console Mode tem uma interface só, feita como a de um console: ocupa a tela toda e funciona com controle Xbox ou PlayStation, mouse ou teclado (clique numa aba ou use Page Up / Page Down; Enter e Esc fazem o papel de A e B). Na primeira vez que você abre, um tour guiado passa pelas abas, pelos iniciadores, pelo botão de jogar, pelas telas, pelos ajustes rápidos e pelos atalhos do controle; **A** avança e **B** pula. Para ver de novo: **Sistema → App → Tutorial**. Enquanto carrega, o app mostra uma abertura com o logo e um som de entrada; qualquer botão pula, de vez em quando, de surpresa, vem uma inspirada no Xbox 360 ou no PS4, com o som do console; **Sistema → App** escolhe um estilo (o que acaba com as surpresas), mostra a abertura na hora e desliga a abertura ou só o som. diff --git a/docs/GUIDE.ru-RU.md b/docs/GUIDE.ru-RU.md index 1f24acbf..15c01afc 100644 --- a/docs/GUIDE.ru-RU.md +++ b/docs/GUIDE.ru-RU.md @@ -21,6 +21,8 @@ Меню работает и **вне режима консоли** — чтобы пользоваться ПК с дивана, ничего не запуская: пока Console Mode запущен (даже только в трее), сочетание для меню, значок в трее или `consolemode://menu` открывают его на игровом экране, если он включён, иначе на основном. Там можно переключать окна, менять громкость, разрешение, аудиовыход и HDR, открывать ControlFS и JoyChromium, скрывать указатель и управлять мышью с геймпада. Изменённое остаётся таким, пока вы не поменяете его снова, ведь сеанса, который можно отменить, нет; ограничение и счётчик FPS появляются только в сеансе. Если сочетание мешает в какой-нибудь игре, выключите **Система → Геймпад → Меню сеанса вне режима консоли** (значок в трее по-прежнему открывает меню). +**Сочетание для представления задач** делает с геймпада то же, что Win + Tab: открывает представление задач Windows со всеми открытыми окнами — в сеансе и вне его. Пока оно открыто, крестовина или левый стик выбирают окно (удержание повторяет), **A** открывает его, а **B** закрывает представление; повторное сочетание тоже закрывает. Оно сразу включено как **Select + X**; изменить или выключить его можно в **«Система» → «Геймпад» → «Сочетание на геймпаде для представления задач»** (подойдёт и одна кнопка Xbox с удержанием, если она не занята сочетанием для открытия Console Mode). Первые три раза перед открытием появляется подсказка с кнопками, потому что поверх представления ничего не показывается. С геймпадом Xbox выделение двигает сама Windows; с геймпадом PlayStation, который Windows там не понимает, — Console Mode (выключите **«Управлять представлением задач геймпадом PlayStation»**, если пользуетесь DS4Windows или Steam Input и команды повторяются). + ## Интерфейс У Console Mode один интерфейс, устроенный как у консоли: он занимает весь экран и работает с геймпадом Xbox или PlayStation, мышью или клавиатурой (щёлкните по вкладке или используйте Page Up / Page Down; Enter и Esc работают как A и B). При первом запуске обзор проводит по вкладкам, лаунчерам, кнопке «Играть», экранам, быстрым настройкам и сочетаниям геймпада; **A** — дальше, **B** — пропустить. Чтобы посмотреть его снова: **«Система» → «Приложение» → «Обучение»**. Пока приложение загружается, показывается заставка с логотипом и звуком; любая кнопка её пропускает, иногда для сюрприза показывается заставка в духе Xbox 360 или PS4 со звуком консоли; в **«Система» → «Приложение»** можно выбрать стиль (после этого сюрпризов не будет), сразу посмотреть её и выключить заставку или только её звук. diff --git a/docs/PRD.md b/docs/PRD.md index 07197e87..198a759e 100644 --- a/docs/PRD.md +++ b/docs/PRD.md @@ -381,6 +381,7 @@ Legenda: **P0** = necessário para a 1.7.0; **P1** = próxima versão; **P2** = - [x] **INPUT-012 —** Bateria do controle no menu e na interface Console, com avisos em 15 % e 5 %. (#160, 1.7.0-alpha.1) - [ ] **INPUT-013 (P0) —** Acordar o PC pelo controle (adaptador Xbox, Bluetooth, cabo). (#168; ajuste na Fase 1.7) - [x] **INPUT-014 —** Estacionar o ponteiro no canto da tela de jogo quando o launcher aparece, ligado por padrão, devolvendo a posição ao voltar (D-21). Issue #172; base de @JarJarShinks no #173. (#177, 1.7.0) +- [x] **INPUT-017 —** Atalho do controle para a visão de tarefas (Win + Tab), dentro ou fora da sessão, com o controle navegando nela: controle Xbox pelo próprio Windows; controle PlayStation pelo Console Mode (direcional/analógico = setas, A = Enter, B = Esc, até ela fechar; opção em Sistema → Controle, ligada por padrão). Vem ligado com Select + X; nas três primeiras vezes um aviso com os botões aparece antes (nada aparece por cima da visão de tarefas). (#188, 1.7.0) - [ ] **INPUT-015 (P3) —** Atalhos por voz e assistente (Alexa, MCP). Issue #12. ### Épico UI — Interface Console diff --git a/docs/TESTING.md b/docs/TESTING.md index 2daf479c..0b1d3916 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -660,6 +660,14 @@ Pré-condições: um `config.json` sem `consoleTourDone` (vale para quem atualiz - [ ] "Ver a abertura" toca o estilo escolhido na hora, por cima da interface, e some sozinha (ou com qualquer botão). Resultado: ______ - [ ] Iniciar com o Windows / `--start` / bandeja: nenhuma abertura nem som com a janela escondida. Com as animações do Windows desligadas, o logo aparece parado e some sem fade. Resultado: ______ +### Atalho da visão de tarefas + +- [ ] Numa instalação nova e numa que já existia, Sistema → Controle → **Atalho do controle para a visão de tarefas** já mostra Select + X. Noutra rodada, trocar para só o botão Xbox (com o atalho de abrir o Console Mode desligado). Fora da sessão e numa sessão, segurar o atalho abre a visão de tarefas do Windows. Resultado: ______ +- [ ] Controle **Xbox**, com ela aberta: o próprio Windows move a seleção, cada toque anda **uma** casa só (sem repetir), **A** abre, **B** fecha; o atalho de novo também fecha. Com o controle como mouse ligado, o ponteiro não se mexe enquanto a visão está aberta. Resultado: ______ +- [ ] Controle **PlayStation** (sem DS4Windows/Steam Input transformando em Xbox): direcional e analógico esquerdo movem a seleção (segurar repete), ✕ abre, ○ fecha. Fechando com o mouse, o controle volta ao jogo (✕ não vira Enter). Com **Navegar na visão de tarefas com controle PlayStation** desligado, o controle PlayStation não mexe na visão. Resultado: ______ +- [ ] Com o menu da sessão aberto, o atalho fecha o menu e abre a visão de tarefas. Resultado: ______ +- [ ] Nas três primeiras vezes, o aviso "Visão de tarefas" desliza no canto com os botões do controle em uso (A/B ou ✕/○) e a visão abre ~1,6 s depois; da quarta em diante abre na hora, sem aviso. O aviso não aparece como janela dentro da visão de tarefas. Resultado: ______ + ### Lista de Sistema e outros apps - [ ] Aviso de início de sessão (com o atalho do menu definido) e de bateria fraca: entra deslizando da borda direita da TV, sem aparecer em outra tela ao lado; o fundo em volta do card é transparente (sem retângulo preto); a barrinha verde esvazia e o aviso sai deslizando para a direita. O jogo não perde o foco em nenhum momento. Resultado: ______ diff --git a/src/ConsoleMode/App.xaml.cs b/src/ConsoleMode/App.xaml.cs index 154d837c..70eb0916 100644 --- a/src/ConsoleMode/App.xaml.cs +++ b/src/ConsoleMode/App.xaml.cs @@ -18,6 +18,7 @@ public partial class App : Application private TrayService? _tray; private ControllerHoldWatcher? _guide; private ControllerHoldWatcher? _exitChord; + private ControllerHoldWatcher? _taskViewChord; private ControllerHoldWatcher? _menuChord; private ControllerConnectWatcher? _connect; private Mutex? _instanceMutex; @@ -186,6 +187,8 @@ private void WatchGuideButton() HoldDuration = TimeSpan.FromMilliseconds(250) }; _menuChord.Held += () => ViewModel?.ToggleSessionMenu(); + _taskViewChord = new ControllerHoldWatcher(_window.DispatcherQueue, 0, "atalho Visão de tarefas"); + _taskViewChord.Held += () => ViewModel?.ToggleTaskView(); ViewModel.PropertyChanged += OnViewModelChangedForGuide; RefreshGuideWatch(); @@ -213,10 +216,13 @@ or nameof(MainViewModel.IsConsoleActive) or nameof(MainViewModel.MenuOutsideSess private void RefreshGuideWatch() { - if (_guide is null || _exitChord is null || _menuChord is null || ViewModel is null) return; + if (_guide is null || _exitChord is null || _menuChord is null || _taskViewChord is null || ViewModel is null) return; _guide.Mask = ViewModel.GetShortcut(ShortcutSlot.Home); _menuChord.Mask = ViewModel.GetShortcut(ShortcutSlot.Menu); _exitChord.Mask = ViewModel.GetShortcut(ShortcutSlot.Exit); + _taskViewChord.Mask = ViewModel.GetShortcut(ShortcutSlot.TaskView); + // The Xbox button alone is a deliberate hold, like on the console; a combo of buttons is quick. + _taskViewChord.HoldDuration = _taskViewChord.Mask == ControllerShortcuts.Guide ? TimeSpan.FromMilliseconds(600) : TimeSpan.FromMilliseconds(250); _guide.HoldDuration = ViewModel.HomeButtonShortPress ? TimeSpan.Zero : ControllerHoldWatcher.LongHold; // Picking a shortcut presses buttons on purpose: nothing may fire meanwhile. A shortcut @@ -226,6 +232,8 @@ private void RefreshGuideWatch() // Outside a session too, unless turned off in System → Controller (a game may use the same buttons). Apply(_menuChord, idle && _menuChord.Mask != 0 && (ViewModel.IsConsoleActive || ViewModel.MenuOutsideSession)); Apply(_exitChord, idle && _exitChord.Mask != 0 && ViewModel.IsConsoleActive); + // Anytime, in a session or not: Windows' Task View is always there. + Apply(_taskViewChord, idle && _taskViewChord.Mask != 0); } private static void Apply(ControllerHoldWatcher watcher, bool run) diff --git a/src/ConsoleMode/Models/Models.cs b/src/ConsoleMode/Models/Models.cs index 3be745d8..b9d56ecf 100644 --- a/src/ConsoleMode/Models/Models.cs +++ b/src/ConsoleMode/Models/Models.cs @@ -70,6 +70,20 @@ public sealed class AppConfig public int HomeShortcut { get; set; } public int MenuShortcut { get; set; } public int ExitShortcut { get; set; } + /// + /// Opens Windows' Task View (Win + Tab), driven with the controller; 0 = turned off. Set from the start to + /// Select + X (Back | X), also for a config from before it existed; one that collides with another shortcut is dropped. + /// + public int TaskViewShortcut { get; set; } = 0x0020 | 0x4000; + + /// + /// A PlayStation controller drives Task View opened from the shortcut (Windows already does it for Xbox ones). + /// Off for whoever has a tool that makes the pad an Xbox one too (DS4Windows, Steam), where moves would repeat. + /// + public bool TaskViewPlayStation { get; set; } = true; + + /// How many times the Task View shortcut showed how to drive it before opening (it stops after a few). + public int TaskViewHintsShown { get; set; } /// The shortcuts setup (first run of the version that made them configurable) was finished or skipped. public bool ShortcutsOnboardingDone { get; set; } diff --git a/src/ConsoleMode/Resources/Strings.de-DE.json b/src/ConsoleMode/Resources/Strings.de-DE.json index f77d92a1..0ede3f52 100644 --- a/src/ConsoleMode/Resources/Strings.de-DE.json +++ b/src/ConsoleMode/Resources/Strings.de-DE.json @@ -84,6 +84,11 @@ "HomeButtonCard": "Controller-Tastenkombination zum Öffnen von Console Mode", "HomeButtonDescription": "Wenn die App im Infobereich läuft, halte diese Tastenkombination 1 Sekunde lang gedrückt, um den Konsolenmodus zu starten (ein kurzer Druck genügt, wenn du die Option für kurzes Drücken unten aktivierst). Funktioniert mit Xbox- und PlayStation-Controllern.", "ExitShortcutCard": "Controller-Tastenkombination für die Rückkehr zum PC", + "TaskViewShortcutCard": "Controller-Tastenkombination für „Aktive Anwendungen“", + "TaskViewShortcutDescription": "Öffnet „Aktive Anwendungen“ von Windows (Win + Tab) mit allen offenen Fenstern, in einer Sitzung oder außerhalb. Solange sie offen ist, wählen Steuerkreuz oder Stick ein Fenster, A öffnet es und B schließt die Ansicht; die Tastenkombination schließt sie ebenfalls.", + "TaskViewHint": "Steuerkreuz oder Stick wählt ein Fenster · {0} öffnet · {1} schließt", + "TaskViewPlayStationCard": "„Aktive Anwendungen“ mit einem PlayStation-Controller bedienen", + "TaskViewPlayStationDescription": "Windows bedient „Aktive Anwendungen“ bereits mit einem Xbox-Controller. Eingeschaltet macht Console Mode dasselbe mit einem PlayStation-Controller, den Windows dort nicht versteht. Schalte es aus, wenn ein Programm deinen Controller zu einem Xbox-Controller macht (DS4Windows, Steam) und sich Eingaben wiederholen.", "ExitShortcutDescription": "Halte diese Tastenkombination während einer Sitzung 1 Sekunde lang gedrückt, um deinen Desktop wiederherzustellen und zum PC zurückzukehren.", "ShortcutHome": "Console Mode öffnen", "ControllerSection": "Controller", @@ -94,6 +99,7 @@ "ControllerLayoutPlaystation": "PlayStation (✕, ○, □, △)", "ShortcutMenu": "Sitzungsmenü", "ShortcutExit": "Zurück zum PC", + "ShortcutTaskView": "Aktive Anwendungen", "ShortcutNotSet": "Nicht festgelegt", "ShortcutSet": "Festlegen", "ShortcutChange": "Ändern", diff --git a/src/ConsoleMode/Resources/Strings.en-US.json b/src/ConsoleMode/Resources/Strings.en-US.json index cef1b952..46d7077d 100644 --- a/src/ConsoleMode/Resources/Strings.en-US.json +++ b/src/ConsoleMode/Resources/Strings.en-US.json @@ -84,6 +84,11 @@ "HomeButtonCard": "Controller shortcut to open Console Mode", "HomeButtonDescription": "With the app in the tray, hold this shortcut for 1 second to enter console mode (a single press if you turn on the short press below). Works with Xbox and PlayStation controllers.", "ExitShortcutCard": "Controller shortcut to go back to the PC", + "TaskViewShortcutCard": "Controller shortcut for Task View", + "TaskViewShortcutDescription": "Opens Windows' Task View (Win + Tab) with all your open windows, in a session or not. While it is open, the D-pad or the stick picks a window, A opens it and B closes the view; the shortcut again closes it too.", + "TaskViewHint": "D-pad or stick picks a window · {0} opens it · {1} closes", + "TaskViewPlayStationCard": "Move around Task View with a PlayStation controller", + "TaskViewPlayStationDescription": "Windows already moves around Task View with an Xbox controller. On, Console Mode does the same with a PlayStation controller, which Windows doesn't understand there. Turn it off if a tool makes your controller an Xbox one (DS4Windows, Steam) and moves repeat.", "ExitShortcutDescription": "During a session, hold this shortcut for 1 second to restore your desk and go back to the PC.", "ShortcutHome": "Open Console Mode", "ControllerSection": "Controller", @@ -94,6 +99,7 @@ "ControllerLayoutPlaystation": "PlayStation (✕, ○, □, △)", "ShortcutMenu": "Session menu", "ShortcutExit": "Back to the PC", + "ShortcutTaskView": "Task View", "ShortcutNotSet": "Not set", "ShortcutSet": "Set", "ShortcutChange": "Change", diff --git a/src/ConsoleMode/Resources/Strings.es-ES.json b/src/ConsoleMode/Resources/Strings.es-ES.json index c45898b9..192949e6 100644 --- a/src/ConsoleMode/Resources/Strings.es-ES.json +++ b/src/ConsoleMode/Resources/Strings.es-ES.json @@ -84,6 +84,11 @@ "HomeButtonCard": "Atajo del mando para abrir Console Mode", "HomeButtonDescription": "Con la aplicación en la bandeja, mantén este atajo 1 segundo para entrar en modo consola (una sola pulsación si activas la pulsación corta de abajo). Funciona con mandos Xbox y PlayStation.", "ExitShortcutCard": "Atajo del mando para volver al PC", + "TaskViewShortcutCard": "Atajo del mando para la vista de tareas", + "TaskViewShortcutDescription": "Abre la vista de tareas de Windows (Win + Tab) con todas las ventanas abiertas, dentro o fuera de una sesión. Con ella abierta, la cruceta o el joystick eligen la ventana, A la abre y B cierra la vista; el atajo otra vez también la cierra.", + "TaskViewHint": "La cruceta o el joystick eligen la ventana · {0} la abre · {1} cierra", + "TaskViewPlayStationCard": "Moverse por la vista de tareas con un mando de PlayStation", + "TaskViewPlayStationDescription": "Windows ya permite moverse por la vista de tareas con un mando de Xbox. Activado, Console Mode hace lo mismo con un mando de PlayStation, que Windows no entiende ahí. Desactívalo si usas un programa que convierte el mando en uno de Xbox (DS4Windows, Steam) y los movimientos se repiten.", "ExitShortcutDescription": "Durante la sesión, mantén este atajo 1 segundo para restaurar el escritorio y volver al PC.", "ShortcutHome": "Abrir Console Mode", "ControllerSection": "Mando", @@ -94,6 +99,7 @@ "ControllerLayoutPlaystation": "PlayStation (✕, ○, □, △)", "ShortcutMenu": "Menú de la sesión", "ShortcutExit": "Volver al PC", + "ShortcutTaskView": "Vista de tareas", "ShortcutNotSet": "Sin definir", "ShortcutSet": "Definir", "ShortcutChange": "Cambiar", diff --git a/src/ConsoleMode/Resources/Strings.fr-FR.json b/src/ConsoleMode/Resources/Strings.fr-FR.json index f844e63c..4a519a24 100644 --- a/src/ConsoleMode/Resources/Strings.fr-FR.json +++ b/src/ConsoleMode/Resources/Strings.fr-FR.json @@ -84,6 +84,11 @@ "HomeButtonCard": "Raccourci manette pour ouvrir Console Mode", "HomeButtonDescription": "Avec l'application dans la zone de notification, maintenez ce raccourci pendant 1 seconde pour entrer en mode console (un simple appui si vous activez l'appui court ci-dessous). Fonctionne avec les manettes Xbox et PlayStation.", "ExitShortcutCard": "Raccourci manette pour revenir au PC", + "TaskViewShortcutCard": "Raccourci manette pour l'affichage des tâches", + "TaskViewShortcutDescription": "Ouvre l'affichage des tâches de Windows (Win + Tab) avec toutes les fenêtres ouvertes, en session ou non. Tant qu'il est ouvert, la croix ou le stick choisit la fenêtre, A l'ouvre et B ferme l'affichage ; le raccourci le ferme aussi.", + "TaskViewHint": "La croix ou le stick choisit la fenêtre · {0} l'ouvre · {1} ferme", + "TaskViewPlayStationCard": "Naviguer dans l'affichage des tâches avec une manette PlayStation", + "TaskViewPlayStationDescription": "Windows permet déjà de naviguer dans l'affichage des tâches avec une manette Xbox. Activé, Console Mode fait de même avec une manette PlayStation, que Windows ne comprend pas à cet endroit. Désactivez-le si un programme transforme votre manette en manette Xbox (DS4Windows, Steam) et que les commandes se répètent.", "ExitShortcutDescription": "Pendant une session, maintenez ce raccourci pendant 1 seconde pour restaurer votre bureau et revenir au PC.", "ShortcutHome": "Ouvrir Console Mode", "ControllerSection": "Manette", @@ -94,6 +99,7 @@ "ControllerLayoutPlaystation": "PlayStation (✕, ○, □, △)", "ShortcutMenu": "Menu de session", "ShortcutExit": "Retour au PC", + "ShortcutTaskView": "Affichage des tâches", "ShortcutNotSet": "Non défini", "ShortcutSet": "Définir", "ShortcutChange": "Modifier", diff --git a/src/ConsoleMode/Resources/Strings.pt-BR.json b/src/ConsoleMode/Resources/Strings.pt-BR.json index 4f3f5801..3e9910da 100644 --- a/src/ConsoleMode/Resources/Strings.pt-BR.json +++ b/src/ConsoleMode/Resources/Strings.pt-BR.json @@ -84,6 +84,11 @@ "HomeButtonCard": "Atalho do controle para abrir o Console Mode", "HomeButtonDescription": "Com o app na bandeja, segure este atalho por 1 segundo para entrar no modo console (um toque só, se você ligar o toque curto abaixo). Funciona com controles Xbox e PlayStation.", "ExitShortcutCard": "Atalho do controle para voltar ao PC", + "TaskViewShortcutCard": "Atalho do controle para a visão de tarefas", + "TaskViewShortcutDescription": "Abre a visão de tarefas do Windows (Win + Tab) com todas as janelas abertas, dentro ou fora de uma sessão. Com ela aberta, o direcional ou o analógico escolhe a janela, A abre e B fecha; o atalho de novo também fecha.", + "TaskViewHint": "Direcional ou analógico escolhe a janela · {0} abre · {1} fecha", + "TaskViewPlayStationCard": "Navegar na visão de tarefas com controle PlayStation", + "TaskViewPlayStationDescription": "O Windows já move a visão de tarefas com controle Xbox. Ligado, o Console Mode faz o mesmo com controle PlayStation, que o Windows não entende ali. Desligue se usar um programa que transforma o controle em Xbox (DS4Windows, Steam) e os comandos se repetirem.", "ExitShortcutDescription": "Durante a sessão, segure este atalho por 1 segundo para restaurar a mesa e voltar ao PC.", "ShortcutHome": "Abrir o Console Mode", "ControllerSection": "Controle", @@ -94,6 +99,7 @@ "ControllerLayoutPlaystation": "PlayStation (✕, ○, □, △)", "ShortcutMenu": "Menu da sessão", "ShortcutExit": "Voltar ao PC", + "ShortcutTaskView": "Visão de tarefas", "ShortcutNotSet": "Não definido", "ShortcutSet": "Definir", "ShortcutChange": "Alterar", diff --git a/src/ConsoleMode/Resources/Strings.ru-RU.json b/src/ConsoleMode/Resources/Strings.ru-RU.json index ec67c3cf..36b6ce21 100644 --- a/src/ConsoleMode/Resources/Strings.ru-RU.json +++ b/src/ConsoleMode/Resources/Strings.ru-RU.json @@ -84,6 +84,11 @@ "HomeButtonCard": "Сочетание на геймпаде для открытия Console Mode", "HomeButtonDescription": "Когда приложение в области уведомлений, удерживайте это сочетание 1 секунду, чтобы войти в режим консоли (или просто нажмите, если включите короткое нажатие ниже). Работает с геймпадами Xbox и PlayStation.", "ExitShortcutCard": "Сочетание на геймпаде для возврата к ПК", + "TaskViewShortcutCard": "Сочетание на геймпаде для представления задач", + "TaskViewShortcutDescription": "Открывает представление задач Windows (Win + Tab) со всеми открытыми окнами — в сеансе и вне его. Пока оно открыто, крестовина или стик выбирают окно, A открывает его, а B закрывает представление; повторное сочетание тоже закрывает его.", + "TaskViewHint": "Крестовина или стик выбирают окно · {0} открывает · {1} закрывает", + "TaskViewPlayStationCard": "Управлять представлением задач геймпадом PlayStation", + "TaskViewPlayStationDescription": "Windows уже позволяет управлять представлением задач геймпадом Xbox. Если включено, Console Mode делает то же для геймпада PlayStation, который Windows там не понимает. Выключите, если программа превращает геймпад в Xbox (DS4Windows, Steam) и команды повторяются.", "ExitShortcutDescription": "Во время сеанса удерживайте это сочетание 1 секунду, чтобы восстановить рабочее место и вернуться к ПК.", "ShortcutHome": "Открыть Console Mode", "ControllerSection": "Геймпад", @@ -94,6 +99,7 @@ "ControllerLayoutPlaystation": "PlayStation (✕, ○, □, △)", "ShortcutMenu": "Меню сеанса", "ShortcutExit": "Вернуться к ПК", + "ShortcutTaskView": "Представление задач", "ShortcutNotSet": "Не задано", "ShortcutSet": "Задать", "ShortcutChange": "Изменить", diff --git a/src/ConsoleMode/Services/ControllerShortcuts.cs b/src/ConsoleMode/Services/ControllerShortcuts.cs index 4ae98024..484949c8 100644 --- a/src/ConsoleMode/Services/ControllerShortcuts.cs +++ b/src/ConsoleMode/Services/ControllerShortcuts.cs @@ -8,7 +8,9 @@ public enum ShortcutSlot /// In a session: open the menu over the game. Menu, /// In a session: go back to the PC (restore the desk). - Exit + Exit, + /// Anytime: Windows' Task View (Win + Tab), driven with the controller while it is open. + TaskView } /// @@ -32,13 +34,14 @@ public static class ControllerShortcuts /// public const ushort Allowed = Guide | Start | Back | A | B | X | Y; - public static readonly ShortcutSlot[] Slots = [ShortcutSlot.Home, ShortcutSlot.Menu, ShortcutSlot.Exit]; + public static readonly ShortcutSlot[] Slots = [ShortcutSlot.Home, ShortcutSlot.Menu, ShortcutSlot.Exit, ShortcutSlot.TaskView]; /// The combo offered (never applied by itself) for each shortcut. public static ushort Suggested(ShortcutSlot slot) => slot switch { ShortcutSlot.Home => Guide, ShortcutSlot.Menu => Back | Y, + ShortcutSlot.TaskView => Back | X, _ => Start | Back }; diff --git a/src/ConsoleMode/Services/LocalizationService.cs b/src/ConsoleMode/Services/LocalizationService.cs index 552f685c..7801995f 100644 --- a/src/ConsoleMode/Services/LocalizationService.cs +++ b/src/ConsoleMode/Services/LocalizationService.cs @@ -205,6 +205,10 @@ internal void NotifyAll() public string ConsoleActiveHint => LocalizationService.Get(nameof(ConsoleActiveHint)); public string HomeButtonCard => LocalizationService.Get(nameof(HomeButtonCard)); public string ExitShortcutCard => LocalizationService.Get(nameof(ExitShortcutCard)); + public string TaskViewShortcutCard => LocalizationService.Get(nameof(TaskViewShortcutCard)); + public string TaskViewShortcutDescription => LocalizationService.Get(nameof(TaskViewShortcutDescription)); + public string TaskViewPlayStationCard => LocalizationService.Get(nameof(TaskViewPlayStationCard)); + public string TaskViewPlayStationDescription => LocalizationService.Get(nameof(TaskViewPlayStationDescription)); public string SoundsCard => LocalizationService.Get(nameof(SoundsCard)); public string IntroSoundCard => LocalizationService.Get(nameof(IntroSoundCard)); public string IntroSoundDescription => LocalizationService.Get(nameof(IntroSoundDescription)); diff --git a/src/ConsoleMode/Services/TaskViewDriver.cs b/src/ConsoleMode/Services/TaskViewDriver.cs new file mode 100644 index 00000000..81dc1519 --- /dev/null +++ b/src/ConsoleMode/Services/TaskViewDriver.cs @@ -0,0 +1,179 @@ +using System.Diagnostics; +using System.Runtime.InteropServices; + +namespace ConsoleMode.Services; + +/// +/// The Task View shortcut: opens Windows' Task View (Win + Tab) and, while it is open, lets a PlayStation controller +/// drive it with the keys it understands (: arrows, Enter, Escape). Windows already moves +/// Task View with an Xbox (XInput) controller, so those are left to it (driving them too sent every move twice); +/// Sony pads, which Windows doesn't understand there, are read over HID on this driver's own thread, without the focus. It stops when A or B closes Task View, when +/// something else does (a click, the keyboard), or after a while; and at once if Task View never took the +/// foreground, so the controller never types into the game behind it. +/// +public sealed class TaskViewDriver : IDisposable +{ + private static readonly TimeSpan SampleInterval = TimeSpan.FromMilliseconds(16); + /// Task View takes the foreground within this; after it, a different foreground window means it closed. + private static readonly TimeSpan SettleTime = TimeSpan.FromMilliseconds(350); + private static readonly TimeSpan LongestOpen = TimeSpan.FromMinutes(2); + + private CancellationTokenSource? _cts; + private Thread? _thread; + + /// Raised on the driver's thread once it stops driving Task View. + public event Action? Stopped; + + public bool IsRunning => _cts is not null; + + /// System → Controller: a PlayStation controller drives Task View (on by default). + public bool DrivePlayStation + { + get => _drivePlayStation; + set => _drivePlayStation = value; + } + + private volatile bool _drivePlayStation = true; + + /// Opens Task View and starts driving it; with Task View already open from here, closes it instead. + public void Toggle() + { + if (IsRunning) + { + SendKey(VkEscape); + Stop(); + return; + } + var before = GetForegroundWindow(); + SendWinTab(); + AppLog.Write("Visão de tarefas: aberta pelo controle"); + SonyHidReader.Acquire(); + var cts = new CancellationTokenSource(); + _cts = cts; + _thread = new Thread(() => Run(before, cts)) { IsBackground = true, Name = "TaskViewDriver" }; + _thread.Start(); + } + + public void Stop() + { + if (_cts is not { } cts) return; + _cts = null; + cts.Cancel(); + if (Thread.CurrentThread != _thread) _thread?.Join(500); + _thread = null; + } + + public void Dispose() => Stop(); + + private void Run(nint before, CancellationTokenSource run) + { + var ct = run.Token; + var keys = new TaskViewKeys(); + var clock = Stopwatch.StartNew(); + nint view = 0; + var why = "tempo esgotado"; + try + { + while (!ct.IsCancellationRequested && clock.Elapsed < LongestOpen) + { + Thread.Sleep(SampleInterval); + var foreground = GetForegroundWindow(); + if (view == 0) + { + if (clock.Elapsed < SettleTime) continue; + if (foreground == before || foreground == 0) + { + why = "não ficou em primeiro plano"; + break; + } + view = foreground; + } + else if (foreground != view) + { + why = "fechada"; + break; + } + + var ended = false; + if (!_drivePlayStation) continue; + foreach (var key in keys.Step(Read(), clock.Elapsed)) + { + SendKey(key switch + { + TaskViewKey.Left => VkLeft, + TaskViewKey.Right => VkRight, + TaskViewKey.Up => VkUp, + TaskViewKey.Down => VkDown, + TaskViewKey.Enter => VkReturn, + _ => VkEscape + }); + ended |= key is TaskViewKey.Enter or TaskViewKey.Escape; + } + if (ended) + { + why = "escolha feita"; + break; + } + } + if (ct.IsCancellationRequested) why = "fechada pelo atalho"; + } + catch (Exception ex) + { + why = ex.Message; + } + finally + { + SonyHidReader.Release(); + AppLog.Write($"Visão de tarefas: controle solto ({why})"); + // Only this run: a new one may already have started. + Interlocked.CompareExchange(ref _cts, null, run); + Stopped?.Invoke(); + } + } + + /// The PlayStation pads (Sony HID): buttons from all of them, the left stick pushed furthest. + private static TaskViewPad Read() + { + double x = 0, y = 0; + foreach (var s in SonyHidReader.ReadSticks()) + { + var sx = ControllerMouseMath.FromHidByte(s.LeftX, false); + var sy = ControllerMouseMath.FromHidByte(s.LeftY, true); + if (sx * sx + sy * sy > x * x + y * y) { x = sx; y = sy; } + } + return new TaskViewPad(SonyHidReader.Held, x, y); + } + + private const byte VkLeftWin = 0x5B; + private const byte VkTab = 0x09; + private const byte VkReturn = 0x0D; + private const byte VkEscape = 0x1B; + private const byte VkLeft = 0x25; + private const byte VkUp = 0x26; + private const byte VkRight = 0x27; + private const byte VkDown = 0x28; + private const uint KeyEventExtended = 0x0001; + private const uint KeyEventUp = 0x0002; + + private static void SendWinTab() + { + keybd_event(VkLeftWin, 0, KeyEventExtended, 0); + keybd_event(VkTab, 0, 0, 0); + keybd_event(VkTab, 0, KeyEventUp, 0); + keybd_event(VkLeftWin, 0, KeyEventExtended | KeyEventUp, 0); + } + + /// One key press; the arrows are extended keys (the ones outside the numeric keypad). + private static void SendKey(byte key) + { + var flags = key is VkLeft or VkUp or VkRight or VkDown ? KeyEventExtended : 0; + keybd_event(key, 0, flags, 0); + keybd_event(key, 0, flags | KeyEventUp, 0); + } + + [DllImport("user32.dll")] + private static extern nint GetForegroundWindow(); + + [DllImport("user32.dll")] + private static extern void keybd_event(byte key, byte scan, uint flags, nuint extraInfo); +} diff --git a/src/ConsoleMode/Services/TaskViewKeys.cs b/src/ConsoleMode/Services/TaskViewKeys.cs new file mode 100644 index 00000000..2ba06207 --- /dev/null +++ b/src/ConsoleMode/Services/TaskViewKeys.cs @@ -0,0 +1,96 @@ +namespace ConsoleMode.Services; + +/// A key the controller stands for while Windows' Task View is open. +public enum TaskViewKey +{ + Left, + Right, + Up, + Down, + /// A: opens the window in focus (and Task View closes). + Enter, + /// B: closes Task View, back to where you were. + Escape +} + +/// What the controller does at one moment, from any pad (XInput bits; a Sony pad's left stick sets the D-pad bits too). +public readonly record struct TaskViewPad(ushort Buttons, double StickX, double StickY); + +/// +/// Turns the controller into the keys Task View understands: the D-pad and the left stick move (a held direction +/// repeats, like a held arrow key), A is Enter and B is Escape. Nothing counts until every button has been let go +/// once: the shortcut that opened Task View is usually still held. Pure, so it is tested. +/// +public sealed class TaskViewKeys +{ + public const ushort DpadUp = 0x0001; + public const ushort DpadDown = 0x0002; + public const ushort DpadLeft = 0x0004; + public const ushort DpadRight = 0x0008; + public const ushort A = 0x1000; + public const ushort B = 0x2000; + + /// How far the stick goes (0 to 1) before it counts as a direction. + public const double StickThreshold = 0.55; + public static readonly TimeSpan RepeatDelay = TimeSpan.FromMilliseconds(420); + public static readonly TimeSpan RepeatInterval = TimeSpan.FromMilliseconds(140); + + private bool _armed; + private TaskViewKey? _direction; + private TimeSpan _nextRepeat; + private bool _aDown; + private bool _bDown; + + /// The keys to send for this sample, taken at . + public IReadOnlyList Step(TaskViewPad pad, TimeSpan now) + { + var keys = new List(); + var direction = Direction(pad); + var a = (pad.Buttons & A) != 0; + var b = (pad.Buttons & B) != 0; + + if (!_armed) + { + if (pad.Buttons != 0 || direction is not null) return keys; + _armed = true; + return keys; + } + + if (direction != _direction) + { + _direction = direction; + if (direction is { } pressed) + { + keys.Add(pressed); + _nextRepeat = now + RepeatDelay; + } + } + else if (direction is { } held && now >= _nextRepeat) + { + keys.Add(held); + _nextRepeat = now + RepeatInterval; + } + + // A and B act when pressed, once per press. + if (a && !_aDown) keys.Add(TaskViewKey.Enter); + if (b && !_bDown) keys.Add(TaskViewKey.Escape); + _aDown = a; + _bDown = b; + return keys; + } + + /// The D-pad first; otherwise the stick, along its stronger axis once it is pushed far enough. + public static TaskViewKey? Direction(TaskViewPad pad) + { + if ((pad.Buttons & DpadLeft) != 0) return TaskViewKey.Left; + if ((pad.Buttons & DpadRight) != 0) return TaskViewKey.Right; + if ((pad.Buttons & DpadUp) != 0) return TaskViewKey.Up; + if ((pad.Buttons & DpadDown) != 0) return TaskViewKey.Down; + var x = pad.StickX; + var y = pad.StickY; + if (Math.Max(Math.Abs(x), Math.Abs(y)) < StickThreshold) return null; + if (Math.Abs(x) >= Math.Abs(y)) return x < 0 ? TaskViewKey.Left : TaskViewKey.Right; + // Stick up is positive. + return y > 0 ? TaskViewKey.Up : TaskViewKey.Down; + } +} diff --git a/src/ConsoleMode/ViewModels/MainViewModel.ConsoleUi.cs b/src/ConsoleMode/ViewModels/MainViewModel.ConsoleUi.cs index 5a91a3a2..6518224f 100644 --- a/src/ConsoleMode/ViewModels/MainViewModel.ConsoleUi.cs +++ b/src/ConsoleMode/ViewModels/MainViewModel.ConsoleUi.cs @@ -166,6 +166,8 @@ private void CycleSetting(string spec) case "home": ToggleSuggestedShortcut(ShortcutSlot.Home); break; case "menushortcut": ToggleSuggestedShortcut(ShortcutSlot.Menu); break; case "exitshortcut": ToggleSuggestedShortcut(ShortcutSlot.Exit); break; + case "taskviewshortcut": ToggleSuggestedShortcut(ShortcutSlot.TaskView); break; + case "taskviewplaystation": TaskViewPlayStation = !TaskViewPlayStation; break; case "shortpress": HomeButtonShortPress = !HomeButtonShortPress; break; case "autostart": AutoStartOnController = !AutoStartOnController; break; case "controllerwake": _ = EnableControllerWakeAsync(); break; @@ -207,6 +209,7 @@ private void OpenShortcutEditor(string slot) "home" => ShortcutSlot.Home, "menu" => ShortcutSlot.Menu, "exit" => ShortcutSlot.Exit, + "taskview" => ShortcutSlot.TaskView, _ => (ShortcutSlot?)null }; if (target is null) return; diff --git a/src/ConsoleMode/ViewModels/MainViewModel.Pointer.cs b/src/ConsoleMode/ViewModels/MainViewModel.Pointer.cs index b4c70bf2..8f1973c5 100644 --- a/src/ConsoleMode/ViewModels/MainViewModel.Pointer.cs +++ b/src/ConsoleMode/ViewModels/MainViewModel.Pointer.cs @@ -63,8 +63,8 @@ private void UpdateSessionPointer() { CursorHider.SetHidden(IsCursorHidden); - // While the menu or the main window is up the pad drives it, not the mouse. - _controllerMouse.Paused = IsSessionMenuOpen || IsMainWindowActive; + // While the menu, the main window or Task View (from the shortcut) is up the pad drives it, not the mouse. + _controllerMouse.Paused = IsSessionMenuOpen || IsMainWindowActive || IsTaskViewOpen; if (IsControllerMouseOn) _controllerMouse.Start((IsConsoleActive ? Engine.State.FocusMonitorRect : Engine.Monitors.GetMonitorRect(SessionMonitorName, Engine.State))?.Height ?? 1080); else diff --git a/src/ConsoleMode/ViewModels/MainViewModel.Shortcuts.cs b/src/ConsoleMode/ViewModels/MainViewModel.Shortcuts.cs index 55d6743d..d145149c 100644 --- a/src/ConsoleMode/ViewModels/MainViewModel.Shortcuts.cs +++ b/src/ConsoleMode/ViewModels/MainViewModel.Shortcuts.cs @@ -3,7 +3,7 @@ namespace ConsoleMode.ViewModels; -// The controller shortcuts the user picks (Home, session menu, back to the PC). Nothing is set +// The controller shortcuts the user picks (Home, session menu, back to the PC, Task View). Nothing is set // until they choose in the first-run setup or in Settings; a combo can serve one purpose only. public partial class MainViewModel { @@ -18,6 +18,7 @@ public partial class MainViewModel public bool HomeShortcutSet => _shortcuts[(int)ShortcutSlot.Home] != 0; public bool ExitShortcutSet => _shortcuts[(int)ShortcutSlot.Exit] != 0; public bool MenuShortcutSet => _shortcuts[(int)ShortcutSlot.Menu] != 0; + public bool TaskViewShortcutSet => _shortcuts[(int)ShortcutSlot.TaskView] != 0; /// True while a "press the buttons you want" capture is running: no shortcut may fire. public bool IsCapturingShortcut => _shortcutCaptures > 0; @@ -37,12 +38,14 @@ public string ShortcutText(ShortcutSlot slot) { ShortcutSlot.Home => "ShortcutHome", ShortcutSlot.Menu => "ShortcutMenu", + ShortcutSlot.TaskView => "ShortcutTaskView", _ => "ShortcutExit" }); public string HomeShortcutText => ShortcutText(ShortcutSlot.Home); public string MenuShortcutText => ShortcutText(ShortcutSlot.Menu); public string ExitShortcutText => ShortcutText(ShortcutSlot.Exit); + public string TaskViewShortcutText => ShortcutText(ShortcutSlot.TaskView); /// The "or hold … to go back" line on the console screen; empty when the shortcut isn't set. public string ConsoleActiveHintText => ExitShortcutSet @@ -112,6 +115,7 @@ private void LoadShortcuts(AppConfig config) _shortcuts[(int)ShortcutSlot.Home] = ControllerShortcuts.Sanitize(config.HomeShortcut); _shortcuts[(int)ShortcutSlot.Menu] = ControllerShortcuts.Sanitize(config.MenuShortcut); _shortcuts[(int)ShortcutSlot.Exit] = ControllerShortcuts.Sanitize(config.ExitShortcut); + _shortcuts[(int)ShortcutSlot.TaskView] = ControllerShortcuts.Sanitize(config.TaskViewShortcut); // A hand-edited file could give one combo two jobs: the later one is dropped. foreach (var slot in ControllerShortcuts.Slots) { @@ -143,9 +147,11 @@ private void NotifyShortcutTexts() OnPropertyChanged(nameof(HomeShortcutSet)); OnPropertyChanged(nameof(MenuShortcutSet)); OnPropertyChanged(nameof(ExitShortcutSet)); + OnPropertyChanged(nameof(TaskViewShortcutSet)); OnPropertyChanged(nameof(HomeShortcutText)); OnPropertyChanged(nameof(MenuShortcutText)); OnPropertyChanged(nameof(ExitShortcutText)); + OnPropertyChanged(nameof(TaskViewShortcutText)); OnPropertyChanged(nameof(ConsoleActiveHintText)); OnPropertyChanged(ShortcutsProperty); } diff --git a/src/ConsoleMode/ViewModels/MainViewModel.TaskView.cs b/src/ConsoleMode/ViewModels/MainViewModel.TaskView.cs new file mode 100644 index 00000000..2f6412dd --- /dev/null +++ b/src/ConsoleMode/ViewModels/MainViewModel.TaskView.cs @@ -0,0 +1,107 @@ +using CommunityToolkit.Mvvm.ComponentModel; +using ConsoleMode.Services; + +namespace ConsoleMode.ViewModels; + +// The Task View shortcut: Windows' Win + Tab from the controller, in a session or not. Windows moves Task View with an +// Xbox controller itself; a PlayStation one is driven from here while it is open (TaskViewDriver, optional). The +// controller mouse waits meanwhile, so the stick moves the selection, not the pointer. +// The first few times, a toast shows how to drive it before it opens: nothing of ours can show over Task View +// (Windows draws it above every always-on-top window), so the hint comes first and Task View a moment later. +public partial class MainViewModel +{ + /// The first uses that show how to drive Task View before it opens; after them it opens at once. + private const int TaskViewHintUses = 3; + private static readonly TimeSpan TaskViewHintLead = TimeSpan.FromMilliseconds(1600); + + private readonly TaskViewDriver _taskView = new(); + private bool _taskViewHooked; + private bool _taskViewPending; + private int _taskViewHintsShown; + + /// Task View is open from the shortcut and the pad is driving it. + [ObservableProperty] private bool _isTaskViewOpen; + + partial void OnIsTaskViewOpenChanged(bool value) => UpdateSessionPointer(); + + /// System → Controller: a PlayStation controller drives Task View (Windows already does it for Xbox ones). + [ObservableProperty] private bool _taskViewPlayStation = true; + + partial void OnTaskViewPlayStationChanged(bool value) + { + _taskView.DrivePlayStation = value; + SaveQuietly(); + } + + /// The shortcut: opens Task View, or closes it when it was opened from here. + public void ToggleTaskView() + { + if (!_taskViewHooked) + { + _taskViewHooked = true; + _taskView.Stopped += () => _dispatcher.TryEnqueue(() => IsTaskViewOpen = _taskView.IsRunning); + } + // Already on its way (the hint is showing): one press is enough. + if (_taskViewPending) return; + if (_taskView.IsRunning) + { + RunTaskView(); + return; + } + // The session menu sits on top of everything: Task View opens instead of it. + if (IsSessionMenuOpen) CloseSessionMenu(); + if (_taskViewHintsShown >= TaskViewHintUses) + { + RunTaskView(); + return; + } + + _taskViewHintsShown++; + SaveQuietly(); + ShowTaskViewHint(); + _taskViewPending = true; + var timer = _dispatcher.CreateTimer(); + timer.Interval = TaskViewHintLead; + timer.IsRepeating = false; + timer.Tick += (_, _) => + { + timer.Stop(); + _taskViewPending = false; + RunTaskView(); + }; + timer.Start(); + } + + private void RunTaskView() + { + try + { + _taskView.Toggle(); + } + catch (Exception ex) + { + AppLog.Write($"Visão de tarefas: {ex.Message}"); + } + IsTaskViewOpen = _taskView.IsRunning; + } + + /// "Task View: the D-pad or stick picks a window · A opens · B closes", with the buttons of the pad in use. + private void ShowTaskViewHint() + { + try + { + var screen = IsConsoleActive + ? Engine.State.FocusMonitorRect + : Engine.Monitors.GetMonitorRect(SessionMonitorName, Engine.State); + // Long enough to read before Task View covers it; it slides out behind Task View. + _ = new SessionHintWindow(LocalizationService.Get("ShortcutTaskView"), + LocalizationService.Get("TaskViewHint", HintConfirm, HintBack), + screen, TaskViewHintLead + TimeSpan.FromMilliseconds(400), glyph: ""); + AppLog.Write($"Visão de tarefas: dica exibida ({_taskViewHintsShown}/{TaskViewHintUses})"); + } + catch (Exception ex) + { + AppLog.Write($"Visão de tarefas: dica: {ex.Message}"); + } + } +} diff --git a/src/ConsoleMode/ViewModels/MainViewModel.cs b/src/ConsoleMode/ViewModels/MainViewModel.cs index 794cc174..069accbf 100644 --- a/src/ConsoleMode/ViewModels/MainViewModel.cs +++ b/src/ConsoleMode/ViewModels/MainViewModel.cs @@ -352,6 +352,8 @@ private void Apply(LoadResult data) _introStyleChosen = !string.IsNullOrWhiteSpace(config.IntroStyle) || !config.IntroAnimation; MinimizeToTray = config.MinimizeToTray; MenuOutsideSession = config.MenuOutsideSession; + _taskViewHintsShown = config.TaskViewHintsShown; + TaskViewPlayStation = config.TaskViewPlayStation; ConsoleBackgroundMode = ConsoleBackgroundService.NormalizeMode(config.ConsoleBackground); ConsoleBackgroundImage = config.ConsoleBackgroundImage ?? ""; CloseSteamOnRestore = config.CloseSteamOnRestore; @@ -903,6 +905,9 @@ private AppConfig BuildConfig() HomeShortcut = _shortcuts[(int)ShortcutSlot.Home], MenuShortcut = _shortcuts[(int)ShortcutSlot.Menu], ExitShortcut = _shortcuts[(int)ShortcutSlot.Exit], + TaskViewShortcut = _shortcuts[(int)ShortcutSlot.TaskView], + TaskViewHintsShown = _taskViewHintsShown, + TaskViewPlayStation = TaskViewPlayStation, ShortcutsOnboardingDone = _loadedConfig.ShortcutsOnboardingDone, HomeButtonShortPress = HomeButtonShortPress, AutoStartOnController = AutoStartOnController, diff --git a/src/ConsoleMode/Views/ConsoleHomeView.xaml b/src/ConsoleMode/Views/ConsoleHomeView.xaml index b4b7b25d..bc09546b 100644 --- a/src/ConsoleMode/Views/ConsoleHomeView.xaml +++ b/src/ConsoleMode/Views/ConsoleHomeView.xaml @@ -695,6 +695,18 @@ + +