using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Threading; using Avalonia.VisualTree; namespace QuiverLauncher.Services; public sealed class GamepadModalDialogNavigation { private static GamepadModalDialogNavigation? _instance; private readonly List _dialogStack = []; private readonly Dictionary> _questionResultCallbacks = new(); private readonly HashSet _keyboardAttachedDialogs = []; private List _dialogControls = []; private int _focusedControlIndex; /// Last ListBox row cursor while focus is on dialog buttons (selection cleared for chrome). private int _listBoxCursorIndex = -1; private InputService? _inputService; private readonly EventHandler _dialogControlPointerEntered; private readonly EventHandler _dialogKeyDownHandler; private readonly EventHandler _dialogKeyUpHandler; public static GamepadModalDialogNavigation Instance => _instance ??= new GamepadModalDialogNavigation(); public bool HasActiveDialog => _dialogStack.Count > 0; public Window? ActiveDialog => _dialogStack.Count > 0 ? _dialogStack[^1] : null; public int DialogStackCount => _dialogStack.Count; /// /// Resolves a key press to a using the app's keyboard bindings. /// public Func? ResolveKeyboardAction { get; set; } /// /// Called when keyboard navigation is used on a modal so focus chrome can activate. /// public Action? OnKeyboardNavigationActivated { get; set; } public GamepadModalDialogNavigation() { _dialogControlPointerEntered = OnDialogControlPointerEntered; _dialogKeyDownHandler = OnDialogKeyDown; _dialogKeyUpHandler = OnDialogKeyUp; } public void Configure(InputService inputService) { _inputService = inputService; } /// /// Syncs gamepad-chrome on all open modal dialog windows. /// public void SyncChromeClass(bool active) { foreach (var dialog in _dialogStack) GamepadFocusChrome.ApplyToWindow(dialog, active); } public static void Attach(Window dialog) => Attach(dialog, setQuestionResult: null); public static void Attach(Window dialog, Action? setQuestionResult) { Instance.PrepareDialog(dialog, setQuestionResult); } public void PrepareDialog(Window dialog, Action? setQuestionResult = null) { if (setQuestionResult != null) _questionResultCallbacks[dialog] = setQuestionResult; else _questionResultCallbacks.Remove(dialog); if (_dialogStack.Contains(dialog)) { BringToTop(dialog); AttachDialogKeyboardHandlers(dialog); RefreshDialogButtons(); return; } _dialogStack.Add(dialog); AttachDialogKeyboardHandlers(dialog); XyFocusNavigation.EnableOnForDialog(dialog); dialog.FocusAdorner = null; GamepadFocusChrome.ApplyToWindow(dialog, GamepadFocusChrome.IsActive); RefreshDialogButtons(); void OnDialogOpened(object? sender, EventArgs e) { if (!ReferenceEquals(ActiveDialog, dialog)) return; RefreshDialogButtons(); void OnLayoutUpdated(object? s, EventArgs args) { if (!ReferenceEquals(ActiveDialog, dialog)) return; RefreshDialogButtons(); dialog.LayoutUpdated -= OnLayoutUpdated; } dialog.LayoutUpdated += OnLayoutUpdated; } void OnDialogClosed(object? sender, EventArgs e) { dialog.Opened -= OnDialogOpened; dialog.Closed -= OnDialogClosed; UnregisterModalDialog(dialog); } dialog.Opened += OnDialogOpened; dialog.Closed += OnDialogClosed; } public void RefreshDialogButtons() { var activeDialog = ActiveDialog; if (activeDialog == null) return; GamepadFocusChrome.ApplyToWindow(activeDialog, GamepadFocusChrome.IsActive); DetachDialogControlHoverHandlers(_dialogControls); _dialogControls = CollectDialogFocusableControls(activeDialog); AttachDialogControlHoverHandlers(_dialogControls); _listBoxCursorIndex = -1; _focusedControlIndex = GetDefaultFocusIndex(_dialogControls); // With chrome active (gamepad or keyboard nav): paint default focus. // Without: wait for mouse hover / first keyboard or D-pad action. if (GamepadFocusChrome.IsActive) Dispatcher.UIThread.Post(FocusCurrentControl, DispatcherPriority.Loaded); else ClearGamepadFocusClasses(_dialogControls); } public void UnregisterModalDialog(Window dialog) { _questionResultCallbacks.Remove(dialog); DetachDialogKeyboardHandlers(dialog); var wasTop = ReferenceEquals(ActiveDialog, dialog); if (!_dialogStack.Remove(dialog)) return; GamepadFocusChrome.ApplyToWindow(dialog, false); if (_dialogStack.Count == 0) { DetachDialogControlHoverHandlers(_dialogControls); ClearGamepadFocusClasses(_dialogControls); _dialogControls = []; _focusedControlIndex = 0; _listBoxCursorIndex = -1; return; } if (wasTop) RefreshDialogButtons(); } private void BringToTop(Window dialog) { if (!_dialogStack.Remove(dialog)) return; _dialogStack.Add(dialog); } private void AttachDialogKeyboardHandlers(Window dialog) { if (!_keyboardAttachedDialogs.Add(dialog)) return; dialog.AddHandler(InputElement.KeyDownEvent, _dialogKeyDownHandler, RoutingStrategies.Tunnel); dialog.AddHandler(InputElement.KeyUpEvent, _dialogKeyUpHandler, RoutingStrategies.Tunnel); } private void DetachDialogKeyboardHandlers(Window dialog) { if (!_keyboardAttachedDialogs.Remove(dialog)) return; dialog.RemoveHandler(InputElement.KeyDownEvent, _dialogKeyDownHandler); dialog.RemoveHandler(InputElement.KeyUpEvent, _dialogKeyUpHandler); } private void OnDialogKeyDown(object? sender, KeyEventArgs e) { if (e.Handled || !ReferenceEquals(sender, ActiveDialog)) return; if (TryHandleDialogKeyDown(e.Key, e.KeyModifiers)) e.Handled = true; } private void OnDialogKeyUp(object? sender, KeyEventArgs e) { if (!ReferenceEquals(sender, ActiveDialog)) return; var action = ResolveKeyboardAction?.Invoke(e.Key, e.KeyModifiers); if (action is GamepadAction.NavUp or GamepadAction.NavDown or GamepadAction.NavLeft or GamepadAction.NavRight) _inputService?.ResetNavigationTimer(); } /// /// Handles a keyboard binding against the active modal dialog. /// internal bool TryHandleDialogKeyDown(Key key, KeyModifiers modifiers) { if (ActiveDialog == null) return false; // Open ComboBox dropdowns own input; do not ActivateKeyboardChrome (that re-focuses // the host ComboBox and steals Up/Down back to dialog field navigation). if (TryHandleOpenComboBoxKey(key, modifiers)) return true; // While typing: Enter/A and Escape/B leave edit so D-pad can move again. // A second Escape/B then cancels the dialog. Highlight-only TextBoxes are not editing. if (GamepadTextInput.IsEditing) { if (key is Key.Escape or Key.Enter) return GamepadTextInput.TryEndEdit(); var editingAction = ResolveKeyboardAction?.Invoke(key, modifiers); if (editingAction is GamepadAction.Cancel or GamepadAction.Confirm) return GamepadTextInput.TryEndEdit(); return false; } var action = ResolveKeyboardAction?.Invoke(key, modifiers); if (action == null) return false; switch (action) { case GamepadAction.Confirm: ActivateKeyboardChrome(); return TryHandleConfirm(); case GamepadAction.Cancel: ActivateKeyboardChrome(); return TryHandleCancel(); case GamepadAction.NavUp: ActivateKeyboardChrome(); return TryHandleNavigation(NavigationDirection.Up); case GamepadAction.NavDown: ActivateKeyboardChrome(); return TryHandleNavigation(NavigationDirection.Down); case GamepadAction.NavLeft: ActivateKeyboardChrome(); return TryHandleNavigation(NavigationDirection.Left); case GamepadAction.NavRight: ActivateKeyboardChrome(); return TryHandleNavigation(NavigationDirection.Right); case GamepadAction.Options: return false; default: return false; } } /// /// Leaves TextBox edit mode and restores the field highlight. /// Returns false when no field is being edited. /// internal bool TryExitTextBoxEditMode() { if (!GamepadTextInput.IsEditing || ActiveDialog == null) return false; var textBox = GamepadTextInput.Active; EnsureDialogControls(); if (textBox != null) { var index = _dialogControls.FindIndex(c => ReferenceEquals(c, textBox)); if (index >= 0) _focusedControlIndex = index; } OnKeyboardNavigationActivated?.Invoke(); if (!GamepadFocusChrome.IsActive) { GamepadFocusChrome.SetKeyboardNavigationActive(true); GamepadFocusChrome.SetActive(true); SyncChromeClass(true); } GamepadTextInput.TryEndEdit(); FocusCurrentControl(); return true; } private bool TryHandleOpenComboBoxKey(Key key, KeyModifiers modifiers) { var comboNav = GamepadComboBoxNavigation.Instance; if (!comboNav.HasActiveComboBox) return false; if (key == Key.Escape) return comboNav.TryHandleCancel(); var action = ResolveKeyboardAction?.Invoke(key, modifiers); return action switch { GamepadAction.Confirm => comboNav.TryHandleConfirm(), GamepadAction.Cancel => comboNav.TryHandleCancel(), GamepadAction.NavUp => comboNav.TryHandleNavigation(NavigationDirection.Up), GamepadAction.NavDown => comboNav.TryHandleNavigation(NavigationDirection.Down), GamepadAction.NavLeft => comboNav.TryHandleNavigation(NavigationDirection.Left), GamepadAction.NavRight => comboNav.TryHandleNavigation(NavigationDirection.Right), _ => false, }; } private void ActivateKeyboardChrome() { OnKeyboardNavigationActivated?.Invoke(); if (!GamepadFocusChrome.IsActive) { GamepadFocusChrome.SetKeyboardNavigationActive(true); GamepadFocusChrome.SetActive(true); SyncChromeClass(true); } EnsureDialogControls(); if (_dialogControls.Count > 0 && (_focusedControlIndex < 0 || _focusedControlIndex >= _dialogControls.Count)) { _focusedControlIndex = GetDefaultFocusIndex(_dialogControls); } FocusCurrentControl(); } public bool TryHandleNavigation(NavigationDirection direction) { var activeDialog = ActiveDialog; if (activeDialog == null) return false; // Prefer open ComboBox item navigation over moving between dialog fields. if (GamepadComboBoxNavigation.Instance.TryHandleNavigation(direction)) return true; EnsureDialogControls(); if (_dialogControls.Count == 0) return true; // ListBox owns Up/Down for moving among its own items; edges fall through to XYFocus. if (TryMoveListBoxSelection(direction)) return true; var previousIndex = _focusedControlIndex; var previousControl = previousIndex >= 0 && previousIndex < _dialogControls.Count ? _dialogControls[previousIndex] : GetFocusedControl(); if (!GamepadTextInput.ShouldSkipXyFocusOnHighlight(previousControl) && XyFocusNavigation.TryMove(activeDialog, direction, activeDialog)) { SyncFocusedIndexFromKeyboardFocus(); var moved = _focusedControlIndex >= 0 && _focusedControlIndex < _dialogControls.Count ? _dialogControls[_focusedControlIndex] : null; if (moved != null && !ReferenceEquals(previousControl, moved) && IsMoveInRequestedDirection(previousIndex, _focusedControlIndex, direction, activeDialog)) { FocusCurrentControl(); return true; } _focusedControlIndex = previousIndex; } if (_dialogControls.Count == 1) return true; var positions = GetControlPositions(_dialogControls, GetControlCenter); if (ArePositionsCollapsed(positions)) positions = GetControlPositions(_dialogControls, control => GetVisualTreeCenter(control, activeDialog)); _focusedControlIndex = MoveFocusIndex(_focusedControlIndex, direction, positions); FocusCurrentControl(); return true; } private void SyncFocusedIndexFromKeyboardFocus() { var focused = TopLevel.GetTopLevel(ActiveDialog)?.FocusManager?.GetFocusedElement(); var index = GamepadControlActivation.IndexOfControlContainingFocus(_dialogControls, focused); if (index >= 0) _focusedControlIndex = index; } private bool TryMoveListBoxSelection(NavigationDirection direction) { if (direction is not (NavigationDirection.Up or NavigationDirection.Down)) return false; if (GetFocusedControl() is not ListBox listBox) return false; var count = listBox.ItemCount; if (count <= 0) return false; var index = listBox.SelectedIndex; if (index < 0) index = 0; if (direction == NavigationDirection.Down) { if (index >= count - 1) return false; listBox.SelectedIndex = index + 1; } else { if (index <= 0) return false; listBox.SelectedIndex = index - 1; } _listBoxCursorIndex = listBox.SelectedIndex; if (listBox.SelectedItem is Control selectedControl) listBox.ScrollIntoView(selectedControl); else if (listBox.SelectedItem != null) listBox.ScrollIntoView(listBox.SelectedItem); FocusCurrentControl(); return true; } private static bool TryToggleListBoxCheckBox(ListBox listBox) { CheckBox? checkBox = listBox.SelectedItem switch { ListBoxItem { Content: CheckBox contentCheck } => contentCheck, CheckBox direct => direct, ListBoxItem item => item.GetVisualDescendants().OfType().FirstOrDefault(), _ => null, }; if (checkBox == null) return false; checkBox.IsChecked = checkBox.IsChecked != true; return true; } public bool TryHandleConfirm() { var activeDialog = ActiveDialog; if (activeDialog == null) return false; if (GamepadComboBoxNavigation.Instance.TryHandleConfirm()) return true; EnsureDialogControls(); if (_dialogControls.Count == 0) { InvokeQuestionResult(activeDialog, false); CloseDialogIfStillOpen(); return true; } var control = GetFocusedControl(); if (control == null) return false; if (control is TextBox textBox) { GamepadControlActivation.ActivateTextBox(textBox); return true; } if (control is ComboBox comboBox) { GamepadComboBoxNavigation.Open(comboBox); return true; } if (control is CheckBox checkBox) { GamepadControlActivation.ActivateCheckBox(checkBox); return true; } // Confirm on a file list: toggle a checkbox row when present, otherwise // activate the dialog's Install/affirmative button. if (control is ListBox listBox) { if (TryToggleListBoxCheckBox(listBox)) return true; var install = FindAffirmativeButton(_dialogControls) ?? _dialogControls.OfType