From a9355e0b44b1c3b21ee08fd687051936e1ddd249 Mon Sep 17 00:00:00 2001 From: Filipe Moreira Date: Sun, 1 Nov 2026 02:39:18 -0300 Subject: [PATCH 1/4] feat: controller shortcut for Windows' Task View A fourth controller shortcut, set in System -> Controller like the others, does what Win + Tab does: it opens Windows' Task View, in a session or not. While it is open the pad drives it (TaskViewDriver, on its own thread, XInput and Sony HID): the D-pad or the left stick send arrow keys (a held direction repeats), A sends Enter and B Escape, and the shortcut again closes it. Nothing counts until the shortcut's buttons are let go (TaskViewKeys). It stops when Task View closes by any means, after two minutes, or at once if Task View never took the foreground, so the pad never types into the game. The controller mouse waits meanwhile; the session menu closes first. Suggested combo: Select + X (free of the other three). The Xbox button alone works as a held shortcut (600 ms) when it isn't the Home shortcut. Co-Authored-By: Claude Opus 5.5 --- src/ConsoleMode/App.xaml.cs | 10 +- src/ConsoleMode/Models/Models.cs | 2 + src/ConsoleMode/Resources/Strings.de-DE.json | 3 + src/ConsoleMode/Resources/Strings.en-US.json | 3 + src/ConsoleMode/Resources/Strings.es-ES.json | 3 + src/ConsoleMode/Resources/Strings.fr-FR.json | 3 + src/ConsoleMode/Resources/Strings.pt-BR.json | 3 + src/ConsoleMode/Resources/Strings.ru-RU.json | 3 + .../Services/ControllerShortcuts.cs | 7 +- .../Services/LocalizationService.cs | 2 + src/ConsoleMode/Services/TaskViewDriver.cs | 211 ++++++++++++++++++ src/ConsoleMode/Services/TaskViewKeys.cs | 96 ++++++++ .../ViewModels/MainViewModel.ConsoleUi.cs | 2 + .../ViewModels/MainViewModel.Pointer.cs | 4 +- .../ViewModels/MainViewModel.Shortcuts.cs | 8 +- .../ViewModels/MainViewModel.TaskView.cs | 38 ++++ src/ConsoleMode/ViewModels/MainViewModel.cs | 1 + src/ConsoleMode/Views/ConsoleHomeView.xaml | 13 +- src/ConsoleMode/Views/ConsoleHomeView.xaml.cs | 4 + .../ConsoleMode.Tests.csproj | 1 + .../ControllerShortcutsTests.cs | 2 +- tests/ConsoleMode.Tests/TaskViewKeysTests.cs | 89 ++++++++ 22 files changed, 499 insertions(+), 9 deletions(-) create mode 100644 src/ConsoleMode/Services/TaskViewDriver.cs create mode 100644 src/ConsoleMode/Services/TaskViewKeys.cs create mode 100644 src/ConsoleMode/ViewModels/MainViewModel.TaskView.cs create mode 100644 tests/ConsoleMode.Tests/TaskViewKeysTests.cs 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..1bb83c23 100644 --- a/src/ConsoleMode/Models/Models.cs +++ b/src/ConsoleMode/Models/Models.cs @@ -70,6 +70,8 @@ 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 = not set. + public int TaskViewShortcut { 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..fd30bdde 100644 --- a/src/ConsoleMode/Resources/Strings.de-DE.json +++ b/src/ConsoleMode/Resources/Strings.de-DE.json @@ -84,6 +84,8 @@ "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.", "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 +96,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..cee738fb 100644 --- a/src/ConsoleMode/Resources/Strings.en-US.json +++ b/src/ConsoleMode/Resources/Strings.en-US.json @@ -84,6 +84,8 @@ "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.", "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 +96,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..a7a1bcba 100644 --- a/src/ConsoleMode/Resources/Strings.es-ES.json +++ b/src/ConsoleMode/Resources/Strings.es-ES.json @@ -84,6 +84,8 @@ "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.", "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 +96,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..58cc8429 100644 --- a/src/ConsoleMode/Resources/Strings.fr-FR.json +++ b/src/ConsoleMode/Resources/Strings.fr-FR.json @@ -84,6 +84,8 @@ "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.", "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 +96,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..aa0fe4a9 100644 --- a/src/ConsoleMode/Resources/Strings.pt-BR.json +++ b/src/ConsoleMode/Resources/Strings.pt-BR.json @@ -84,6 +84,8 @@ "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.", "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 +96,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..5fac9084 100644 --- a/src/ConsoleMode/Resources/Strings.ru-RU.json +++ b/src/ConsoleMode/Resources/Strings.ru-RU.json @@ -84,6 +84,8 @@ "HomeButtonCard": "Сочетание на геймпаде для открытия Console Mode", "HomeButtonDescription": "Когда приложение в области уведомлений, удерживайте это сочетание 1 секунду, чтобы войти в режим консоли (или просто нажмите, если включите короткое нажатие ниже). Работает с геймпадами Xbox и PlayStation.", "ExitShortcutCard": "Сочетание на геймпаде для возврата к ПК", + "TaskViewShortcutCard": "Сочетание на геймпаде для представления задач", + "TaskViewShortcutDescription": "Открывает представление задач Windows (Win + Tab) со всеми открытыми окнами — в сеансе и вне его. Пока оно открыто, крестовина или стик выбирают окно, A открывает его, а B закрывает представление; повторное сочетание тоже закрывает его.", "ExitShortcutDescription": "Во время сеанса удерживайте это сочетание 1 секунду, чтобы восстановить рабочее место и вернуться к ПК.", "ShortcutHome": "Открыть Console Mode", "ControllerSection": "Геймпад", @@ -94,6 +96,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..9ff6fa90 100644 --- a/src/ConsoleMode/Services/LocalizationService.cs +++ b/src/ConsoleMode/Services/LocalizationService.cs @@ -205,6 +205,8 @@ 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 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..256666fe --- /dev/null +++ b/src/ConsoleMode/Services/TaskViewDriver.cs @@ -0,0 +1,211 @@ +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 the controller drive it +/// with the keys it understands (: arrows, Enter, Escape). Reads XInput and Sony HID on its +/// own thread, like the controller mouse, since neither needs 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; + private static bool _xinputMissing; + + /// Raised on the driver's thread once it stops driving Task View. + public event Action? Stopped; + + public bool IsRunning => _cts is not null; + + /// 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; + 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(); + } + } + + /// Every pad at once: buttons from all of them, the stick pushed furthest. + private static TaskViewPad Read() + { + ushort buttons = 0; + double x = 0, y = 0; + + void Take(double sx, double sy) + { + if (sx * sx + sy * sy > x * x + y * y) { x = sx; y = sy; } + } + + if (!_xinputMissing) + { + try + { + for (uint i = 0; i < 4; i++) + { + if (XInputGetState(i, out var state) != 0) continue; + buttons |= state.Gamepad.wButtons; + Take(ControllerMouseMath.FromXInput(state.Gamepad.sThumbLX), ControllerMouseMath.FromXInput(state.Gamepad.sThumbLY)); + } + } + catch (DllNotFoundException) + { + _xinputMissing = true; + } + } + buttons |= SonyHidReader.Held; + foreach (var s in SonyHidReader.ReadSticks()) + Take(ControllerMouseMath.FromHidByte(s.LeftX, false), ControllerMouseMath.FromHidByte(s.LeftY, true)); + return new TaskViewPad(buttons, 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); + } + + [StructLayout(LayoutKind.Sequential)] + private struct XInputGamepad + { + public ushort wButtons; + public byte bLeftTrigger; + public byte bRightTrigger; + public short sThumbLX; + public short sThumbLY; + public short sThumbRX; + public short sThumbRY; + } + + [StructLayout(LayoutKind.Sequential)] + private struct XInputState + { + public uint dwPacketNumber; + public XInputGamepad Gamepad; + } + + [DllImport("xinput1_4.dll", EntryPoint = "XInputGetState")] + private static extern uint XInputGetState(uint userIndex, out XInputState state); + + [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..2d3154dd 100644 --- a/src/ConsoleMode/ViewModels/MainViewModel.ConsoleUi.cs +++ b/src/ConsoleMode/ViewModels/MainViewModel.ConsoleUi.cs @@ -166,6 +166,7 @@ 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 "shortpress": HomeButtonShortPress = !HomeButtonShortPress; break; case "autostart": AutoStartOnController = !AutoStartOnController; break; case "controllerwake": _ = EnableControllerWakeAsync(); break; @@ -207,6 +208,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..90c71dfc --- /dev/null +++ b/src/ConsoleMode/ViewModels/MainViewModel.TaskView.cs @@ -0,0 +1,38 @@ +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, driven with the pad while it +// is open (TaskViewDriver). The controller mouse waits meanwhile, so the stick moves the selection, not the pointer. +public partial class MainViewModel +{ + private readonly TaskViewDriver _taskView = new(); + private bool _taskViewHooked; + + /// Task View is open from the shortcut and the pad is driving it. + [ObservableProperty] private bool _isTaskViewOpen; + + partial void OnIsTaskViewOpenChanged(bool value) => UpdateSessionPointer(); + + /// 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); + } + // The session menu sits on top of everything: Task View opens instead of it. + if (!_taskView.IsRunning && IsSessionMenuOpen) CloseSessionMenu(); + try + { + _taskView.Toggle(); + } + catch (Exception ex) + { + AppLog.Write($"Visão de tarefas: {ex.Message}"); + } + IsTaskViewOpen = _taskView.IsRunning; + } +} diff --git a/src/ConsoleMode/ViewModels/MainViewModel.cs b/src/ConsoleMode/ViewModels/MainViewModel.cs index 794cc174..be91104c 100644 --- a/src/ConsoleMode/ViewModels/MainViewModel.cs +++ b/src/ConsoleMode/ViewModels/MainViewModel.cs @@ -903,6 +903,7 @@ private AppConfig BuildConfig() HomeShortcut = _shortcuts[(int)ShortcutSlot.Home], MenuShortcut = _shortcuts[(int)ShortcutSlot.Menu], ExitShortcut = _shortcuts[(int)ShortcutSlot.Exit], + TaskViewShortcut = _shortcuts[(int)ShortcutSlot.TaskView], ShortcutsOnboardingDone = _loadedConfig.ShortcutsOnboardingDone, HomeButtonShortPress = HomeButtonShortPress, AutoStartOnController = AutoStartOnController, diff --git a/src/ConsoleMode/Views/ConsoleHomeView.xaml b/src/ConsoleMode/Views/ConsoleHomeView.xaml index 3fe64b30..d65d7755 100644 --- a/src/ConsoleMode/Views/ConsoleHomeView.xaml +++ b/src/ConsoleMode/Views/ConsoleHomeView.xaml @@ -695,6 +695,12 @@ + +