Interactive 2D wave optics simulator. Turn any image into a refractive scene, add sources, watch waves refract, diffract and interfere. Probes, intensity maps, video export.
C#
Preview: timeline bar, in/out range, transport keys, locale-aware combo list
Alexander Graef9edff810f2e4
diff --git a/CLAUDE.md b/CLAUDE.mdindex 56ca506..cd964e6 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -37,16 +37,29 @@ WPF shell as it stands:- Preview document: `Panes/PreviewPane` (dummy, 2026-10-08). Two placeholder pictures (field,intensity) side by side or stacked (`Orientation`), each centred in its cell, with a `GridSplitter`between them (one 3×3 grid; the unused dimension is spanned, so each orientation keeps its own- ratio; Enter or double-click resets to half). Transport bar with `MediaCommands.Play/Pause`- (Space toggles), a scrub `Slider` over `Position` 0..`LastFrame`, `FrameCount` bound to- `Simulation.Steps`/`VisualizeEvery` via `FrameCountConverter`, and an editable speed combo+ ratio; Enter or double-click resets to half). Below them the time axis, `Controls/TimelineBar`+ (2026-10-09, custom `OnRender`: tick labels, playhead with frame number, in/out range as a band+ with brackets, hover frame; UIA peer exposes it as a slider). Transport bar with+ `MediaCommands.Play/Pause` (Space toggles), `Commands/PreviewCommands` (step `,` `.`, Home/End to+ the in/out points, `I`/`O` set them, `X` clears, `L` loops; letters are `KeyBinding`s on the pane+ because `KeyGesture` rejects unmodified letters, and `CanTransport` refuses them inside text+ boxes), a frame and step readout, `FrameCount` bound to `Simulation.Steps`/`VisualizeEvery` via+ `FrameCountConverter`, and an editable speed combo(`SpeedPresets` 0.25…4, any value typed; `DoubleTextConverter` ignores text that does not parseyet, otherwise every keystroke logs a binding error to the status bar). Numbers follow the Windowslocale everywhere: `App.OnStartup` overrides `FrameworkElement.Language` with the current culture(WPF defaults to en-US), so the preset list and the typed text both say `0,25` on a de-DE machine. Playback is a`DispatcherTimer` moving `Position` at `BaseFrameRate` × `Speed`; nothing renders yet. The renderpipeline will set `FieldImage` / `IntensityImage`. `Editors.xaml` gained the editable-combo text- box, a `Slider` style and keyboard-focus visuals for combo and slider.+ box, a `Slider` style and keyboard-focus visuals for combo and slider. An open combo list sits+ on the combo's own background (`ComboBoxListBackground`, not the darker menu popup colour) and+ the highlighted item is the accent with white text (`ComboBoxItemHover*`), like a tree+ selection; agreed with the user 2026-10-09 after the menu colours read as inverted there.+ The in/out range is model state: `Display.ExportFrom`/`ExportTo` in **steps** (0 = start / end of+ the run, also edited on the Display view); the pane derives `InPoint`/`OutPoint` in frames with+ `StepToFrameConverter` and writes steps back only through the commands (the bar's bracket drags+ execute `SetInPoint`/`SetOutPoint` with the frame as parameter). Playback stops at the out point+ or wraps to the in point while looping.- **Keyboard first.** Every control must be reachable and operable with Tab and the arrow keys andshow its keyboard focus (accent border); the user tests without the mouse. The preview pane isthe model: explicit `TabIndex` order, the radio group is one tab stop (`IsTabStop` bound to@@ -104,16 +117,20 @@ the project sources (same reference list as above, `-target:exe`, `-nowarn:...,1- `_tools/avi_check/Program.cs` — compile with `AviMjpegWriter.cs` only. Writes a 3-frame MJPEG AVI andwalks the RIFF tree (44 structural checks: header offsets, strh dwQuality = -1, movi size, idx1 offsets, EOF).-- `_tools/ui_check/PreviewCheck.ps1` drives the WPF preview pane end to end (25 checks: play/pause,- speed incl. locale spelling, scrubber keys, split radios, splitter, tab order, focus hand-off,- foreground untouched).+- `_tools/ui_check/PreviewCheck.ps1` drives the WPF preview pane end to end (39 checks: play/pause,+ speed incl. locale spelling, timeline keys, frame steps, in/out/loop, split radios, splitter, tab+ order, focus hand-off, foreground untouched).Run `powershell -ExecutionPolicy Bypass -File _tools/ui_check/PreviewCheck.ps1` (`-Trace` addsforeground/focus per line); exit code = failures. **How UI harnesses must work here**: the user maybe using the machine, so no mouse, no `SendKeys`, no `SetForegroundWindow`. Post `WM_KEYDOWN`/`WM_CHAR` to the app's HWND (WPF processes them while inactive) and read state back through`System.Windows.Automation` properties. Do **not** call UIA *patterns* (`Invoke`, `SetValue`,`Select`, `SetFocus`): on this app each one focuses its target and activates the window.- `PrintWindow(…, PW_RENDERFULLCONTENT)` captures the inactive window. The older scripts in the+ `_tools/ui_check/ComboListShot.ps1` opens the speed combo by keyboard and screenshots the list+ (the popup has no HWND in UIA, so its screen rectangle is copied), for judging list colours.+ `PrintWindow(…, PW_RENDERFULLCONTENT)` captures the inactive window. UIA lookups can miss while+ the UI thread is busy, so `Find` retries; the harness parks the foreground on its own off-screen+ form (minimise the app, activate the form, show the app without activation). The older scripts in thefolder (`MessagesCheck`, `ProjectTreeCheck`, `StatusBar*Check`) predate this rule and still usepatterns/mouse; rewrite them the same way when they are next needed.@@ -230,6 +247,11 @@ functional spec for the WPF UI.- Private `ref` parameters that are really `out` remain outside the engines (`TryPictureToCanvas`,`TryParseInt`, `DampingProblem`, `PromptForCValue`, `ComputeRanges`, `RgbToHsv`, …).- WPF: theme choice not persisted; panes empty.+- WPF preview, frames vs. steps: the transport bar, scrubber and playback count **frames**+ (0..`LastFrame`, one per `VisualizeEvery` steps), while sources, probes, the export range and the+ Properties pane use **steps**; the readout shows both (`773 / 1249 step 1546`), which reads as+ "why is step twice the frame". Undecided (2026-10-09): label it `step 1546 of 2500`, drop the+ step from the bar, or label the timeline ticks in steps. Do not change on your own.Fixed on 2026-10-07 (kept here so nobody re-reports them): `AviMjpegWriter` header/offset mismatch(header was 236 bytes vs. 224 assumed; now spec-exact, see `avi_check`); `GpuWaveSimulator.SetProbes`@@ -259,6 +281,19 @@ probes for `*.sln` (was `*.vbproj`, which never matched above the C# exe); NaN-s5. **WPF UI** in `WaveDude.WPF`: fill the Project / Preview / Properties panes; preview as a`WriteableBitmap` fed from `FrameRenderer` pixel buffers; MVVM over the existing settings POCOs;persist the theme choice. Use `HelpForm.cs` as the functional spec.+ Timeline, agreed 2026-10-09 (the scrub bar, in/out range and transport keys are done; these+ stay inside the preview pane, below the pictures):+ - **Event tracks** under the bar, one row per source and probe on the same time axis: a source+ draws a bar from its start to its end step (pulse envelope as a filled shape), a probe draws+ its start step as a flag; clicking selects the item in the Project tree, dragging a bar's+ edge changes its start/stop steps. Needs a scrollable track area and a collapse rule for+ many rows.+ - **Probe signal lane**: the probe's sampled amplitude/intensity over time drawn like an audio+ track on the same axis, so graph and picture line up; only meaningful once a run has data.+ - **Zoom and pan of the time axis**: Ctrl+wheel zooms around the cursor, Shift+wheel pans, a+ thin overview bar shows the visible window; needed once tracks exist, since 2500 steps at+ one pixel per frame do not fit.+ Deferred, possibly never: filmstrip thumbnails behind the bar (needs cached frames).6. Retire `Wave_Dude_2D` once the WPF app covers it.## Conventionsdiff --git a/WaveDude.WPF/Commands/PreviewCommands.cs b/WaveDude.WPF/Commands/PreviewCommands.csnew file mode 100644index 0000000..fe4bda5--- /dev/null+++ b/WaveDude.WPF/Commands/PreviewCommands.cs@@ -0,0 +1,40 @@+using System.Windows.Input;++namespace WaveDude.WPF.Commands;++/// <summary>+/// Transport commands of the preview pane beyond the built-in <see cref="MediaCommands"/>.+/// Bound on the pane, so the keys work from any control inside it (the pane's handlers refuse+/// them while a text box has focus, so typing is never hijacked). Home and End are gestures of+/// the commands; the letter and punctuation keys (, . I O X L) are <c>KeyBinding</c>s in the+/// pane's XAML, because <see cref="KeyGesture"/> rejects unmodified letters. The in/out commands+/// take a frame number as parameter, or null for the frame shown.+/// </summary>+public static class PreviewCommands+{+ /// <summary>Shows the previous frame.</summary>+ public static readonly RoutedUICommand StepBack = new("Previous frame", nameof(StepBack), typeof(PreviewCommands));++ /// <summary>Shows the next frame.</summary>+ public static readonly RoutedUICommand StepForward = new("Next frame", nameof(StepForward), typeof(PreviewCommands));++ /// <summary>Jumps to the in point (the first frame while no range is set).</summary>+ public static readonly RoutedUICommand GoToStart = new("Go to in point", nameof(GoToStart), typeof(PreviewCommands),+ [new KeyGesture(Key.Home)]);++ /// <summary>Jumps to the out point (the last frame while no range is set).</summary>+ public static readonly RoutedUICommand GoToEnd = new("Go to out point", nameof(GoToEnd), typeof(PreviewCommands),+ [new KeyGesture(Key.End)]);++ /// <summary>Sets the in point of the export/loop range at the parameter frame or the frame shown.</summary>+ public static readonly RoutedUICommand SetInPoint = new("Set in point", nameof(SetInPoint), typeof(PreviewCommands));++ /// <summary>Sets the out point of the export/loop range at the parameter frame or the frame shown.</summary>+ public static readonly RoutedUICommand SetOutPoint = new("Set out point", nameof(SetOutPoint), typeof(PreviewCommands));++ /// <summary>Clears the export/loop range back to the whole run.</summary>+ public static readonly RoutedUICommand ClearRange = new("Clear range", nameof(ClearRange), typeof(PreviewCommands));++ /// <summary>Toggles looping between the in and out points.</summary>+ public static readonly RoutedUICommand ToggleLoop = new("Loop", nameof(ToggleLoop), typeof(PreviewCommands));+}diff --git a/WaveDude.WPF/Controls/TimelineBar.cs b/WaveDude.WPF/Controls/TimelineBar.csnew file mode 100644index 0000000..179e6bd--- /dev/null+++ b/WaveDude.WPF/Controls/TimelineBar.cs@@ -0,0 +1,511 @@+using System.Globalization;+using System.Windows;+using System.Windows.Automation;+using System.Windows.Automation.Peers;+using System.Windows.Automation.Provider;+using System.Windows.Input;+using System.Windows.Media;++namespace WaveDude.WPF.Controls;++/// <summary>+/// The time axis of a run, in frames: a tall scrub bar with tick labels, a playhead with its+/// frame number, an in/out range drawn as a band between two brackets, and the frame under the+/// mouse. Click or drag scrubs; dragging a bracket asks for a new in or out point through+/// <see cref="SetRangeStartCommand"/> / <see cref="SetRangeEndCommand"/> (the range itself is+/// owned by the model, so the control never writes <see cref="RangeStart"/> or+/// <see cref="RangeEnd"/>). Keyboard: Left/Right one frame, PageUp/PageDown ten, Home/End to+/// the in/out points, the wheel one frame. Drawn in <see cref="OnRender"/>; colours come from+/// the brush properties so a theme style can set them.+/// </summary>+public sealed class TimelineBar : FrameworkElement+{+ /// <summary>Height of the label row above the bar, in pixels.</summary>+ public const double LabelRowHeight = 14.0;++ /// <summary>Default height of the whole control, in pixels.</summary>+ public const double DefaultHeight = 36.0;++ /// <summary>Pixels a tick label needs at least, which picks the labelled tick interval.</summary>+ private const double MinLabelSpacing = 64.0;++ /// <summary>Half-width of the hit area of a range bracket, in pixels.</summary>+ private const double BracketHitHalfWidth = 6.0;++ private static readonly int[] TickCandidates = [1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000];+ private static readonly Typeface LabelTypeface = new("Segoe UI");++ /// <summary>Identifies the <see cref="Maximum"/> property: the last frame index.</summary>+ public static readonly DependencyProperty MaximumProperty = DependencyProperty.Register(+ nameof(Maximum), typeof(int), typeof(TimelineBar),+ new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.AffectsRender, OnMaximumChanged));++ /// <summary>Identifies the <see cref="Value"/> property: the frame shown.</summary>+ public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(+ nameof(Value), typeof(int), typeof(TimelineBar),+ new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,+ OnValueChanged, CoerceValue));++ /// <summary>Identifies the <see cref="RangeStart"/> property: the in point, in frames.</summary>+ public static readonly DependencyProperty RangeStartProperty = DependencyProperty.Register(+ nameof(RangeStart), typeof(int), typeof(TimelineBar), new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.AffectsRender));++ /// <summary>Identifies the <see cref="RangeEnd"/> property: the out point, in frames.</summary>+ public static readonly DependencyProperty RangeEndProperty = DependencyProperty.Register(+ nameof(RangeEnd), typeof(int), typeof(TimelineBar), new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.AffectsRender));++ /// <summary>Identifies the <see cref="SetRangeStartCommand"/> property.</summary>+ public static readonly DependencyProperty SetRangeStartCommandProperty = DependencyProperty.Register(+ nameof(SetRangeStartCommand), typeof(ICommand), typeof(TimelineBar));++ /// <summary>Identifies the <see cref="SetRangeEndCommand"/> property.</summary>+ public static readonly DependencyProperty SetRangeEndCommandProperty = DependencyProperty.Register(+ nameof(SetRangeEndCommand), typeof(ICommand), typeof(TimelineBar));++ /// <summary>Identifies the <see cref="Background"/> property: fill of the bar.</summary>+ public static readonly DependencyProperty BackgroundProperty = DependencyProperty.Register(+ nameof(Background), typeof(Brush), typeof(TimelineBar), new FrameworkPropertyMetadata(Brushes.Transparent, FrameworkPropertyMetadataOptions.AffectsRender));++ /// <summary>Identifies the <see cref="Foreground"/> property: playhead and its label.</summary>+ public static readonly DependencyProperty ForegroundProperty = DependencyProperty.Register(+ nameof(Foreground), typeof(Brush), typeof(TimelineBar), new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.AffectsRender));++ /// <summary>Identifies the <see cref="TickBrush"/> property: ticks, bar border and hover line.</summary>+ public static readonly DependencyProperty TickBrushProperty = DependencyProperty.Register(+ nameof(TickBrush), typeof(Brush), typeof(TimelineBar), new FrameworkPropertyMetadata(Brushes.Gray, FrameworkPropertyMetadataOptions.AffectsRender));++ /// <summary>Identifies the <see cref="LabelBrush"/> property: tick labels and the hover label.</summary>+ public static readonly DependencyProperty LabelBrushProperty = DependencyProperty.Register(+ nameof(LabelBrush), typeof(Brush), typeof(TimelineBar), new FrameworkPropertyMetadata(Brushes.Gray, FrameworkPropertyMetadataOptions.AffectsRender));++ /// <summary>Identifies the <see cref="AccentBrush"/> property: range band, brackets and keyboard focus.</summary>+ public static readonly DependencyProperty AccentBrushProperty = DependencyProperty.Register(+ nameof(AccentBrush), typeof(Brush), typeof(TimelineBar), new FrameworkPropertyMetadata(Brushes.DodgerBlue, FrameworkPropertyMetadataOptions.AffectsRender));++ private enum DragMode { None, Scrub, RangeStart, RangeEnd }++ private DragMode _drag;+ private int? _hoverFrame;++ public TimelineBar()+ {+ Focusable = true;+ FocusVisualStyle = null;+ SnapsToDevicePixels = true;+ Height = DefaultHeight;+ }++ /// <summary>Last frame index; 0 means a single frame and nothing to scrub.</summary>+ public int Maximum+ {+ get => (int)GetValue(MaximumProperty);+ set => SetValue(MaximumProperty, value);+ }++ /// <summary>Frame shown, 0..<see cref="Maximum"/>.</summary>+ public int Value+ {+ get => (int)GetValue(ValueProperty);+ set => SetValue(ValueProperty, value);+ }++ /// <summary>In point of the range, in frames.</summary>+ public int RangeStart+ {+ get => (int)GetValue(RangeStartProperty);+ set => SetValue(RangeStartProperty, value);+ }++ /// <summary>Out point of the range, in frames.</summary>+ public int RangeEnd+ {+ get => (int)GetValue(RangeEndProperty);+ set => SetValue(RangeEndProperty, value);+ }++ /// <summary>Executed with the frame (int) when the in bracket is dragged.</summary>+ public ICommand? SetRangeStartCommand+ {+ get => (ICommand?)GetValue(SetRangeStartCommandProperty);+ set => SetValue(SetRangeStartCommandProperty, value);+ }++ /// <summary>Executed with the frame (int) when the out bracket is dragged.</summary>+ public ICommand? SetRangeEndCommand+ {+ get => (ICommand?)GetValue(SetRangeEndCommandProperty);+ set => SetValue(SetRangeEndCommandProperty, value);+ }++ /// <summary>Fill of the bar.</summary>+ public Brush Background+ {+ get => (Brush)GetValue(BackgroundProperty);+ set => SetValue(BackgroundProperty, value);+ }++ /// <summary>Playhead and its frame label.</summary>+ public Brush Foreground+ {+ get => (Brush)GetValue(ForegroundProperty);+ set => SetValue(ForegroundProperty, value);+ }++ /// <summary>Ticks, the bar's border and the hover line.</summary>+ public Brush TickBrush+ {+ get => (Brush)GetValue(TickBrushProperty);+ set => SetValue(TickBrushProperty, value);+ }++ /// <summary>Tick labels and the hover label.</summary>+ public Brush LabelBrush+ {+ get => (Brush)GetValue(LabelBrushProperty);+ set => SetValue(LabelBrushProperty, value);+ }++ /// <summary>Range band and brackets, keyboard focus border.</summary>+ public Brush AccentBrush+ {+ get => (Brush)GetValue(AccentBrushProperty);+ set => SetValue(AccentBrushProperty, value);+ }++ private static void OnMaximumChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) => d.CoerceValue(ValueProperty);++ private static object CoerceValue(DependencyObject d, object value) => Math.Clamp((int)value, 0, ((TimelineBar)d).Maximum);++ private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)+ {+ if (UIElementAutomationPeer.FromElement((TimelineBar)d) is TimelineBarAutomationPeer peer)+ {+ peer.RaisePropertyChangedEvent(RangeValuePatternIdentifiers.ValueProperty, (double)(int)e.OldValue, (double)(int)e.NewValue);+ }+ }++ /// <inheritdoc/>+ protected override AutomationPeer OnCreateAutomationPeer() => new TimelineBarAutomationPeer(this);++ /// <inheritdoc/>+ protected override Size MeasureOverride(Size availableSize) =>+ new(double.IsInfinity(availableSize.Width) ? 0 : availableSize.Width, DefaultHeight);++ // ---------------------------------------------------------------- geometry++ /// <summary>Usable track: one pixel inset at both ends so the playhead at 0 and at Maximum is visible.</summary>+ private double TrackLeft => 1.0;+ private double TrackWidth => Math.Max(1.0, ActualWidth - 2.0);+ private double BarTop => LabelRowHeight;+ private double BarHeight => Math.Max(1.0, ActualHeight - LabelRowHeight);++ /// <summary>Pixel x of a frame's centre line.</summary>+ private double XOf(int frame) => Maximum > 0 ? TrackLeft + frame * TrackWidth / Maximum : TrackLeft;++ /// <summary>Frame nearest to a pixel x, clamped.</summary>+ private int FrameAt(double x) =>+ Maximum > 0 ? Math.Clamp((int)Math.Round((x - TrackLeft) / TrackWidth * Maximum), 0, Maximum) : 0;++ /// <summary>Which bracket, if any, a pixel x is on; the nearer one wins when both are close.</summary>+ private DragMode BracketAt(double x)+ {+ double dStart = Math.Abs(x - XOf(RangeStart));+ double dEnd = Math.Abs(x - XOf(RangeEnd));+ if (dStart <= BracketHitHalfWidth && dStart <= dEnd)+ {+ return DragMode.RangeStart;+ }+ return dEnd <= BracketHitHalfWidth ? DragMode.RangeEnd : DragMode.None;+ }++ // ---------------------------------------------------------------- rendering++ /// <inheritdoc/>+ protected override void OnRender(DrawingContext dc)+ {+ double w = ActualWidth;+ double h = ActualHeight;+ if (w <= 2 || h <= LabelRowHeight)+ {+ return;+ }+ var pen = new Pen(TickBrush, 1.0);+ var bar = new Rect(0.5, BarTop + 0.5, w - 1.0, BarHeight - 1.0);+ dc.DrawRectangle(Background, pen, bar);++ // the in/out range: two brackets, plus a translucent band once it is narrower than the run+ double x0 = Math.Round(XOf(RangeStart)) + 0.5;+ double x1 = Math.Round(XOf(RangeEnd)) + 0.5;+ if (x1 > x0 && (RangeStart > 0 || RangeEnd < Maximum))+ {+ dc.PushOpacity(0.25);+ dc.DrawRectangle(AccentBrush, null, new Rect(x0, bar.Top + 1, x1 - x0, bar.Height - 2));+ dc.Pop();+ }+ DrawBracket(dc, x0, bar, open: true);+ DrawBracket(dc, x1, bar, open: false);++ // ticks and labels; the labelled interval is the smallest candidate that leaves room for its text+ if (Maximum > 0)+ {+ double pxPerFrame = TrackWidth / Maximum;+ int major = TickCandidates[^1];+ foreach (int candidate in TickCandidates)+ {+ if (candidate * pxPerFrame >= MinLabelSpacing)+ {+ major = candidate;+ break;+ }+ }+ int minor = major >= 10 ? major / 5 : major >= 2 ? 1 : 0;+ if (minor > 0)+ {+ for (int f = 0; f <= Maximum; f += minor)+ {+ if (f % major != 0)+ {+ double x = Math.Round(XOf(f)) + 0.5;+ dc.DrawLine(pen, new Point(x, bar.Top), new Point(x, bar.Top + 3));+ }+ }+ }+ for (int f = 0; f <= Maximum; f += major)+ {+ double x = Math.Round(XOf(f)) + 0.5;+ dc.DrawLine(pen, new Point(x, bar.Top), new Point(x, bar.Top + 6));+ FormattedText label = Label(f.ToString(CultureInfo.CurrentCulture), LabelBrush);+ double lx = Math.Min(x + 2, w - label.Width - 1);+ if (lx + label.Width <= Math.Round(XOf(Value)) - 4 || lx >= Math.Round(XOf(Value)) + 4 + PlayheadLabelWidth())+ {+ dc.DrawText(label, new Point(lx, 0));+ }+ }+ }++ // the frame under the mouse+ if (_hoverFrame is int hover && _drag == DragMode.None && hover != Value)+ {+ double x = Math.Round(XOf(hover)) + 0.5;+ dc.PushOpacity(0.5);+ dc.DrawLine(pen, new Point(x, bar.Top), new Point(x, bar.Bottom));+ dc.Pop();+ }++ // the playhead: a line through the bar, a handle on top, the frame number next to it+ double px = Math.Round(XOf(Value)) + 0.5;+ dc.DrawLine(new Pen(Foreground, 1.0), new Point(px, bar.Top), new Point(px, bar.Bottom));+ var handle = new StreamGeometry();+ using (StreamGeometryContext g = handle.Open())+ {+ g.BeginFigure(new Point(px - 5, bar.Top - 6), true, true);+ g.LineTo(new Point(px + 5, bar.Top - 6), false, false);+ g.LineTo(new Point(px, bar.Top), false, false);+ }+ dc.DrawGeometry(Foreground, null, handle);+ FormattedText playhead = Label(Value.ToString(CultureInfo.CurrentCulture), Foreground, bold: true);+ double tx = px + 8 + playhead.Width <= w ? px + 8 : px - 8 - playhead.Width;+ dc.DrawText(playhead, new Point(tx, 0));++ if (IsKeyboardFocused)+ {+ dc.DrawRectangle(null, new Pen(AccentBrush, 1.0), new Rect(0.5, 0.5, w - 1, h - 1));+ }+ }++ private double PlayheadLabelWidth() => Label(Value.ToString(CultureInfo.CurrentCulture), Foreground, bold: true).Width + 8;++ /// <summary>A bracket at x: a 2 px vertical bar with feet pointing into the range.</summary>+ private void DrawBracket(DrawingContext dc, double x, Rect bar, bool open)+ {+ double foot = open ? 4 : -4;+ double left = open ? x - 0.5 : x - 1.5;+ dc.DrawRectangle(AccentBrush, null, new Rect(left, bar.Top, 2, bar.Height));+ dc.DrawRectangle(AccentBrush, null, new Rect(Math.Min(left, left + foot), bar.Top, Math.Abs(foot) + 2, 2));+ dc.DrawRectangle(AccentBrush, null, new Rect(Math.Min(left, left + foot), bar.Bottom - 2, Math.Abs(foot) + 2, 2));+ }++ private FormattedText Label(string text, Brush brush, bool bold = false) =>+ new(text, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight,+ bold ? new Typeface(LabelTypeface.FontFamily, FontStyles.Normal, FontWeights.SemiBold, FontStretches.Normal) : LabelTypeface,+ 11.0, brush, VisualTreeHelper.GetDpi(this).PixelsPerDip);++ // ---------------------------------------------------------------- mouse++ /// <inheritdoc/>+ protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)+ {+ base.OnMouseLeftButtonDown(e);+ Focus();+ double x = e.GetPosition(this).X;+ _drag = BracketAt(x) switch+ {+ DragMode.RangeStart => DragMode.RangeStart,+ DragMode.RangeEnd => DragMode.RangeEnd,+ _ => DragMode.Scrub,+ };+ ApplyDrag(x);+ CaptureMouse();+ e.Handled = true;+ }++ /// <inheritdoc/>+ protected override void OnMouseMove(MouseEventArgs e)+ {+ base.OnMouseMove(e);+ double x = e.GetPosition(this).X;+ if (_drag != DragMode.None)+ {+ ApplyDrag(x);+ return;+ }+ _hoverFrame = FrameAt(x);+ Cursor = BracketAt(x) == DragMode.None ? Cursors.Arrow : Cursors.SizeWE;+ InvalidateVisual();+ }++ /// <inheritdoc/>+ protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)+ {+ base.OnMouseLeftButtonUp(e);+ if (_drag != DragMode.None)+ {+ _drag = DragMode.None;+ ReleaseMouseCapture();+ InvalidateVisual();+ e.Handled = true;+ }+ }++ /// <inheritdoc/>+ protected override void OnMouseLeave(MouseEventArgs e)+ {+ base.OnMouseLeave(e);+ _hoverFrame = null;+ InvalidateVisual();+ }++ /// <inheritdoc/>+ protected override void OnMouseWheel(MouseWheelEventArgs e)+ {+ base.OnMouseWheel(e);+ Value += e.Delta > 0 ? 1 : -1;+ e.Handled = true;+ }++ private void ApplyDrag(double x)+ {+ int frame = FrameAt(x);+ switch (_drag)+ {+ case DragMode.Scrub:+ Value = frame;+ break;+ case DragMode.RangeStart:+ Execute(SetRangeStartCommand, frame);+ break;+ case DragMode.RangeEnd:+ Execute(SetRangeEndCommand, frame);+ break;+ }+ }++ private void Execute(ICommand? command, int frame)+ {+ if (command is RoutedCommand routed)+ {+ if (routed.CanExecute(frame, this))+ {+ routed.Execute(frame, this);+ }+ }+ else if (command?.CanExecute(frame) == true)+ {+ command.Execute(frame);+ }+ }++ // ---------------------------------------------------------------- keyboard++ /// <inheritdoc/>+ protected override void OnKeyDown(KeyEventArgs e)+ {+ base.OnKeyDown(e);+ int? target = e.Key switch+ {+ Key.Left => Value - 1,+ Key.Right => Value + 1,+ Key.PageDown => Value - 10,+ Key.PageUp => Value + 10,+ Key.Home => RangeStart,+ Key.End => RangeEnd,+ _ => null,+ };+ if (target is int frame)+ {+ Value = frame;+ e.Handled = true;+ }+ }++ /// <inheritdoc/>+ protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e)+ {+ base.OnGotKeyboardFocus(e);+ InvalidateVisual();+ }++ /// <inheritdoc/>+ protected override void OnLostKeyboardFocus(KeyboardFocusChangedEventArgs e)+ {+ base.OnLostKeyboardFocus(e);+ InvalidateVisual();+ }+}++/// <summary>Exposes a <see cref="TimelineBar"/> to UI Automation as a slider with a range value.</summary>+public sealed class TimelineBarAutomationPeer : FrameworkElementAutomationPeer, IRangeValueProvider+{+ public TimelineBarAutomationPeer(TimelineBar owner) : base(owner)+ {+ }++ private TimelineBar Bar => (TimelineBar)Owner;++ /// <inheritdoc/>+ protected override AutomationControlType GetAutomationControlTypeCore() => AutomationControlType.Slider;++ /// <inheritdoc/>+ protected override string GetClassNameCore() => nameof(TimelineBar);++ /// <inheritdoc/>+ protected override bool IsContentElementCore() => true;++ /// <inheritdoc/>+ protected override bool IsControlElementCore() => true;++ /// <inheritdoc/>+ public override object? GetPattern(PatternInterface patternInterface) =>+ patternInterface == PatternInterface.RangeValue ? this : base.GetPattern(patternInterface);++ /// <inheritdoc/>+ public bool IsReadOnly => false;++ /// <inheritdoc/>+ public double Value => Bar.Value;++ /// <inheritdoc/>+ public double Minimum => 0;++ /// <inheritdoc/>+ public double Maximum => Bar.Maximum;++ /// <inheritdoc/>+ public double SmallChange => 1;++ /// <inheritdoc/>+ public double LargeChange => 10;++ /// <inheritdoc/>+ public void SetValue(double value) => Bar.Value = (int)Math.Round(value);+}diff --git a/WaveDude.WPF/Converters/FrameToStepConverter.cs b/WaveDude.WPF/Converters/FrameToStepConverter.csnew file mode 100644index 0000000..ce54a71--- /dev/null+++ b/WaveDude.WPF/Converters/FrameToStepConverter.cs@@ -0,0 +1,20 @@+using System.Globalization;+using System.Windows.Data;++namespace WaveDude.WPF.Converters;++/// <summary>+/// The simulation step a frame shows: frame index × visualisation interval (the two inputs in+/// that order), as text in the given culture. One way, for readouts: a multi-binding does not+/// convert an int to a string target on its own.+/// </summary>+public sealed class FrameToStepConverter : IMultiValueConverter+{+ /// <inheritdoc/>+ public object Convert(object[] values, Type targetType, object? parameter, CultureInfo culture) =>+ (values.Length == 2 && values[0] is int frame && values[1] is int every ? frame * every : 0).ToString(culture);++ /// <inheritdoc/>+ public object[] ConvertBack(object value, Type[] targetTypes, object? parameter, CultureInfo culture) =>+ throw new NotSupportedException();+}diff --git a/WaveDude.WPF/Converters/StepToFrameConverter.cs b/WaveDude.WPF/Converters/StepToFrameConverter.csnew file mode 100644index 0000000..207b03c--- /dev/null+++ b/WaveDude.WPF/Converters/StepToFrameConverter.cs@@ -0,0 +1,32 @@+using System.Globalization;+using System.Windows.Data;++namespace WaveDude.WPF.Converters;++/// <summary>+/// Turns a simulation step into the index of the frame that shows it. Inputs, in this order:+/// the step, the visualisation interval (steps per frame) and the last frame index. The result+/// is clamped to 0..last frame. With the parameter <c>"end"</c> a step of 0 means the end of+/// the run and gives the last frame, which is how <c>Display.ExportTo</c> encodes "no out point".+/// One way: the pane writes steps back through its commands.+/// </summary>+public sealed class StepToFrameConverter : IMultiValueConverter+{+ /// <inheritdoc/>+ public object Convert(object[] values, Type targetType, object? parameter, CultureInfo culture)+ {+ if (values.Length != 3 || values[0] is not int step || values[1] is not int every || values[2] is not int lastFrame)+ {+ return 0;+ }+ if (step <= 0)+ {+ return Equals(parameter, "end") ? lastFrame : 0;+ }+ return Math.Clamp(every > 0 ? step / every : 0, 0, lastFrame);+ }++ /// <inheritdoc/>+ public object[] ConvertBack(object value, Type[] targetTypes, object? parameter, CultureInfo culture) =>+ throw new NotSupportedException();+}diff --git a/WaveDude.WPF/Panes/PreviewPane.xaml b/WaveDude.WPF/Panes/PreviewPane.xamlindex b5a8a50..b2ddd66 100644--- a/WaveDude.WPF/Panes/PreviewPane.xaml+++ b/WaveDude.WPF/Panes/PreviewPane.xaml@@ -3,16 +3,25 @@xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:local="clr-namespace:WaveDude.WPF.Panes"xmlns:converters="clr-namespace:WaveDude.WPF.Converters"+ xmlns:controls="clr-namespace:WaveDude.WPF.Controls"+ xmlns:commands="clr-namespace:WaveDude.WPF.Commands"Background="{DynamicResource DocumentBackground}" Focusable="True" IsTabStop="False"><UserControl.Resources><converters:EnumBooleanConverter x:Key="EnumBoolean" /><converters:DoubleTextConverter x:Key="DoubleText" />+ <converters:FrameToStepConverter x:Key="FrameToStep" /><StreamGeometry x:Key="PlayGeometry">M0,0 L9,5 L0,10 Z</StreamGeometry><StreamGeometry x:Key="PauseGeometry">M0,0 L3,0 L3,10 L0,10 Z M6,0 L9,0 L9,10 L6,10 Z</StreamGeometry><StreamGeometry x:Key="SideBySideGeometry">M0,0 L5,0 L5,10 L0,10 Z M7,0 L12,0 L12,10 L7,10 Z</StreamGeometry><StreamGeometry x:Key="StackedGeometry">M0,0 L12,0 L12,4 L0,4 Z M0,6 L12,6 L12,10 L0,10 Z</StreamGeometry>+ <StreamGeometry x:Key="StepBackGeometry">M0,0 L2,0 L2,10 L0,10 Z M9,0 L3,5 L9,10 Z</StreamGeometry>+ <StreamGeometry x:Key="StepForwardGeometry">M7,0 L9,0 L9,10 L7,10 Z M0,0 L6,5 L0,10 Z</StreamGeometry>+ <StreamGeometry x:Key="SetInGeometry">M0,0 L4,0 L4,2 L2,2 L2,8 L4,8 L4,10 L0,10 Z M6,2 L11,5 L6,8 Z</StreamGeometry>+ <StreamGeometry x:Key="SetOutGeometry">M11,0 L7,0 L7,2 L9,2 L9,8 L7,8 L7,10 L11,10 Z M5,2 L0,5 L5,8 Z</StreamGeometry>+ <StreamGeometry x:Key="ClearRangeGeometry">M0,1.5 L1.5,0 L5,3.5 L8.5,0 L10,1.5 L6.5,5 L10,8.5 L8.5,10 L5,6.5 L1.5,10 L0,8.5 L3.5,5 Z</StreamGeometry>+ <StreamGeometry x:Key="LoopGeometry">M5,1 A4,4 0 1 1 1,5 L3,5 A2,2 0 1 0 5,3 Z M5,0 L8,2 L5,4 Z</StreamGeometry><!-- filled-glyph transport button; Content is the geometry. A tab stop: keyboard focus shows as an accent border --><Style x:Key="TransportButton" TargetType="{x:Type Button}">@@ -49,9 +58,9 @@</Setter></Style>- <!-- glyph radio button for a choice shown as a row of buttons; the chosen one stays pressed.- The group is one tab stop; Left/Right move within it (see the StackPanel below) -->- <Style x:Key="TransportRadio" TargetType="{x:Type RadioButton}">+ <!-- glyph toggle (and radio) button; the checked one stays pressed. Used for the loop toggle and+ the split radios, whose group is one tab stop with Left/Right inside (see the StackPanel below) -->+ <Style x:Key="TransportToggle" TargetType="{x:Type ToggleButton}"><Setter Property="Width" Value="22" /><Setter Property="Height" Value="22" /><Setter Property="Margin" Value="1,0" />@@ -59,7 +68,7 @@<Setter Property="FocusVisualStyle" Value="{x:Null}" /><Setter Property="Template"><Setter.Value>- <ControlTemplate TargetType="{x:Type RadioButton}">+ <ControlTemplate TargetType="{x:Type ToggleButton}"><Border x:Name="Bd" Background="Transparent" BorderBrush="Transparent" BorderThickness="1" SnapsToDevicePixels="True"><Path Data="{TemplateBinding Content}" Fill="{TemplateBinding Foreground}"HorizontalAlignment="Center" VerticalAlignment="Center" />@@ -80,22 +89,49 @@</Setter.Value></Setter></Style>++ <!-- the time axis: theme colours for the custom-drawn bar -->+ <Style TargetType="{x:Type controls:TimelineBar}">+ <Setter Property="Background" Value="{DynamicResource ScrollBarBackground}" />+ <Setter Property="Foreground" Value="{DynamicResource WindowForeground}" />+ <Setter Property="TickBrush" Value="{DynamicResource ControlBorder}" />+ <Setter Property="LabelBrush" Value="{DynamicResource GrayText}" />+ <Setter Property="AccentBrush" Value="{DynamicResource Accent}" />+ <Setter Property="Margin" Value="4,2" />+ </Style></UserControl.Resources><UserControl.CommandBindings><CommandBinding Command="MediaCommands.Play" CanExecute="CanPlay" Executed="OnPlay" /><CommandBinding Command="MediaCommands.Pause" CanExecute="CanPause" Executed="OnPause" /><CommandBinding Command="MediaCommands.TogglePlayPause" CanExecute="CanTogglePlayPause" Executed="OnTogglePlayPause" />+ <!-- Home/End are gestures of the commands, the letter keys are the InputBindings below; CanTransport refuses all of them inside a text box -->+ <CommandBinding Command="{x:Static commands:PreviewCommands.StepBack}" CanExecute="CanTransport" Executed="OnStepBack" />+ <CommandBinding Command="{x:Static commands:PreviewCommands.StepForward}" CanExecute="CanTransport" Executed="OnStepForward" />+ <CommandBinding Command="{x:Static commands:PreviewCommands.GoToStart}" CanExecute="CanTransport" Executed="OnGoToStart" />+ <CommandBinding Command="{x:Static commands:PreviewCommands.GoToEnd}" CanExecute="CanTransport" Executed="OnGoToEnd" />+ <CommandBinding Command="{x:Static commands:PreviewCommands.SetInPoint}" CanExecute="CanEditRange" Executed="OnSetInPoint" />+ <CommandBinding Command="{x:Static commands:PreviewCommands.SetOutPoint}" CanExecute="CanEditRange" Executed="OnSetOutPoint" />+ <CommandBinding Command="{x:Static commands:PreviewCommands.ClearRange}" CanExecute="CanClearRange" Executed="OnClearRange" />+ <CommandBinding Command="{x:Static commands:PreviewCommands.ToggleLoop}" CanExecute="CanTransport" Executed="OnToggleLoop" /></UserControl.CommandBindings>+ <!-- plain letters are not valid KeyGestures on a command, so these live here; CanTransport keeps them out of text boxes --><UserControl.InputBindings><KeyBinding Key="Space" Command="MediaCommands.TogglePlayPause" />+ <KeyBinding Key="OemComma" Command="{x:Static commands:PreviewCommands.StepBack}" />+ <KeyBinding Key="OemPeriod" Command="{x:Static commands:PreviewCommands.StepForward}" />+ <KeyBinding Key="I" Command="{x:Static commands:PreviewCommands.SetInPoint}" />+ <KeyBinding Key="O" Command="{x:Static commands:PreviewCommands.SetOutPoint}" />+ <KeyBinding Key="X" Command="{x:Static commands:PreviewCommands.ClearRange}" />+ <KeyBinding Key="L" Command="{x:Static commands:PreviewCommands.ToggleLoop}" /></UserControl.InputBindings><DockPanel>- <!-- transport bar: play, pause, scrubber, frame readout, speed, split.- Tab order (TabIndex) is left to right: play, pause, scrubber, speed, split; the DockPanel- declares the right-docked items first, so it cannot be the declaration order. -->+ <!-- transport bar: play, pause, frame steps, in/out/clear, loop, frame and step readout, speed,+ split. Tab order (TabIndex) is left to right; the DockPanel declares the right-docked items+ first, so it cannot be the declaration order. The timeline is the row above (declared after+ this one, since both dock to the bottom) and follows in the tab order. --><Border DockPanel.Dock="Bottom" BorderBrush="{DynamicResource ToolWindowBorder}" BorderThickness="0,1,0,0" Padding="4,3"><DockPanel KeyboardNavigation.TabNavigation="Local"><Button x:Name="playButton" DockPanel.Dock="Left" TabIndex="1" Style="{StaticResource TransportButton}" Content="{StaticResource PlayGeometry}"@@ -105,30 +141,52 @@Command="MediaCommands.Pause" ToolTip="{DynamicResource TipPreviewPause}"AutomationProperties.Name="{DynamicResource TipPreviewPause}" AutomationProperties.AutomationId="PreviewPause" /><Rectangle DockPanel.Dock="Left" Width="1" Margin="4,2" Fill="{DynamicResource ToolWindowBorder}" />+ <Button DockPanel.Dock="Left" TabIndex="3" Style="{StaticResource TransportButton}" Content="{StaticResource StepBackGeometry}"+ Command="{x:Static commands:PreviewCommands.StepBack}" ToolTip="{DynamicResource TipPreviewStepBack}"+ AutomationProperties.Name="{DynamicResource TipPreviewStepBack}" AutomationProperties.AutomationId="PreviewStepBack" />+ <Button DockPanel.Dock="Left" TabIndex="4" Style="{StaticResource TransportButton}" Content="{StaticResource StepForwardGeometry}"+ Command="{x:Static commands:PreviewCommands.StepForward}" ToolTip="{DynamicResource TipPreviewStepForward}"+ AutomationProperties.Name="{DynamicResource TipPreviewStepForward}" AutomationProperties.AutomationId="PreviewStepForward" />+ <Rectangle DockPanel.Dock="Left" Width="1" Margin="4,2" Fill="{DynamicResource ToolWindowBorder}" />+ <Button DockPanel.Dock="Left" TabIndex="5" Style="{StaticResource TransportButton}" Content="{StaticResource SetInGeometry}"+ Command="{x:Static commands:PreviewCommands.SetInPoint}" ToolTip="{DynamicResource TipPreviewSetIn}"+ AutomationProperties.Name="{DynamicResource TipPreviewSetIn}" AutomationProperties.AutomationId="PreviewSetIn" />+ <Button DockPanel.Dock="Left" TabIndex="6" Style="{StaticResource TransportButton}" Content="{StaticResource SetOutGeometry}"+ Command="{x:Static commands:PreviewCommands.SetOutPoint}" ToolTip="{DynamicResource TipPreviewSetOut}"+ AutomationProperties.Name="{DynamicResource TipPreviewSetOut}" AutomationProperties.AutomationId="PreviewSetOut" />+ <Button DockPanel.Dock="Left" TabIndex="7" Style="{StaticResource TransportButton}" Content="{StaticResource ClearRangeGeometry}"+ Command="{x:Static commands:PreviewCommands.ClearRange}" ToolTip="{DynamicResource TipPreviewClearRange}"+ AutomationProperties.Name="{DynamicResource TipPreviewClearRange}" AutomationProperties.AutomationId="PreviewClearRange" />+ <ToggleButton DockPanel.Dock="Left" TabIndex="8" Style="{StaticResource TransportToggle}" Content="{StaticResource LoopGeometry}"+ IsChecked="{Binding IsLooping, ElementName=pane}" ToolTip="{DynamicResource TipPreviewLoop}"+ AutomationProperties.Name="{DynamicResource TipPreviewLoop}" AutomationProperties.AutomationId="PreviewLoop" />+ <Rectangle DockPanel.Dock="Left" Width="1" Margin="4,2" Fill="{DynamicResource ToolWindowBorder}" /><!-- right-docked items: the first declared is the rightmost --><!-- one tab stop, the checked radio (IsTabStop follows IsChecked); the arrow keys move to theneighbour and check it, in code, since WPF's directional navigation skips non-tab-stops -->- <StackPanel x:Name="splitGroup" DockPanel.Dock="Right" Orientation="Horizontal" KeyboardNavigation.TabIndex="5"+ <StackPanel x:Name="splitGroup" DockPanel.Dock="Right" Orientation="Horizontal" KeyboardNavigation.TabIndex="10"KeyDown="OnSplitGroupKeyDown">- <RadioButton Style="{StaticResource TransportRadio}" Content="{StaticResource SideBySideGeometry}" GroupName="Split"+ <RadioButton Style="{StaticResource TransportToggle}" Content="{StaticResource SideBySideGeometry}" GroupName="Split"ToolTip="{DynamicResource TipPreviewSideBySide}"AutomationProperties.Name="{DynamicResource TipPreviewSideBySide}" AutomationProperties.AutomationId="PreviewSideBySide"IsChecked="{Binding Orientation, ElementName=pane, Converter={StaticResource EnumBoolean}, ConverterParameter={x:Static Orientation.Horizontal}}"IsTabStop="{Binding IsChecked, RelativeSource={RelativeSource Self}, Mode=OneWay}" />- <RadioButton Style="{StaticResource TransportRadio}" Content="{StaticResource StackedGeometry}" GroupName="Split"+ <RadioButton Style="{StaticResource TransportToggle}" Content="{StaticResource StackedGeometry}" GroupName="Split"ToolTip="{DynamicResource TipPreviewStacked}"AutomationProperties.Name="{DynamicResource TipPreviewStacked}" AutomationProperties.AutomationId="PreviewStacked"IsChecked="{Binding Orientation, ElementName=pane, Converter={StaticResource EnumBoolean}, ConverterParameter={x:Static Orientation.Vertical}}"IsTabStop="{Binding IsChecked, RelativeSource={RelativeSource Self}, Mode=OneWay}" /></StackPanel><Rectangle DockPanel.Dock="Right" Width="1" Margin="4,2" Fill="{DynamicResource ToolWindowBorder}" />- <ComboBox x:Name="speedBox" DockPanel.Dock="Right" TabIndex="4" Width="64" IsEditable="True" ItemsSource="{x:Static local:PreviewPane.SpeedPresets}"+ <ComboBox x:Name="speedBox" DockPanel.Dock="Right" TabIndex="9" Width="64" IsEditable="True" ItemsSource="{x:Static local:PreviewPane.SpeedPresets}"Text="{Binding Speed, ElementName=pane, Mode=TwoWay, Converter={StaticResource DoubleText}}" ToolTip="{DynamicResource TipPreviewSpeed}"AutomationProperties.Name="{DynamicResource LabelPreviewSpeed}" AutomationProperties.AutomationId="PreviewSpeed"PreviewKeyDown="OnSpeedBoxPreviewKeyDown" /><TextBlock DockPanel.Dock="Right" Style="{StaticResource FormLabel}" Margin="8,0,4,0" Text="{DynamicResource LabelPreviewSpeed}" />- <TextBlock DockPanel.Dock="Right" Style="{StaticResource FormValue}" MinWidth="90" TextAlignment="Right" ToolTip="{DynamicResource TipPreviewFrame}"++ <!-- readout: "frame / last" and, dimmer, the simulation step of that frame -->+ <TextBlock DockPanel.Dock="Left" Style="{StaticResource FormLabel}" Margin="4,0" ToolTip="{DynamicResource TipPreviewFrame}"AutomationProperties.AutomationId="PreviewFrame"><TextBlock.Text><MultiBinding StringFormat="{}{0} / {1}">@@ -137,14 +195,30 @@</MultiBinding></TextBlock.Text></TextBlock>-- <!-- the scrubber takes what is left; Left/Right step a frame, PageUp/PageDown ten, Home/End to the ends -->- <Slider TabIndex="3" Margin="4,0" Minimum="0" Maximum="{Binding LastFrame, ElementName=pane}" Value="{Binding Position, ElementName=pane}"- SmallChange="1" LargeChange="10" ToolTip="{DynamicResource TipPreviewScrub}"- AutomationProperties.Name="{DynamicResource TipPreviewScrub}" AutomationProperties.AutomationId="PreviewScrub" />+ <TextBlock DockPanel.Dock="Left" Style="{StaticResource FormValue}" ToolTip="{DynamicResource TipPreviewStep}"+ AutomationProperties.AutomationId="PreviewStep">+ <Run Text="{DynamicResource LabelPreviewStep}" /><Run Text=" " /><Run>+ <Run.Text>+ <MultiBinding Converter="{StaticResource FrameToStep}" Mode="OneWay">+ <Binding Path="Position" ElementName="pane" />+ <Binding Path="Project.Simulation.VisualizeEvery" ElementName="pane" />+ </MultiBinding>+ </Run.Text>+ </Run>+ </TextBlock>+ <Rectangle Fill="Transparent" /></DockPanel></Border>+ <!-- the time axis, full width above the transport bar -->+ <controls:TimelineBar x:Name="timeline" DockPanel.Dock="Bottom"+ Maximum="{Binding LastFrame, ElementName=pane}" Value="{Binding Position, ElementName=pane}"+ RangeStart="{Binding InPoint, ElementName=pane}" RangeEnd="{Binding OutPoint, ElementName=pane}"+ SetRangeStartCommand="{x:Static commands:PreviewCommands.SetInPoint}"+ SetRangeEndCommand="{x:Static commands:PreviewCommands.SetOutPoint}"+ ToolTip="{DynamicResource TipPreviewTimeline}"+ AutomationProperties.Name="{DynamicResource TipPreviewTimeline}" AutomationProperties.AutomationId="PreviewTimeline" />+<!-- the two pictures, side by side (columns 0 and 2) or stacked (rows 0 and 2), with a splitter inthe middle definition. The unused dimension is bridged by spanning all three of itsdefinitions, so a drag in one orientation survives a switch to the other. Each picture isdiff --git a/WaveDude.WPF/Panes/PreviewPane.xaml.cs b/WaveDude.WPF/Panes/PreviewPane.xaml.csindex ea87226..568a2ed 100644--- a/WaveDude.WPF/Panes/PreviewPane.xaml.cs+++ b/WaveDude.WPF/Panes/PreviewPane.xaml.cs@@ -8,6 +8,7 @@ using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Threading;using WaveDude.Model;+using WaveDude.WPF.Commands;using WaveDude.WPF.Converters;namespace WaveDude.WPF.Panes;@@ -18,7 +19,10 @@ namespace WaveDude.WPF.Panes;/// speed. Dummy stage: the pictures are fixed placeholders and playing only advances/// <see cref="Position"/>; the render pipeline that will feed <see cref="FieldImage"/> and/// <see cref="IntensityImage"/> per frame does not exist yet. <see cref="FrameCount"/> follows-/// the project's step count and visualisation interval through a binding.+/// the project's step count and visualisation interval through a binding, and so do the+/// <see cref="InPoint"/>/<see cref="OutPoint"/> of the export range (<c>Display.ExportFrom/To</c>,+/// in steps; the <see cref="PreviewCommands"/> write them). Playback runs between the two,+/// looping when <see cref="IsLooping"/>./// </summary>/// <remarks>/// Playback runs on a <see cref="DispatcherTimer"/> on the UI thread: a speed of 1 advances@@ -79,6 +83,18 @@ public partial class PreviewPane : UserControlnameof(Speed), typeof(double), typeof(PreviewPane),new FrameworkPropertyMetadata(1.0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, null, CoerceSpeed));+ /// <summary>Identifies the <see cref="InPoint"/> property.</summary>+ public static readonly DependencyProperty InPointProperty = DependencyProperty.Register(+ nameof(InPoint), typeof(int), typeof(PreviewPane), new PropertyMetadata(0));++ /// <summary>Identifies the <see cref="OutPoint"/> property.</summary>+ public static readonly DependencyProperty OutPointProperty = DependencyProperty.Register(+ nameof(OutPoint), typeof(int), typeof(PreviewPane), new PropertyMetadata(0));++ /// <summary>Identifies the <see cref="IsLooping"/> property.</summary>+ public static readonly DependencyProperty IsLoopingProperty = DependencyProperty.Register(+ nameof(IsLooping), typeof(bool), typeof(PreviewPane), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));+/// <summary>Identifies the <see cref="Orientation"/> property.</summary>public static readonly DependencyProperty OrientationProperty = DependencyProperty.Register(nameof(Orientation), typeof(Orientation), typeof(PreviewPane),@@ -113,11 +129,28 @@ public partial class PreviewPane : UserControl},});+ // in/out points in frames from the model's steps; "end" makes an ExportTo of 0 the last frame+ SetBinding(InPointProperty, RangeBinding(nameof(Display.ExportFrom), null));+ SetBinding(OutPointProperty, RangeBinding(nameof(Display.ExportTo), "end"));+_timer = new DispatcherTimer(DispatcherPriority.Render) { Interval = TimeSpan.FromSeconds(1.0 / 60.0) };_timer.Tick += OnTick;Unloaded += (_, _) => IsPlaying = false;}+ private MultiBinding RangeBinding(string stepProperty, string? parameter) => new()+ {+ Converter = new StepToFrameConverter(),+ ConverterParameter = parameter,+ Mode = BindingMode.OneWay,+ Bindings =+ {+ new Binding($"{nameof(Project)}.{nameof(Model.Project.Display)}.{stepProperty}") { Source = this },+ new Binding($"{nameof(Project)}.{nameof(Model.Project.Simulation)}.{nameof(Simulation.VisualizeEvery)}") { Source = this },+ new Binding(nameof(LastFrame)) { Source = this },+ },+ };+/// <summary>The project whose run is shown; null shows the placeholders with a single frame.</summary>public Project? Project{@@ -160,6 +193,27 @@ public partial class PreviewPane : UserControlset => SetValue(SpeedProperty, value);}+ /// <summary>First frame of the export/loop range; 0 while no in point is set. Follows the model.</summary>+ public int InPoint+ {+ get => (int)GetValue(InPointProperty);+ private set => SetValue(InPointProperty, value);+ }++ /// <summary>Last frame of the export/loop range; <see cref="LastFrame"/> while no out point is set. Follows the model.</summary>+ public int OutPoint+ {+ get => (int)GetValue(OutPointProperty);+ private set => SetValue(OutPointProperty, value);+ }++ /// <summary>Whether playback wraps from the out point back to the in point instead of stopping.</summary>+ public bool IsLooping+ {+ get => (bool)GetValue(IsLoopingProperty);+ set => SetValue(IsLoopingProperty, value);+ }+/// <summary>How the two pictures are split: <see cref="Orientation.Horizontal"/> side by side, <see cref="Orientation.Vertical"/> field above intensity.</summary>public Orientation Orientation{@@ -203,9 +257,9 @@ public partial class PreviewPane : UserControlvar pane = (PreviewPane)d;if ((bool)e.NewValue){- if (pane.Position >= pane.LastFrame)+ if (pane.Position >= pane.OutPoint){- pane.Position = 0; // play again from the start+ pane.Position = pane.InPoint; // play the range again from its start}pane._carry = 0.0;pane._clock.Restart();@@ -237,7 +291,10 @@ public partial class PreviewPane : UserControl}}- /// <summary>Advances <see cref="Position"/> by the frames elapsed since the previous tick; stops at the last frame.</summary>+ /// <summary>+ /// Advances <see cref="Position"/> by the frames elapsed since the previous tick. At the out+ /// point playback stops, or wraps to the in point when <see cref="IsLooping"/>.+ /// </summary>private void OnTick(object? sender, EventArgs e){double seconds = _clock.Elapsed.TotalSeconds;@@ -250,14 +307,19 @@ public partial class PreviewPane : UserControl}_carry -= frames;int next = Position + frames;- if (next >= LastFrame)+ int end = OutPoint;+ if (next < end){- Position = LastFrame;- IsPlaying = false;+ Position = next;+ }+ else if (IsLooping && end > InPoint)+ {+ Position = InPoint + (next - end) % (end - InPoint);}else{- Position = next;+ Position = end;+ IsPlaying = false;}}@@ -273,6 +335,68 @@ public partial class PreviewPane : UserControlprivate void OnTogglePlayPause(object sender, ExecutedRoutedEventArgs e) => IsPlaying = !IsPlaying;+ // ---------------------------------------------------------------- transport commands++ /// <summary>The letter and punctuation gestures must not fire while the user types in a text box.</summary>+ private void CanTransport(object sender, CanExecuteRoutedEventArgs e) =>+ e.CanExecute = Project != null && e.OriginalSource is not TextBoxBase;++ private void OnStepBack(object sender, ExecutedRoutedEventArgs e) => Position -= 1;++ private void OnStepForward(object sender, ExecutedRoutedEventArgs e) => Position += 1;++ private void OnGoToStart(object sender, ExecutedRoutedEventArgs e) => Position = InPoint;++ private void OnGoToEnd(object sender, ExecutedRoutedEventArgs e) => Position = OutPoint;++ private void CanEditRange(object sender, CanExecuteRoutedEventArgs e) =>+ e.CanExecute = Project != null && LastFrame > 0 && e.OriginalSource is not TextBoxBase;++ /// <summary>The frame a range command was given, or the frame shown.</summary>+ private int FrameOf(ExecutedRoutedEventArgs e) => e.Parameter is int frame ? Math.Clamp(frame, 0, LastFrame) : Position;++ /// <summary>+ /// Sets the in point, in steps, on the model. An in point past the out point clears the out+ /// point (0 = end of the run), so the range stays ordered.+ /// </summary>+ private void OnSetInPoint(object sender, ExecutedRoutedEventArgs e)+ {+ Display display = Project!.Display;+ int step = FrameOf(e) * Project.Simulation.VisualizeEvery;+ if (display.ExportTo != 0 && display.ExportTo <= step)+ {+ display.ExportTo = 0;+ }+ display.ExportFrom = step;+ }++ /// <summary>+ /// Sets the out point on the model; the last frame means "to the end" and is stored as 0. An+ /// out point before the in point clears the in point.+ /// </summary>+ private void OnSetOutPoint(object sender, ExecutedRoutedEventArgs e)+ {+ Display display = Project!.Display;+ int frame = FrameOf(e);+ int step = frame >= LastFrame ? 0 : frame * Project.Simulation.VisualizeEvery;+ if (step != 0 && display.ExportFrom >= step)+ {+ display.ExportFrom = 0;+ }+ display.ExportTo = step;+ }++ private void CanClearRange(object sender, CanExecuteRoutedEventArgs e) =>+ e.CanExecute = Project is { Display: { } display } && (display.ExportFrom != 0 || display.ExportTo != 0) && e.OriginalSource is not TextBoxBase;++ private void OnClearRange(object sender, ExecutedRoutedEventArgs e)+ {+ Project!.Display.ExportFrom = 0;+ Project.Display.ExportTo = 0;+ }++ private void OnToggleLoop(object sender, ExecutedRoutedEventArgs e) => IsLooping = !IsLooping;+/// <summary>Space inside the speed text box is neither a digit nor the play/pause toggle: swallowed.</summary>private void OnSpeedBoxPreviewKeyDown(object sender, KeyEventArgs e){diff --git a/WaveDude.WPF/Strings/Strings.EN.xaml b/WaveDude.WPF/Strings/Strings.EN.xamlindex f6aceba..36b4002 100644--- a/WaveDude.WPF/Strings/Strings.EN.xaml+++ b/WaveDude.WPF/Strings/Strings.EN.xaml@@ -62,6 +62,15 @@<s:String x:Key="TipPreviewSpeed">Playback speed: pick a factor or type one</s:String><s:String x:Key="TipPreviewSideBySide">Field and intensity side by side</s:String><s:String x:Key="TipPreviewStacked">Field above intensity</s:String>+ <s:String x:Key="TipPreviewTimeline">Click or drag to scrub; drag a bracket to move the in or out point. Left/Right step a frame, PageUp/PageDown ten, Home/End jump to the in/out points</s:String>+ <s:String x:Key="TipPreviewStepBack">Previous frame (,)</s:String>+ <s:String x:Key="TipPreviewStepForward">Next frame (.)</s:String>+ <s:String x:Key="TipPreviewSetIn">Set the in point at this frame (I)</s:String>+ <s:String x:Key="TipPreviewSetOut">Set the out point at this frame (O)</s:String>+ <s:String x:Key="TipPreviewClearRange">Clear the in/out range (X)</s:String>+ <s:String x:Key="TipPreviewLoop">Loop playback between the in and out points (L)</s:String>+ <s:String x:Key="LabelPreviewStep">step</s:String>+ <s:String x:Key="TipPreviewStep">Simulation step of the frame shown</s:String><s:String x:Key="TipPreviewSplitter">Drag or use the arrow keys to resize; double-click or Enter resets to half</s:String><s:String x:Key="Ready">Ready</s:String><s:String x:Key="NoSelection">No selection</s:String>@@ -79,6 +88,7 @@<s:String x:Key="SectionField">Field</s:String><s:String x:Key="SectionIntensity">Intensity</s:String><s:String x:Key="SectionVideo">Video export</s:String>+ <s:String x:Key="SectionExportRange">Export range</s:String><s:String x:Key="SectionPosition">Position</s:String><s:String x:Key="SectionWave">Wave</s:String><s:String x:Key="SectionTiming">Timing</s:String>diff --git a/WaveDude.WPF/Themes/Dark.xaml b/WaveDude.WPF/Themes/Dark.xamlindex 67cd768..41f401c 100644--- a/WaveDude.WPF/Themes/Dark.xaml+++ b/WaveDude.WPF/Themes/Dark.xaml@@ -102,6 +102,10 @@<SolidColorBrush x:Key="ComboBoxBackground" Color="#FF333337" /><SolidColorBrush x:Key="ComboBoxBorder" Color="#FF434346" /><SolidColorBrush x:Key="ComboBoxHover" Color="#FF3F3F46" />+ <!-- an open list sits on the combo's own grey; the item under the mouse or keyboard is the accent, like a tree selection -->+ <SolidColorBrush x:Key="ComboBoxListBackground" Color="#FF333337" />+ <SolidColorBrush x:Key="ComboBoxItemHover" Color="#FF3399FF" />+ <SolidColorBrush x:Key="ComboBoxItemHoverForeground" Color="#FFFFFFFF" /><SolidColorBrush x:Key="ComboBoxGlyph" Color="#FFF1F1F1" /><SolidColorBrush x:Key="CheckBoxBackground" Color="#FF333337" /><SolidColorBrush x:Key="CheckBoxBorder" Color="#FF6D6D70" />diff --git a/WaveDude.WPF/Themes/Editors.xaml b/WaveDude.WPF/Themes/Editors.xamlindex 2d937ca..b0369d6 100644--- a/WaveDude.WPF/Themes/Editors.xaml+++ b/WaveDude.WPF/Themes/Editors.xaml@@ -85,8 +85,8 @@</Border><ControlTemplate.Triggers><Trigger Property="IsHighlighted" Value="True">- <Setter TargetName="Bd" Property="Background" Value="{DynamicResource MenuItemHover}" />- <Setter Property="Foreground" Value="{DynamicResource MenuItemHoverForeground}" />+ <Setter TargetName="Bd" Property="Background" Value="{DynamicResource ComboBoxItemHover}" />+ <Setter Property="Foreground" Value="{DynamicResource ComboBoxItemHoverForeground}" /></Trigger></ControlTemplate.Triggers></ControlTemplate>@@ -139,7 +139,7 @@Padding="{TemplateBinding Padding}" IsReadOnly="{TemplateBinding IsReadOnly}" /><Popup x:Name="PART_Popup" Placement="Bottom" IsOpen="{TemplateBinding IsDropDownOpen}"AllowsTransparency="True" PopupAnimation="None" Focusable="False">- <Border Background="{DynamicResource MenuPopupBackground}" BorderBrush="{DynamicResource MenuPopupBorder}"+ <Border Background="{DynamicResource ComboBoxListBackground}" BorderBrush="{DynamicResource MenuPopupBorder}"BorderThickness="1" MinWidth="{TemplateBinding ActualWidth}" MaxHeight="{TemplateBinding MaxDropDownHeight}"SnapsToDevicePixels="True"><ScrollViewer>diff --git a/WaveDude.WPF/Themes/Light.xaml b/WaveDude.WPF/Themes/Light.xamlindex e9731cd..3246726 100644--- a/WaveDude.WPF/Themes/Light.xaml+++ b/WaveDude.WPF/Themes/Light.xaml@@ -102,6 +102,10 @@<SolidColorBrush x:Key="ComboBoxBackground" Color="#FFFFFFFF" /><SolidColorBrush x:Key="ComboBoxBorder" Color="#FFCCCEDB" /><SolidColorBrush x:Key="ComboBoxHover" Color="#FFE6E7ED" />+ <!-- an open list sits on the combo's own white; the item under the mouse or keyboard is the accent, like a tree selection -->+ <SolidColorBrush x:Key="ComboBoxListBackground" Color="#FFFFFFFF" />+ <SolidColorBrush x:Key="ComboBoxItemHover" Color="#FF3399FF" />+ <SolidColorBrush x:Key="ComboBoxItemHoverForeground" Color="#FFFFFFFF" /><SolidColorBrush x:Key="ComboBoxGlyph" Color="#FF1E1E1E" /><SolidColorBrush x:Key="CheckBoxBackground" Color="#FFFFFFFF" /><SolidColorBrush x:Key="CheckBoxBorder" Color="#FF9A9A9E" />diff --git a/WaveDude.WPF/Views/DisplayView.xaml b/WaveDude.WPF/Views/DisplayView.xamlindex ae09ad7..6e04913 100644--- a/WaveDude.WPF/Views/DisplayView.xaml+++ b/WaveDude.WPF/Views/DisplayView.xaml@@ -14,6 +14,15 @@<TextBlock Style="{StaticResource FormSection}" Text="{DynamicResource SectionIntensity}" /><local:DisplayLayerView DataContext="{Binding Intensity}" />+ <TextBlock Style="{StaticResource FormSection}" Text="{DynamicResource SectionExportRange}" />+ <controls:FormPanel>+ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Display.ExportFrom}" />+ <TextBox Text="{Binding ExportFrom}" ToolTip="{meta:Hint model:Display.ExportFrom}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Display.ExportTo}" />+ <TextBox Text="{Binding ExportTo}" ToolTip="{meta:Hint model:Display.ExportTo}" />+ </controls:FormPanel>+<TextBlock Style="{StaticResource FormSection}" Text="{DynamicResource SectionVideo}" /><controls:FormPanel DataContext="{Binding Video}"><TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Video.Fps}" />diff --git a/WaveDude/Model/Display.cs b/WaveDude/Model/Display.csindex 899008b..b210799 100644--- a/WaveDude/Model/Display.cs+++ b/WaveDude/Model/Display.cs@@ -17,6 +17,8 @@ public sealed class Display : ObservableObjectprivate DisplayLayer _field = new() { ColorScheme = DefaultFieldColorScheme, BlackLevel = DefaultFieldBlackLevel };private DisplayLayer _intensity = new() { ColorScheme = DefaultIntensityColorScheme };private Video _video = new();+ private int _exportFrom;+ private int _exportTo;/// <summary>Rendering of the wave field.</summary>[XmlElement]@@ -48,6 +50,30 @@ public sealed class Display : ObservableObjectset => SetProperty(ref _video, value);}+ /// <summary>First simulation step of the exported range (and of loop playback); 0 is the start of the run.</summary>+ [XmlAttribute]+ [DefaultValue(0)]+ [Category("Export")]+ [DisplayName("From step")]+ [Description("First simulation step of the exported range; 0 is the start of the run.")]+ public int ExportFrom+ {+ get => _exportFrom;+ set => SetProperty(ref _exportFrom, value);+ }++ /// <summary>Last simulation step of the exported range (and of loop playback); 0 means the end of the run.</summary>+ [XmlAttribute]+ [DefaultValue(0)]+ [Category("Export")]+ [DisplayName("To step")]+ [Description("Last simulation step of the exported range; 0 means the end of the run.")]+ public int ExportTo+ {+ get => _exportTo;+ set => SetProperty(ref _exportTo, value);+ }+/// <summary>Tells <see cref="XmlSerializer"/> to leave all-default video settings out of the file.</summary>public bool ShouldSerializeVideo() => Video.Fps != Video.DefaultFps || Video.Quality != Video.DefaultQuality;@@ -57,6 +83,12 @@ public sealed class Display : ObservableObjectField.Normalize(DefaultFieldColorScheme);Intensity.Normalize(DefaultIntensityColorScheme);Video.Normalize();+ ExportFrom = Math.Max(0, ExportFrom);+ ExportTo = Math.Max(0, ExportTo);+ if (ExportTo != 0 && ExportTo < ExportFrom)+ {+ ExportTo = 0;+ }}/// <summary>The two colour scheme names, for display in a property grid.</summary>diff --git a/_tools/ui_check/ComboListShot.ps1 b/_tools/ui_check/ComboListShot.ps1new file mode 100644index 0000000..b39922c--- /dev/null+++ b/_tools/ui_check/ComboListShot.ps1@@ -0,0 +1,53 @@+# Opens the preview's speed combo by keyboard (Tab to it, F4, Down) and saves a screenshot of the+# open list, for looking at list colours. Keystrokes are posted to the app window; the popup has+# no window handle of its own in UI Automation, so its screen rectangle (from the item bounds) is+# copied instead. The app never takes the foreground.+#+# powershell -ExecutionPolicy Bypass -File _tools\ui_check\ComboListShot.ps1 [-Exe <path>] [-Shot <png>]++param(+ [string]$Exe = (Join-Path $PSScriptRoot "..\..\WaveDude.WPF\bin\Debug\net10.0-windows\WaveDude.WPF.exe"),+ [string]$Shot = (Join-Path $env:TEMP "wavedude_combo_list.png")+)+Add-Type -AssemblyName UIAutomationClient, UIAutomationTypes, System.Drawing, System.Windows.Forms+Add-Type -TypeDefinition @"+using System; using System.Runtime.InteropServices;+public static class N {+ [DllImport("user32.dll")] static extern bool PostMessage(IntPtr h, uint m, IntPtr w, IntPtr l);+ [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();+ [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr h, int c);+ public static void Key(IntPtr h, int vk) { PostMessage(h, 0x100, (IntPtr)vk, (IntPtr)1); PostMessage(h, 0x101, (IntPtr)vk, (IntPtr)(1 | (1 << 30) | (1 << 31))); }+}+"@+$A = [System.Windows.Automation.AutomationElement]+$p = Start-Process -FilePath $Exe -PassThru+$win = $null+for ($i = 0; $i -lt 100 -and $win -eq $null; $i++) { Start-Sleep -Milliseconds 200; $win = $A::RootElement.FindFirst("Children", (New-Object System.Windows.Automation.PropertyCondition($A::ProcessIdProperty, $p.Id))) }+$p.Refresh(); $hwnd = $p.MainWindowHandle; Start-Sleep -Milliseconds 800+$park = New-Object System.Windows.Forms.Form; $park.StartPosition = "Manual"; $park.Location = New-Object System.Drawing.Point(-3000, -3000); $park.Size = New-Object System.Drawing.Size(10, 10); $park.ShowInTaskbar = $false+$park.Show(); $park.Activate(); [System.Windows.Forms.Application]::DoEvents(); Start-Sleep -Milliseconds 400+for ($i = 0; $i -lt 3 -and [N]::GetForegroundWindow() -eq $hwnd; $i++) { [N]::ShowWindow($hwnd, 6) | Out-Null; Start-Sleep -Milliseconds 300; $park.Activate(); [System.Windows.Forms.Application]::DoEvents(); Start-Sleep -Milliseconds 300; [N]::ShowWindow($hwnd, 4) | Out-Null; Start-Sleep -Milliseconds 500 }+try {+ $speed = $win.FindFirst("Descendants", (New-Object System.Windows.Automation.PropertyCondition($A::AutomationIdProperty, "PreviewSpeed")))+ for ($i = 0; $i -lt 60; $i++) {+ $c = New-Object System.Windows.Automation.PropertyCondition($A::HasKeyboardFocusProperty, $true)+ if ($speed.FindFirst("Descendants", $c) -ne $null) { break }+ [N]::Key($hwnd, 0x09); Start-Sleep -Milliseconds 150+ }+ [N]::Key($hwnd, 0x73); Start-Sleep -Milliseconds 500 # F4 opens the list+ [N]::Key($hwnd, 0x28); Start-Sleep -Milliseconds 300 # Down highlights an item+ $items = $speed.FindAll("Descendants", (New-Object System.Windows.Automation.PropertyCondition($A::ControlTypeProperty, [System.Windows.Automation.ControlType]::ListItem)))+ "list items: " + (($items | ForEach-Object { $n = $_.Current.Name; if ($_.Current.HasKeyboardFocus) { $n += "*" }; $n }) -join " ")+ $rects = $items | ForEach-Object { $_.Current.BoundingRectangle }+ $l = ($rects | Measure-Object -Property Left -Minimum).Minimum; $t = ($rects | Measure-Object -Property Top -Minimum).Minimum+ $r = ($rects | Measure-Object -Property Right -Maximum).Maximum; $b = ($rects | Measure-Object -Property Bottom -Maximum).Maximum+ $bmp = New-Object System.Drawing.Bitmap ([int]($r - $l + 8)), ([int]($b - $t + 8))+ $g = [System.Drawing.Graphics]::FromImage($bmp); $g.CopyFromScreen([int]($l - 4), [int]($t - 4), 0, 0, $bmp.Size); $g.Dispose()+ $bmp.Save($Shot, [System.Drawing.Imaging.ImageFormat]::Png); $bmp.Dispose()+ "screenshot: $Shot"+ "foreground is app: " + ([N]::GetForegroundWindow() -eq $hwnd)+ [N]::Key($hwnd, 0x1B)+}+finally {+ $p.CloseMainWindow() | Out-Null; if (-not $p.WaitForExit(5000)) { $p.Kill() }; $park.Close()+}diff --git a/_tools/ui_check/PreviewCheck.ps1 b/_tools/ui_check/PreviewCheck.ps1index 7bfe661..7a04e9f 100644--- a/_tools/ui_check/PreviewCheck.ps1+++ b/_tools/ui_check/PreviewCheck.ps1@@ -24,6 +24,7 @@ public static class Native[DllImport("user32.dll")] static extern bool GetWindowRect(IntPtr hwnd, out RECT rect);[DllImport("user32.dll")] static extern bool PostMessage(IntPtr hwnd, uint msg, IntPtr wParam, IntPtr lParam);[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();+ [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hwnd, int cmd);[StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left, Top, Right, Bottom; }// PW_RENDERFULLCONTENT: ask DWM for the composed content, which a hardware-rendered WPF window needs@@ -56,7 +57,8 @@ public static class Native$A = [System.Windows.Automation.AutomationElement]$VK_BACK = 0x08; $VK_TAB = 0x09; $VK_SPACE = 0x20; $VK_END = 0x23; $VK_HOME = 0x24-$VK_LEFT = 0x25; $VK_RIGHT = 0x27; $VK_PRIOR = 0x21; $VK_RETURN = 0x0D; $VK_ESCAPE = 0x1B; $VK_F4 = 0x73+$VK_LEFT = 0x25; $VK_RIGHT = 0x27; $VK_PRIOR = 0x21; $VK_NEXT = 0x22; $VK_RETURN = 0x0D; $VK_ESCAPE = 0x1B; $VK_F4 = 0x73+$VK_I = 0x49; $VK_O = 0x4F; $VK_X = 0x58; $VK_L = 0x4C; $VK_COMMA = 0xBC; $VK_PERIOD = 0xBE$script:failures = 0function Check([string]$name, [bool]$ok, [string]$detail = "") {@@ -70,9 +72,12 @@ function Foreground() {}function Find([string]$id) {$c = New-Object System.Windows.Automation.PropertyCondition($A::AutomationIdProperty, $id)- $e = $win.FindFirst([System.Windows.Automation.TreeScope]::Descendants, $c)- if ($e -eq $null) { throw "element '$id' not found" }- return $e+ for ($i = 0; $i -lt 10; $i++) {+ $e = $win.FindFirst([System.Windows.Automation.TreeScope]::Descendants, $c)+ if ($e -ne $null) { return $e }+ Start-Sleep -Milliseconds 200+ }+ throw "element '$id' not found"}function Pattern($e, [string]$name) {$type = [System.Windows.Automation.InvokePattern].Assembly.GetType("System.Windows.Automation." + $name + "Pattern", $true)@@ -84,8 +89,12 @@ function Playing() { return (Find "PreviewPause").Current.IsEnabled }function Selected([string]$id) { return (Pattern (Find $id) "SelectionItem").Current.IsSelected }function SpeedText() { return (Pattern (Find "PreviewSpeed") "Value").Current.Value }function Focused([string]$id) { return (Find $id).Current.HasKeyboardFocus }+function StepText() { return (Find "PreviewStep").Current.Name }+function Range() { $t = Find "PreviewTimeline"; return $t }+function LoopOn() { return (Pattern (Find "PreviewLoop") "Toggle").Current.ToggleState -eq [System.Windows.Automation.ToggleState]::On }function FocusedId() {- foreach ($id in "PreviewPlay", "PreviewPause", "PreviewScrub", "PreviewSpeed", "PreviewSideBySide", "PreviewStacked", "PreviewSplitter") {+ foreach ($id in "PreviewPlay", "PreviewPause", "PreviewStepBack", "PreviewStepForward", "PreviewSetIn", "PreviewSetOut", "PreviewClearRange", "PreviewLoop",+ "PreviewSpeed", "PreviewSideBySide", "PreviewStacked", "PreviewTimeline", "PreviewSplitter") {if (Focused $id) { return $id }}# the editable combo keeps focus in its inner text box@@ -93,6 +102,9 @@ function FocusedId() {if ((Find "PreviewSpeed").FindFirst([System.Windows.Automation.TreeScope]::Descendants, $c) -ne $null) { return "PreviewSpeed" }$other = $win.FindFirst([System.Windows.Automation.TreeScope]::Descendants, $c)if ($other -ne $null) { return "(other: " + $other.Current.ControlType.ProgrammaticName + " '" + $other.Current.Name + "')" }+ # nothing in the window reports focus: ask the system (only meaningful while the app is foreground)+ $fe = $A::FocusedElement+ if ($fe -ne $null -and $fe.Current.ProcessId -eq $p.Id) { return "(focused: " + $fe.Current.ControlType.ProgrammaticName + " '" + $fe.Current.Name + "' " + $fe.Current.ClassName + ")" }return "(none)"}function Key([int]$vk, [int]$settle = 150) { [Native]::Key($hwnd, $vk); Start-Sleep -Milliseconds $settle }@@ -128,6 +140,14 @@ $park.Size = New-Object System.Drawing.Size(10, 10)$park.ShowInTaskbar = $false$park.Show(); $park.Activate(); [System.Windows.Forms.Application]::DoEvents()Start-Sleep -Milliseconds 500+for ($i = 0; $i -lt 3 -and (Foreground) -eq "APP"; $i++) {+ [Native]::ShowWindow($hwnd, 6) | Out-Null # SW_MINIMIZE: the OS activates something else+ Start-Sleep -Milliseconds 300+ $park.Activate(); [System.Windows.Forms.Application]::DoEvents()+ Start-Sleep -Milliseconds 300+ [Native]::ShowWindow($hwnd, 4) | Out-Null # SW_SHOWNOACTIVATE+ Start-Sleep -Milliseconds 500+}Write-Output ("window: '{0}' foreground: {1}" -f $win.Current.Name, (Foreground))try {@@ -139,9 +159,9 @@ try {FocusOn "PreviewPlay"Check "Tab reaches play while the window stays inactive" (((FocusedId) -eq "PreviewPlay") -and ((Foreground) -ne "APP")) (FocusedId)$order = @()- for ($i = 0; $i -lt 5; $i++) { Key $VK_TAB 250; $order += (FocusedId) }- # pause is disabled while not playing and is skipped; the split group is one stop (its checked radio); the splitter; then the pane is left- Check "tab order play > scrubber > speed > split > splitter > out of the pane" (($order[0..3] -join ",") -eq "PreviewScrub,PreviewSpeed,PreviewSideBySide,PreviewSplitter" -and $order[4] -like "(other*") ($order -join ",")+ for ($i = 0; $i -lt 10; $i++) { Key $VK_TAB 250; $order += (FocusedId) }+ # pause and clear-range are disabled and skipped; the split group is one stop (its checked radio); timeline; splitter; then the pane is left+ Check "tab order play > step back/forward > in > out > loop > speed > split > timeline > splitter > out of the pane" (($order[0..8] -join ",") -eq "PreviewStepBack,PreviewStepForward,PreviewSetIn,PreviewSetOut,PreviewLoop,PreviewSpeed,PreviewSideBySide,PreviewTimeline,PreviewSplitter" -and $order[9] -like "(other*") ($order -join ",")FocusOn "PreviewPlay"Key $VK_SPACE 2000@@ -152,6 +172,7 @@ try {$held = PositionStart-Sleep -Milliseconds 700Check "Space on pause: position holds, focus handed back to play" (-not (Playing) -and (Position) -eq $held -and (Focused "PreviewPlay")) ("position {0}, focus {1}" -f $held, (FocusedId))+ Check "step readout shows frame x visualize every" ((StepText) -eq ("step {0}" -f ($held * 2))) (StepText)# ------------------------------------------------------------ speedFocusOn "PreviewSpeed"@@ -178,19 +199,59 @@ try {$delta = (Position) - $beforeCheck "speed 4: ~240 frames in 2 s" ($delta -ge 190 -and $delta -le 290) "delta $delta"- # ------------------------------------------------------------ scrubber- FocusOn "PreviewScrub"+ # ------------------------------------------------------------ timeline keys+ FocusOn "PreviewTimeline"Key $VK_END 300- Check "scrubber End goes to the last frame" ((Frame) -eq "1249 / 1249") (Frame)+ Check "timeline End goes to the last frame" ((Frame) -eq "1249 / 1249") (Frame)+ Check "step readout follows (last frame x visualize every)" ((StepText) -eq "step 2498") (StepText)Key $VK_HOME 200Key $VK_RIGHT; Key $VK_RIGHT 300- Check "scrubber Home then Right twice gives frame 2" ((Position) -eq 2) (Frame)+ Check "timeline Home then Right twice gives frame 2" ((Position) -eq 2) (Frame)Key $VK_PRIOR 300- Check "scrubber PageUp steps 10 frames" ((Position) -eq 12) (Frame)+ Check "timeline PageUp steps 10 frames" ((Position) -eq 12) (Frame)+ Key $VK_NEXT 300+ Check "timeline PageDown steps back 10 frames" ((Position) -eq 2) (Frame)Key $VK_SPACE 1000$playing = PlayingKey $VK_SPACE 300- Check "Space on the scrubber starts playback, Space again pauses" ($playing -and -not (Playing)) (Frame)+ Check "Space on the timeline starts playback, Space again pauses" ($playing -and -not (Playing)) (Frame)++ # ------------------------------------------------------------ frame steps and in/out range (gestures work from any transport control)+ FocusOn "PreviewPlay"+ Key $VK_HOME 200+ Key $VK_PERIOD; Key $VK_PERIOD; Key $VK_PERIOD 300+ Check "period steps forward three frames from play button" ((Position) -eq 3) (Frame)+ Key $VK_COMMA 300+ Check "comma steps back one frame" ((Position) -eq 2) (Frame)+ Key $VK_PRIOR 100 # no effect here: PageUp is only the timeline's key+ FocusOn "PreviewTimeline"+ Key $VK_HOME 100; Key $VK_PRIOR 300 # frame 10+ Key $VK_I 300+ Check "I sets the in point at frame 10 (clear range becomes enabled)" ((Find "PreviewClearRange").Current.IsEnabled) (Frame)+ Key $VK_END 300+ for ($i = 0; $i -lt 5; $i++) { Key $VK_LEFT 60 }+ Start-Sleep -Milliseconds 300+ Key $VK_O 300+ Check "O sets the out point at frame 1244" ((Position) -eq 1244) (Frame)+ Key $VK_HOME 300+ Check "Home now jumps to the in point" ((Position) -eq 10) (Frame)+ Key $VK_END 300+ Check "End now jumps to the out point" ((Position) -eq 1244) (Frame)+ Key $VK_HOME 200+ Key $VK_L 300+ Check "L turns looping on" (LoopOn)+ Key $VK_SPACE 2500 # 2.5 s at speed 4 = ~300 frames through a range of 1234: still inside, and still playing+ $pos = Position+ $still = Playing+ Key $VK_SPACE 300+ Check "looped playback stays inside the range and keeps running" ($still -and $pos -ge 10 -and $pos -le 1244) ("position {0}, playing {1}" -f $pos, $still)+ Key $VK_L 300+ Check "L turns looping off" (-not (LoopOn))+ Key $VK_X 300+ Check "X clears the range (clear range disabled again)" (-not (Find "PreviewClearRange").Current.IsEnabled)+ Key $VK_END 300+ Check "End is the last frame again" ((Position) -eq 1249) (Frame)+ Key $VK_HOME 300# ------------------------------------------------------------ splitFocusOn "PreviewSideBySide"@@ -204,8 +265,8 @@ try {[Native]::Capture($hwnd, $Shot)Write-Output "screenshot: $Shot"# Tab must enter the group at the checked radio, which is now the second one- FocusOn "PreviewScrub"- Key $VK_TAB; Key $VK_TAB 300+ FocusOn "PreviewSpeed"+ Key $VK_TAB 300Check "Tab enters the split group at the checked (stacked) radio" (Focused "PreviewStacked") (FocusedId)Key $VK_LEFT 400$fr = $field.Current.BoundingRectangle; $ir = $intensity.Current.BoundingRectangle