using System.Collections.Specialized; 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.Input; using System.Windows.Media; using System.Windows.Shapes; using System.Windows.Threading; using Titano.Ui.Controls; using Titano.Uploader.Infrastructure; using Titano.Uploader.Uploads; namespace Titano.Uploader.Shell; /// The uploader's single window (mockup Uploader.html). public sealed partial class MainWindow : TitanoWindow { /// Height of a queue row; the list scrolls by whole rows. public const double RowHeight = 28; private readonly MainViewModel _vm; private readonly UploaderSettings _settings; private bool _connectShown; public MainWindow(MainViewModel vm, UploaderSettings settings) { _vm = vm; _settings = settings; _connectShown = vm.IsConnectVisible; DataContext = vm; InitializeComponent(); WindowDirection.Follow(this); vm.PendingToasts.CollectionChanged += OnToastRequested; vm.PropertyChanged += OnViewModelChanged; vm.Connect.PropertyChanged += OnConnectChanged; vm.SignInRequested += (_, _) => FocusLater(Password); PreviewKeyDown += OnPreviewKeyDown; Loaded += (_, _) => FocusStart(); RestorePlacement(); } /// Remembers size and position (also when the window only hides to the tray). public void SavePlacement() { var b = RestoreBounds; if (b.IsEmpty || b.Width < MinWidth || b.Height < MinHeight) return; _settings.Window = new UploaderSettings.WindowPlacement { Left = b.Left, Top = b.Top, Width = b.Width, Height = b.Height }; } protected override void OnDragOver(DragEventArgs e) { var accepted = CanDrop(e); e.Effects = accepted ? DragDropEffects.Copy : DragDropEffects.None; SetDropHighlight(accepted); e.Handled = true; } protected override void OnDragLeave(DragEventArgs e) => SetDropHighlight(false); protected override void OnDrop(DragEventArgs e) { SetDropHighlight(false); if (!CanDrop(e) || e.Data.GetData(DataFormats.FileDrop) is not string[] paths) return; e.Handled = true; _ = EnqueueAsync(paths); } private async Task EnqueueAsync(IReadOnlyList paths) { try { await _vm.EnqueueAsync(paths); } catch (Exception ex) { // UI boundary: a drop must never take the window down. _vm.ReportError(ex); } } private bool CanDrop(DragEventArgs e) => !_vm.IsConnectVisible && e.Data.GetDataPresent(DataFormats.FileDrop); private void SetDropHighlight(bool on) { DropBorder.SetResourceReference(Shape.StrokeProperty, on ? "Brush.Accent" : "Brush.Stroke"); if (on) DropBorder.SetResourceReference(Shape.FillProperty, "Brush.AccentSubtle"); else DropBorder.Fill = Brushes.Transparent; } private void OnBrowseClick(object sender, RoutedEventArgs e) => OpenMenu((Button)sender); private void OnWatchChipClick(object sender, RoutedEventArgs e) => OpenMenu((Button)sender); /// Opens a button's menu under it on a normal click. private static void OpenMenu(Button button) { if (button.ContextMenu is not { } menu) return; menu.DataContext = button.DataContext; menu.PlacementTarget = button; menu.Placement = PlacementMode.Bottom; menu.IsOpen = true; } private void OnSequencesDropDownOpened(object? sender, EventArgs e) => _vm.RefreshSequencesCommand.Execute(null); private void OnPasswordChanged(object sender, RoutedEventArgs e) => _vm.Connect.Password = Password.Password; /// The "3 failed" link: brings the first failed file into view and gives it the keyboard (Enter retries it). private void OnShowFailedClick(object sender, RoutedEventArgs e) { if (_vm.FirstFailed() is not { } item) return; ScrollNearTop(item); ItemList.UpdateLayout(); if (ItemList.ItemContainerGenerator.ContainerFromItem(item) is ListBoxItem row) row.Focus(); } /// Enter on a failed row retries it: the keyboard path to the row's Retry button. private void OnItemListKeyDown(object sender, KeyEventArgs e) { if (e.Key != Key.Enter || e.OriginalSource is not ListBoxItem { DataContext: UploadItem { State: UploadItemState.Failed } item }) return; _vm.RetryItemCommand.Execute(item); e.Handled = true; } /// DESIGN ยง4 inputs: Enter commits, Esc reverts; Esc also closes the settings panel. private void OnPreviewKeyDown(object sender, KeyEventArgs e) { if (e.OriginalSource is TextBox box && (e.Key is Key.Enter or Key.Escape) && box.GetBindingExpression(TextBox.TextProperty) is { } binding) { if (e.Key == Key.Enter) binding.UpdateSource(); else binding.UpdateTarget(); if (e.Key == Key.Escape) e.Handled = true; return; } if (e.Key == Key.Escape && _vm.IsSettingsOpen) { _vm.IsSettingsOpen = false; e.Handled = true; } } private void OnViewModelChanged(object? sender, PropertyChangedEventArgs e) { switch (e.PropertyName) { case nameof(MainViewModel.CurrentItem) when _vm.CurrentItem is { } item && !ItemList.IsKeyboardFocusWithin: // Follow the upload unless the user is reading the list with the keyboard; a list that has just // appeared has its scroll viewer once it is laid out. Dispatcher.BeginInvoke(DispatcherPriority.Loaded, () => ScrollNearTop(item)); break; // Raised with every session change; only a real switch between the form and the queue moves the keyboard. case nameof(MainViewModel.IsConnectVisible) when _vm.IsConnectVisible != _connectShown: _connectShown = _vm.IsConnectVisible; if (_connectShown) Password.Clear(); FocusStart(); break; case nameof(MainViewModel.IsSettingsOpen): // Focus moves into the panel and comes back to the gear, so it is never left behind the scrim. FocusLater(_vm.IsSettingsOpen ? CloseSettingsButton : SettingsButton); break; case nameof(MainViewModel.Activity): Announce(QueueLine); break; } } /// A refused address or password takes the keyboard to that field; other failures are announced. private void OnConnectChanged(object? sender, PropertyChangedEventArgs e) { var connect = _vm.Connect; switch (e.PropertyName) { case nameof(ConnectViewModel.AddressError) when connect.AddressError is not null: FocusLater(AddressBox); break; case nameof(ConnectViewModel.PasswordError) when connect.PasswordError is not null: FocusLater(Password); break; case nameof(ConnectViewModel.ErrorText) when connect.ErrorText is not null: Dispatcher.BeginInvoke(DispatcherPriority.Loaded, () => Announce(ErrorMessage)); break; } } /// Where the keyboard starts: the first empty field of the sign-in form, or Browse once signed in. private void FocusStart() { if (!_vm.IsConnectVisible) FocusLater(BrowseButton); else if (_vm.Connect.Address.Length == 0) FocusLater(AddressBox); else FocusLater(_vm.Connect.Username.Length == 0 ? UserBox : Password); } /// Focuses once a visibility change has been laid out; text is selected so typing replaces it. private void FocusLater(Control target) => Dispatcher.BeginInvoke(DispatcherPriority.Loaded, () => { if (!target.IsVisible || !target.Focus()) return; if (target is TextBox box) box.SelectAll(); else if (target is PasswordBox password) password.SelectAll(); }); /// Scrolls so is the second visible row (the list scrolls by rows), unless it is already in view. private void ScrollNearTop(UploadItem item) { if (FindScrollViewer(ItemList) is not { } scroll) return; var index = ItemList.Items.IndexOf(item); if (index < 0) return; if (index >= scroll.VerticalOffset && index + 1 <= scroll.VerticalOffset + scroll.ViewportHeight) return; scroll.ScrollToVerticalOffset(Math.Max(0, index - 1)); } private static ScrollViewer? FindScrollViewer(DependencyObject node) { for (var i = 0; i < VisualTreeHelper.GetChildrenCount(node); i++) { var child = VisualTreeHelper.GetChild(node, i); if (child is ScrollViewer scroll) return scroll; if (FindScrollViewer(child) is { } found) return found; } return null; } /// Asks screen readers to read again (it carries ). private static void Announce(UIElement element) { if (element.IsVisible) UIElementAutomationPeer.CreatePeerForElement(element)?.RaiseAutomationEvent(AutomationEvents.LiveRegionChanged); } private void OnToastRequested(object? sender, NotifyCollectionChangedEventArgs e) { if (e.Action != NotifyCollectionChangedAction.Add || e.NewItems is null) return; foreach (Toast t in e.NewItems) Toasts.Show(t); Dispatcher.BeginInvoke(() => _vm.PendingToasts.Clear()); } private void RestorePlacement() { if (_settings.Window is not { } p || p.Width < MinWidth || p.Height < MinHeight) return; var screen = new Rect(SystemParameters.VirtualScreenLeft, SystemParameters.VirtualScreenTop, SystemParameters.VirtualScreenWidth, SystemParameters.VirtualScreenHeight); if (!screen.IntersectsWith(new Rect(p.Left, p.Top, p.Width, p.Height))) return; WindowStartupLocation = WindowStartupLocation.Manual; Left = p.Left; Top = p.Top; Width = p.Width; Height = p.Height; } }