using System.ComponentModel;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Peers;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Threading;
namespace Titano.App.Sections;
public partial class ImportView : UserControl
{
/// A polite text that keeps changing (copy progress) is announced at most this often.
private static readonly TimeSpan PoliteInterval = TimeSpan.FromSeconds(3);
private readonly Dictionary _announced = [];
private readonly HashSet _pending = [];
private bool _nicknameOpen;
private bool _restoreFocus;
public ImportView()
{
InitializeComponent();
DataContextChanged += OnDataContextChanged;
AddHandler(Binding.TargetUpdatedEvent, new EventHandler(OnTargetUpdated));
}
private ImportViewModel? Model => DataContext as ImportViewModel;
/// "Edit ▾" and "{ }" open their menu under themselves.
private void OnOpenMenu(object sender, RoutedEventArgs e)
{
if (sender is not Button { ContextMenu: { } menu } button) return;
menu.DataContext = DataContext;
menu.PlacementTarget = button;
menu.Placement = PlacementMode.Bottom;
menu.IsOpen = true;
}
/// The "{ }" menu writes into the template field used last.
private void OnFolderTemplateFocus(object sender, KeyboardFocusChangedEventArgs e) => Model?.SetActiveTemplate(folder: true);
private void OnFileTemplateFocus(object sender, KeyboardFocusChangedEventArgs e) => Model?.SetActiveTemplate(folder: false);
private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (e.OldValue is INotifyPropertyChanged old) old.PropertyChanged -= OnModelChanged;
if (e.NewValue is INotifyPropertyChanged model) model.PropertyChanged += OnModelChanged;
}
///
/// Keyboard focus follows what opens: the nickname field when it appears (a new card, Rename), and "Show plan"
/// (focus returns to its button when it closes). A change of phase that hides the focused button (Import, Retry,
/// New import, the status action, "Split here" closing the plan) moves focus to what replaced it, once the card
/// is planned again.
///
private void OnModelChanged(object? sender, PropertyChangedEventArgs e)
{
if (Model is not { } model) return;
if (e.PropertyName is nameof(ImportViewModel.IsNicknameOpen) or "")
{
var opened = model.IsNicknameOpen && !_nicknameOpen;
_nicknameOpen = model.IsNicknameOpen;
if (opened && IsVisible) FocusLater(NicknameBox);
}
if (e.PropertyName is nameof(ImportViewModel.IsDetailsOpen) && IsVisible)
{
if (model.IsDetailsOpen) FocusLater(ClosePlanButton);
else _restoreFocus = true;
}
if (e.PropertyName is nameof(ImportViewModel.IsDetailsOpen) or "" && IsVisible) Dispatcher.BeginInvoke(DispatcherPriority.Input, RestoreFocus);
}
private void RestoreFocus()
{
if (Model is not { } model || model.IsBusyPlanning) return;
var lost = Keyboard.FocusedElement is UIElement { IsVisible: false } focused && IsAncestorOf(focused);
if (!_restoreFocus && !lost) return;
_restoreFocus = false;
UIElement? target = model.IsRunning ? CancelButton
: model.IsDone ? NewImportButton
: model.IsFailed ? RetryButton
: model.HasPlan ? ShowPlanButton
: model.HasStatusAction ? StatusActionButton
: null;
target?.Focus();
}
/// After layout: an element that just became visible cannot take focus yet.
private void FocusLater(UIElement element) => Dispatcher.BeginInvoke(DispatcherPriority.Input, () => element.Focus());
///
/// Live texts (AutomationProperties.LiveSetting in XAML, their binding with NotifyOnTargetUpdated) tell screen
/// readers that they changed: planning status, copy progress, the result and the failure. WPF raises nothing by itself.
///
private void OnTargetUpdated(object? sender, DataTransferEventArgs e)
{
if (e.TargetObject is not UIElement element || AutomationProperties.GetLiveSetting(element) is var setting && setting == AutomationLiveSetting.Off) return;
if (AutomationPeer.ListenerExists(AutomationEvents.LiveRegionChanged)) Announce(element, setting);
}
/// Polite texts at most every , ending with their latest value; assertive ones at once.
private void Announce(UIElement element, AutomationLiveSetting setting)
{
var wait = setting == AutomationLiveSetting.Polite && _announced.TryGetValue(element, out var last) ? last + PoliteInterval - DateTime.UtcNow : TimeSpan.Zero;
if (wait > TimeSpan.Zero)
{
if (_pending.Add(element)) _ = AnnounceLaterAsync(element, setting, wait);
return;
}
_announced[element] = DateTime.UtcNow;
// After the bindings of the same change: a text that is being hidden is not announced.
Dispatcher.BeginInvoke(DispatcherPriority.Background, () =>
{
if (element.IsVisible) UIElementAutomationPeer.CreatePeerForElement(element)?.RaiseAutomationEvent(AutomationEvents.LiveRegionChanged);
});
}
private async Task AnnounceLaterAsync(UIElement element, AutomationLiveSetting setting, TimeSpan wait)
{
await Task.Delay(wait);
_pending.Remove(element);
Announce(element, setting);
}
}