using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using Chronos.App.Editor;
using Chronos.App.Shell;
using Chronos.Core.Diagnostics;
namespace Chronos.App.Sections;
public partial class SequenceView : UserControl
{
/// Set on a window once its closing waits for the editor's last save.
private static readonly DependencyProperty SavesBeforeClosingProperty =
DependencyProperty.RegisterAttached("SavesBeforeClosing", typeof(bool), typeof(SequenceView), new PropertyMetadata(false));
public SequenceView()
{
InitializeComponent();
// A drag, a click or a key press is one undo step even when it moves a slider many times (ProjectHistory runs);
// handled events too, because sliders and repeat buttons mark theirs handled.
EditorRoot.AddHandler(Thumb.DragCompletedEvent, new DragCompletedEventHandler((_, _) => EndEditRun()), handledEventsToo: true);
EditorRoot.AddHandler(MouseLeftButtonUpEvent, new MouseButtonEventHandler((_, _) => EndEditRun()), handledEventsToo: true);
EditorRoot.AddHandler(KeyUpEvent, new KeyEventHandler((_, _) => EndEditRun()), handledEventsToo: true);
EditorRoot.IsKeyboardFocusWithinChanged += OnEditorFocusWithinChanged;
DataContextChanged += OnDataContextChanged;
}
private EditorViewModel? Editor => (DataContext as SequenceViewModel)?.Editor;
/// The picker covers the open sequence: its keys are the picker's.
private bool IsPicking => (DataContext as SequenceViewModel)?.IsPicking == true;
///
/// Ctrl+PgDn and Ctrl+PgUp move one step along the path (owner review 1, R7); null for any other key. They are read as
/// the key goes down the tree, because the filmstrip and the curve editors take Page Up and Page Down whatever the
/// modifiers.
///
internal static int? StepDelta(Key key, ModifierKeys modifiers) => modifiers != ModifierKeys.Control ? null : key switch
{
Key.PageDown => 1,
Key.PageUp => -1,
_ => null,
};
///
/// The project is saved a moment after each edit; closing the window first stores the last edit, and asks before
/// discarding one that cannot be stored (once per window, so it holds even when another section is showing).
///
private void OnLoaded(object sender, RoutedEventArgs e)
{
FocusPreview();
if (Window.GetWindow(this) is not { } window || (bool)window.GetValue(SavesBeforeClosingProperty)) return;
window.SetValue(SavesBeforeClosingProperty, true);
var (saved, asking, closed) = (false, false, false);
window.Closing += OnClosing;
window.Closed += (_, _) => closed = true;
async void OnClosing(object? s, CancelEventArgs args)
{
if (saved || args.Cancel || window.DataContext is not ShellViewModel { Sequence: { HasPendingSave: true } section }) return;
args.Cancel = true;
if (asking) return;
asking = true;
var close = true;
try
{
close = await section.ConfirmCloseAsync();
if (close) await section.CloseAsync();
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("editor", "The last edit was not saved before closing", ex);
}
finally
{
asking = false;
}
// "Keep editing": the window stays open with the edit still pending.
if (!close) return;
saved = true;
// An application shutdown closes the window without waiting.
if (!closed) window.Close();
}
}
///
/// Space plays or pauses, arrows step a frame (BRIEF §12.3) — unless a text field or a control that uses the key has
/// it, or the picker or a dialog covers the editor.
///
private void OnKeyDown(object sender, KeyEventArgs e)
{
if (e.Handled || IsPicking || (DataContext as SequenceViewModel)?.IsDialogOpen == true || Editor is not { } editor || Keyboard.Modifiers != ModifierKeys.None
|| e.OriginalSource is TextBoxBase) return;
var command = e.Key switch
{
Key.Space => editor.PlayCommand,
Key.Left => editor.StepBackCommand,
Key.Right => editor.StepForwardCommand,
_ => null,
};
if (command is null) return;
command.Execute(null);
e.Handled = true;
}
/// Ctrl+PgDn and Ctrl+PgUp: the next and the previous step, stopping at the ends.
private void OnEditorPreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Handled || Editor is not { } editor || StepDelta(e.Key, Keyboard.Modifiers) is not { } delta) return;
editor.MoveStep(delta);
e.Handled = true;
}
/// The arrows move between steps while the step bar has the keyboard; at either end they do nothing else (no frame step).
private void OnStepsKeyDown(object sender, KeyEventArgs e)
{
if (e.Key is Key.Left or Key.Right or Key.Up or Key.Down) e.Handled = true;
}
///
/// On the step shown, Space plays or pauses as everywhere in the editor (the list would only select the step again), and
/// Ctrl+Space does nothing (the list would leave the bar without a current step). Read on the way down, before the list.
///
private void OnStepsPreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key != Key.Space || IsPicking || Editor is not { } editor || e.OriginalSource is not ListBoxItem { IsSelected: true }) return;
if (Keyboard.Modifiers == ModifierKeys.None) editor.PlayCommand.Execute(null);
e.Handled = Keyboard.Modifiers is ModifierKeys.None or ModifierKeys.Control;
}
/// Ctrl+click on the step shown keeps it the current one (a list would unselect it).
private void OnStepsPreviewMouseDown(object sender, MouseButtonEventArgs e)
{
if ((Keyboard.Modifiers & ModifierKeys.Control) == 0
|| ItemsControl.ContainerFromElement(Steps, e.OriginalSource as DependencyObject) is not ListBoxItem { IsSelected: true } item) return;
item.Focus();
e.Handled = true;
}
///
/// After a step change (Alt+n, Ctrl+PgUp/PgDn, Previous/Next, a step's own button) the keyboard stays in the editor: when
/// it was in the step bar, on a control of the step that is about to be replaced, or on Previous about to be disabled
/// on the first step, it goes to the new step's cell; otherwise it stays where it is.
///
private void OnStepsSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (!ReferenceEquals(e.OriginalSource, Steps) || IsPicking || Editor is not { } editor || e.AddedItems.Count == 0) return;
if (Window.GetWindow(this) is not { } window || FocusManager.GetFocusedElement(window) is not DependencyObject focused) return;
var follows = Steps.IsAncestorOf(focused) || StepMeasure.IsAncestorOf(focused) || StepPanel.IsAncestorOf(focused)
|| (ReferenceEquals(focused, PreviousStep) && editor.SelectedTab.Number == 1);
if (!follows) return;
// After the step's templates are swapped and the commands re-read (Background), so the cell is laid out and nothing takes it back;
// logical focus too, so a window that is not active gives the keyboard to the cell when it is activated.
Dispatcher.BeginInvoke(() =>
{
if (Editor is not { } current || Steps.ItemContainerGenerator.ContainerFromItem(current.SelectedTab) is not ListBoxItem { IsVisible: true } cell) return;
FocusManager.SetFocusedElement(FocusManager.GetFocusScope(cell), cell);
Keyboard.Focus(cell);
}, DispatcherPriority.Background);
}
/// An opened editor takes the keyboard, so its shortcuts work without clicking into it first.
private void OnEditorVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue is true) FocusPreview();
}
///
/// The focused control left the editor's tree or was disabled (a control of a step replaced by another, a button whose
/// command stopped applying): the keyboard fell to the window, where none of the editor's shortcuts are, so the preview
/// takes it back. A deliberate move out of the editor (the rail, a toast, another window) is left alone.
///
private void OnEditorFocusWithinChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue is true) return;
// After WPF has re-evaluated the focus (Input), which is what raised this.
Dispatcher.BeginInvoke(() =>
{
if (Window.GetWindow(this) is { IsActive: true } window && ReferenceEquals(Keyboard.FocusedElement, window) && EditorRoot.IsVisible && !IsPicking && Editor is not null)
Keyboard.Focus(Preview);
}, DispatcherPriority.Background);
}
/// A tool clicked with the mouse hands the keyboard back to the preview (Space keeps playing); keyboard users keep their focus.
private void OnToolClicked(object sender, RoutedEventArgs e)
{
if (InputManager.Current.MostRecentInputDevice is MouseDevice) Preview.Focus();
}
private void FocusPreview()
{
if (Editor is null || IsPicking) return;
Dispatcher.BeginInvoke(() =>
{
// Back from the picker, the focus is still in it (now hidden): the preview takes it.
if (Preview.IsVisible && (!IsKeyboardFocusWithin || Picker.IsKeyboardFocusWithin)) Keyboard.Focus(Preview);
}, DispatcherPriority.Input);
}
private void EndEditRun() => Editor?.Session.EndEditRun();
/// The project button (▾ beside the title) opens its menu under itself.
private void OnOpenProjectMenu(object sender, RoutedEventArgs e)
{
if (sender is not Button { ContextMenu: { } menu } button) return;
menu.DataContext = button.DataContext;
menu.PlacementTarget = button;
menu.Placement = PlacementMode.Bottom;
menu.IsOpen = true;
}
/// A dialog that opens takes the keyboard: its first field or button.
private void OnSectionChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName != nameof(SequenceViewModel.Dialog) || DataContext is not SequenceViewModel { Dialog: not null } || !IsVisible) return;
Dispatcher.BeginInvoke(DispatcherPriority.Input, () => DialogHost.MoveFocus(new TraversalRequest(FocusNavigationDirection.First)));
}
private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (e.OldValue is SequenceViewModel old) old.PropertyChanged -= OnSectionChanged;
if (e.NewValue is SequenceViewModel section) section.PropertyChanged += OnSectionChanged;
}
/// The preview renders at the size it is shown, in device pixels.
private void OnPreviewSizeChanged(object sender, SizeChangedEventArgs e)
{
if (Editor is not { } editor) return;
var scale = VisualTreeHelper.GetDpi(this).DpiScaleX;
editor.PreviewEdge = (int)(double.Max(e.NewSize.Width, e.NewSize.Height) * scale);
}
private void OnFullScreen(object sender, RoutedEventArgs e)
{
if (Editor is not { } editor) return;
var restore = editor.PreviewEdge;
var window = new FullScreenPreview(editor) { Owner = Window.GetWindow(this) };
window.ShowDialog();
editor.PreviewEdge = restore;
Preview.Focus();
}
}