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#
Undo and redo of every project edit, and an Edit menu with Cut, Copy, Paste and Delete
Alexander Graef7039f9bf3b4f
diff --git a/WaveDudeNext.WPF/Commands/EditCommands.cs b/WaveDudeNext.WPF/Commands/EditCommands.csnew file mode 100644index 0000000..34cfad6--- /dev/null+++ b/WaveDudeNext.WPF/Commands/EditCommands.cs@@ -0,0 +1,42 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 Alexander Graef <[email protected]>+//+// This file is part of WaveDude Next, a 2D wave simulator.+//+// Based on the work of+// Jeroen Vleggaar (Huygens Optics), author of Wave Dude 2D, Copyright (C) 2026+// <https://www.youtube.com/@HuygensOptics>, <https://www.huygensoptics.com>+// 0x23 (Diffraction Limited), author of WaveSimulator2D+// <https://www.youtube.com/@DiffractionLimited>, <https://github.com/0x23/WaveSimulator2D>+//+// WaveDude Next is free software: you can redistribute it and/or modify it under+// the terms of the GNU General Public License as published by the Free Software+// Foundation, either version 3 of the License, or (at your option) any later+// version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or+// <https://www.gnu.org/licenses/>.++using System.Windows.Input;++namespace WaveDudeNext.WPF.Commands;++/// <summary>+/// The Edit menu's own commands, bound on the main window: undo and redo of project edits (handlers in+/// <c>MainWindow.History.cs</c>), with the usual shortcuts, and Delete (<c>MainWindow.Project.cs</c>). A text box being typed+/// in keeps its own Ctrl+Z for its text; Cut, Copy and Paste are WPF's <see cref="ApplicationCommands"/>, which text boxes handle.+/// </summary>+public static class EditCommands+{+ /// <summary>+ /// Deletes the selected text in the text box that has the focus, else removes the selected sources, parts, probes or+ /// schemes as the tree's Remove does. No gesture of its own: Del is the text box's and the tree's.+ /// </summary>+ public static readonly RoutedUICommand Delete = new("Delete", nameof(Delete), typeof(EditCommands));++ /// <summary>Takes the project back one step. Ctrl+Z.</summary>+ public static readonly RoutedUICommand Undo = new("Undo", nameof(Undo), typeof(EditCommands),+ [new KeyGesture(Key.Z, ModifierKeys.Control)]);++ /// <summary>Takes the project forward again one undone step. Ctrl+Y or Ctrl+Shift+Z.</summary>+ public static readonly RoutedUICommand Redo = new("Redo", nameof(Redo), typeof(EditCommands),+ [new KeyGesture(Key.Y, ModifierKeys.Control), new KeyGesture(Key.Z, ModifierKeys.Control | ModifierKeys.Shift)]);+}diff --git a/WaveDudeNext.WPF/MainWindow.History.cs b/WaveDudeNext.WPF/MainWindow.History.csnew file mode 100644index 0000000..e2ac5c0--- /dev/null+++ b/WaveDudeNext.WPF/MainWindow.History.cs@@ -0,0 +1,195 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 Alexander Graef <[email protected]>+//+// This file is part of WaveDude Next, a 2D wave simulator.+//+// Based on the work of+// Jeroen Vleggaar (Huygens Optics), author of Wave Dude 2D, Copyright (C) 2026+// <https://www.youtube.com/@HuygensOptics>, <https://www.huygensoptics.com>+// 0x23 (Diffraction Limited), author of WaveSimulator2D+// <https://www.youtube.com/@DiffractionLimited>, <https://github.com/0x23/WaveSimulator2D>+//+// WaveDude Next is free software: you can redistribute it and/or modify it under+// the terms of the GNU General Public License as published by the Free Software+// Foundation, either version 3 of the License, or (at your option) any later+// version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or+// <https://www.gnu.org/licenses/>.++using System.Collections;+using System.Windows.Input;+using System.Windows.Threading;+using WaveDudeNext.Model;+using WaveDudeNext.Rendering;++namespace WaveDudeNext.WPF;++/// <summary>+/// Undo and redo (2026-10-22, the user's request): a <see cref="ProjectHistory"/> per open project. An edit ends a step+/// after <see cref="RecordDelay"/> of quiet with no mouse button held, so a drag, a number box scrub or a held arrow key is+/// one step; Undo and Redo end a pending step first. A step written back is reported by the watcher like any edit (the+/// run goes stale, a scratch frame and the re-run follow), but not recorded again; the selection is carried over to the+/// restored objects by name, else by position. The project is dirty unless the current step is the saved one. UI thread.+/// </summary>+public partial class MainWindow+{+ /// <summary>How long after the last edit, with no mouse button held, the edit ends a step.</summary>+ private static readonly TimeSpan RecordDelay = TimeSpan.FromMilliseconds(500);++ private ProjectHistory? _history;+ private DispatcherTimer? _recordTimer;+ /// <summary>Whether an edit has not ended its step yet.</summary>+ private bool _recordPending;+ /// <summary>Whether a step is being written back, so its changes are not recorded as a new one.</summary>+ private bool _restoring;++ /// <summary>A new project starts a new history, its present state the first step.</summary>+ private void StartHistory(Project? project)+ {+ _recordTimer?.Stop();+ _recordPending = false;+ _history = project != null ? new ProjectHistory(project) : null;+ }++ /// <summary>An edit: its step ends after the quiet period (a step being written back is not an edit of its own).</summary>+ private void ScheduleRecord()+ {+ if (_restoring)+ {+ return;+ }+ _recordPending = true;+ _recordTimer ??= MakeTimer(RecordDelay, OnRecordTimer);+ _recordTimer.Stop();+ _recordTimer.Start();+ }++ private void OnRecordTimer()+ {+ if (Mouse.LeftButton == MouseButtonState.Pressed || Mouse.RightButton == MouseButtonState.Pressed)+ {+ // a drag or a scrub goes on: its step ends when the button is let go and the quiet period has passed+ return;+ }+ RecordStep();+ }++ /// <summary>Ends the pending step, if any: the project's state becomes a step when it differs from the current one.</summary>+ private void RecordStep()+ {+ _recordTimer?.Stop();+ if (!_recordPending || _history == null)+ {+ return;+ }+ _recordPending = false;+ if (_history.Record())+ {+ Logger.Debug("Undo step {Step} recorded", _history.Position);+ }+ IsDirty = !_history.IsAtSaved;+ CommandManager.InvalidateRequerySuggested();+ }++ /// <summary>After a save: the saved state is the current step.</summary>+ private void MarkHistorySaved()+ {+ RecordStep();+ _history?.MarkSaved();+ }++ private void CanUndo(object sender, CanExecuteRoutedEventArgs e) => e.CanExecute = _history != null && (_history.CanUndo || _recordPending);++ private void CanRedo(object sender, CanExecuteRoutedEventArgs e) => e.CanExecute = _history != null && _history.CanRedo && !_recordPending;++ private void OnUndo(object sender, ExecutedRoutedEventArgs e) => MoveInHistory(history => history.Undo(), "Undo");++ private void OnRedo(object sender, ExecutedRoutedEventArgs e) => MoveInHistory(history => history.Redo(), "Redo");++ /// <summary>Ends a pending step, then writes the step <paramref name="move"/> goes to back into the project, keeping the selection.</summary>+ private void MoveInHistory(Func<ProjectHistory, bool> move, string what)+ {+ RecordStep();+ if (_history == null)+ {+ return;+ }+ object? current = SelectedItem;+ List<(IList? List, string? Name, int Index)> selection = [.. SelectedItems.Select(Locate)];+ (IList? List, string? Name, int Index)? currentPlace = current != null ? Locate(current) : null;+ bool moved;+ _restoring = true;+ try+ {+ moved = move(_history);+ }+ finally+ {+ _restoring = false;+ }+ if (!moved)+ {+ return;+ }+ Logger.Debug("{What}: step {Step} of {Count}", what, _history.Position, _history.Count - 1);+ List<object> found = [.. selection.Select(Find).OfType<object>()];+ object? newCurrent = currentPlace is { } place ? Find(place) : null;+ SelectedItems.Clear();+ foreach (object item in found)+ {+ SelectedItems.Add(item);+ }+ SelectedItem = newCurrent ?? found.FirstOrDefault();+ if (SelectedItem == null)+ {+ projectTree.SelectRoot();+ }+ IsDirty = !_history.IsAtSaved;+ CommandManager.InvalidateRequerySuggested();+ }++ /// <summary>The project's settings objects a selection can hold, by their place: replaced as a whole by a step written back.</summary>+ private static readonly Func<Project, object>[] SettingsObjects =+ [+ project => project,+ project => project.Scene,+ project => project.Simulation,+ project => project.Display,+ project => project.Display.Field,+ project => project.Display.Intensity,+ project => project.Display.Video,+ ];++ /// <summary>Where a selected item sits: its list, name and index there; or, with no list, the index of its settings object (-1 for anything else).</summary>+ private (IList? List, string? Name, int Index) Locate(object item)+ {+ foreach (IList list in (IList[])[Project.Sources, Project.Parts, Project.Probes, Project.ColorSchemes])+ {+ int index = list.IndexOf(item);+ if (index >= 0)+ {+ return (list, NameOf(item), index);+ }+ }+ return (null, null, Array.FindIndex(SettingsObjects, get => ReferenceEquals(get(Project), item)));+ }++ /// <summary>The restored object at a place <see cref="Locate"/> gave: the item of that name in the same list, else at the same index, or the settings object at the same place; null when it is gone.</summary>+ private object? Find((IList? List, string? Name, int Index) place)+ {+ if (place.List is { } list)+ {+ object? named = place.Name != null ? list.Cast<object>().FirstOrDefault(item => NameOf(item) == place.Name) : null;+ return named ?? (place.Index < list.Count ? list[place.Index] : null);+ }+ return place.Index >= 0 ? SettingsObjects[place.Index](Project) : null;+ }++ private static string? NameOf(object item) => item switch+ {+ Source source => source.Name,+ OpticalPart part => part.Name,+ Probe probe => probe.Name,+ ColorScheme scheme => scheme.Name,+ _ => null,+ };+}diff --git a/WaveDudeNext.WPF/MainWindow.Live.cs b/WaveDudeNext.WPF/MainWindow.Live.csindex 13a7b33..284bc23 100644--- a/WaveDudeNext.WPF/MainWindow.Live.cs+++ b/WaveDudeNext.WPF/MainWindow.Live.cs@@ -157,6 +157,7 @@ public partial class MainWindowIsProbesStale = false;IsDirty = false;ScratchFrame = null;+ StartHistory(project);if (project != null){_watcher = new ProjectWatcher(project);@@ -170,9 +171,11 @@ public partial class MainWindowprivate void OnProjectChanged(object? sender, ProjectChange change){IsDirty = true;- if (change.Item is Scene && change.Property is nameof(Scene.ImagePath) or nameof(Scene.ImageData))+ ScheduleRecord();+ bool sceneReplaced = change.Item is Project && change.Property == nameof(Project.Scene);+ if (change.Item is Scene && change.Property is nameof(Scene.ImagePath) or nameof(Scene.ImageData) || sceneReplaced){- // a new image file to watch (Browse, a reload, a path made relative)+ // a new image file to watch (Browse, a reload, a path made relative, a scene written back by Undo or Redo)ArmSceneImageWatch();}if (change.Item is ColorScheme or ObservableCollection<ColorScheme>)@@ -213,7 +216,7 @@ public partial class MainWindow// the parts are painted into the scene pixels: paint again, so the outline follows the edit at once_partsVersion++;}- if (change.Item is Scene || IsPartChange(change))+ if (change.Item is Scene || sceneReplaced || IsPartChange(change)){UpdateScenePixels();}diff --git a/WaveDudeNext.WPF/MainWindow.Project.cs b/WaveDudeNext.WPF/MainWindow.Project.csindex b779df4..c7ffa08 100644--- a/WaveDudeNext.WPF/MainWindow.Project.cs+++ b/WaveDudeNext.WPF/MainWindow.Project.cs@@ -24,6 +24,7 @@ using Microsoft.Win32;using WaveDudeNext.Model;using WaveDudeNext.Rendering;using WaveDudeNext.Runs;+using WaveDudeNext.WPF.Commands;using WaveDudeNext.WPF.Converters;using WaveDudeNext.WPF.Rendering;@@ -221,6 +222,24 @@ public partial class MainWindowAdded(copies[^1]);}+ /// <summary>Edit > Delete: in a text box (the menu's command starts from the element that had the focus) its selected text; else what Remove takes.</summary>+ private void CanDelete(object sender, CanExecuteRoutedEventArgs e) =>+ e.CanExecute = e.OriginalSource is System.Windows.Controls.TextBox box+ ? box is { IsReadOnly: false, SelectionLength: > 0 }+ : Target(null) is Source or OpticalPart or Probe or ColorScheme;++ private void OnDelete(object sender, ExecutedRoutedEventArgs e)+ {+ if (e.OriginalSource is System.Windows.Controls.TextBox box)+ {+ box.SelectedText = "";+ }+ else+ {+ ProjectCommands.Remove.Execute(null, this);+ }+ }+/// <summary>Removes the target, or the whole selection it belongs to; the user is kept in place at the slot of the last one removed.</summary>private void OnRemove(object sender, ExecutedRoutedEventArgs e){diff --git a/WaveDudeNext.WPF/MainWindow.xaml b/WaveDudeNext.WPF/MainWindow.xamlindex 3b32f1f..17d103f 100644--- a/WaveDudeNext.WPF/MainWindow.xaml+++ b/WaveDudeNext.WPF/MainWindow.xaml@@ -42,6 +42,22 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file orAllowDrop="True" Drop="OnDrop"><Window.Resources>+ <!-- a menu icon from Windows' icon font: Segoe Fluent Icons on Windows 11, Segoe MDL2 Assets on Windows 10 (the same code+ points), drawn on their 16 px grid; the line is held to 16 px, as the font's own line height overflowed the 16 px slot+ and cut the glyphs, and the glyph then moved down 3 px to the text's middle (measured on a capture: it sat 3.5 px high) -->+ <Style x:Key="MenuIconText" TargetType="{x:Type TextBlock}">+ <Setter Property="FontFamily" Value="Segoe Fluent Icons, Segoe MDL2 Assets" />+ <Setter Property="FontSize" Value="16" />+ <Setter Property="LineHeight" Value="16" />+ <Setter Property="LineStackingStrategy" Value="BlockLineHeight" />+ <Setter Property="RenderTransform">+ <Setter.Value>+ <TranslateTransform Y="3" />+ </Setter.Value>+ </Setter>+ <Setter Property="HorizontalAlignment" Value="Center" />+ <Setter Property="VerticalAlignment" Value="Center" />+ </Style><converters:EqualityConverter x:Key="Equality" /><converters:FrameMemoryOptionConverter x:Key="FrameMemoryOption" /><converters:IntEqualsConverter x:Key="IntEquals" />@@ -176,6 +192,12 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<!-- the pictures' Auto brightness; handler in MainWindow.Display.cs --><CommandBinding Command="{x:Static commands:DisplayCommands.AutoBrightness}" CanExecute="CanAutoBrightness" Executed="OnAutoBrightness" />+ <!-- undo and redo; handlers in MainWindow.History.cs -->+ <CommandBinding Command="{x:Static commands:EditCommands.Undo}" CanExecute="CanUndo" Executed="OnUndo" />+ <CommandBinding Command="{x:Static commands:EditCommands.Redo}" CanExecute="CanRedo" Executed="OnRedo" />+ <!-- Edit > Delete; handlers in MainWindow.Project.cs (Cut, Copy and Paste are the text boxes' own) -->+ <CommandBinding Command="{x:Static commands:EditCommands.Delete}" CanExecute="CanDelete" Executed="OnDelete" />+<!-- project structure; handlers in MainWindow.Project.cs --><CommandBinding Command="{x:Static commands:ProjectCommands.AddSource}" Executed="OnAddSource" /><CommandBinding Command="{x:Static commands:ProjectCommands.AddPart}" Executed="OnAddPart" />@@ -226,6 +248,28 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<Separator /><MenuItem Command="{StaticResource FileExit}" Header="{DynamicResource MenuFileExit}" /></MenuItem>+ <MenuItem Header="{DynamicResource MenuEdit}">+ <!-- the icons are Windows' own glyphs (Segoe Fluent Icons, Segoe MDL2 Assets on Windows 10), in the item's text colour -->+ <MenuItem Header="{DynamicResource MenuEditUndo}" Command="{x:Static commands:EditCommands.Undo}" AutomationProperties.AutomationId="MenuUndo">+ <MenuItem.Icon><TextBlock Style="{StaticResource MenuIconText}" Text="" /></MenuItem.Icon>+ </MenuItem>+ <MenuItem Header="{DynamicResource MenuEditRedo}" Command="{x:Static commands:EditCommands.Redo}" AutomationProperties.AutomationId="MenuRedo">+ <MenuItem.Icon><TextBlock Style="{StaticResource MenuIconText}" Text="" /></MenuItem.Icon>+ </MenuItem>+ <Separator />+ <MenuItem Header="{DynamicResource MenuEditCut}" Command="ApplicationCommands.Cut" AutomationProperties.AutomationId="MenuCut">+ <MenuItem.Icon><TextBlock Style="{StaticResource MenuIconText}" Text="" /></MenuItem.Icon>+ </MenuItem>+ <MenuItem Header="{DynamicResource MenuEditCopy}" Command="ApplicationCommands.Copy" AutomationProperties.AutomationId="MenuCopy">+ <MenuItem.Icon><TextBlock Style="{StaticResource MenuIconText}" Text="" /></MenuItem.Icon>+ </MenuItem>+ <MenuItem Header="{DynamicResource MenuEditPaste}" Command="ApplicationCommands.Paste" AutomationProperties.AutomationId="MenuPaste">+ <MenuItem.Icon><TextBlock Style="{StaticResource MenuIconText}" Text="" /></MenuItem.Icon>+ </MenuItem>+ <MenuItem Header="{DynamicResource MenuEditDelete}" Command="{x:Static commands:EditCommands.Delete}" InputGestureText="Del" AutomationProperties.AutomationId="MenuDelete">+ <MenuItem.Icon><TextBlock Style="{StaticResource MenuIconText}" Text="" /></MenuItem.Icon>+ </MenuItem>+ </MenuItem><MenuItem Header="{DynamicResource MenuView}"><MenuItem Header="{DynamicResource MenuViewPanes}"ItemsSource="{Binding Items, ElementName=dockHost}"diff --git a/WaveDudeNext.WPF/MainWindow.xaml.cs b/WaveDudeNext.WPF/MainWindow.xaml.csindex 07bf5d9..1aaa415 100644--- a/WaveDudeNext.WPF/MainWindow.xaml.cs+++ b/WaveDudeNext.WPF/MainWindow.xaml.cs@@ -143,7 +143,8 @@ public partial class MainWindow : Window/// <summary>/// Whether the project was edited since it was opened, created or last saved (2026-10-14): the title/// carries an asterisk and New, Open, Close and Exit ask before discarding. Set by the watcher on any- /// change, model-wide; cleared when the project is replaced or saved.+ /// change, model-wide; cleared when the project is replaced or saved, and when Undo or Redo reach the saved step+ /// (<c>MainWindow.History.cs</c>)./// </summary>public bool IsDirty{@@ -290,6 +291,7 @@ public partial class MainWindow : WindowProject.Scene.RelativizeImagePath(Path.GetDirectoryName(fileName));Project.Save(fileName);Filename = fileName;+ MarkHistorySaved();IsDirty = false;ArmSceneImageWatch();Logger.Info("Saved '{Path}'", fileName);diff --git a/WaveDudeNext.WPF/Strings/Strings.DE.xaml b/WaveDudeNext.WPF/Strings/Strings.DE.xamlindex 090af50..e7f2270 100644--- a/WaveDudeNext.WPF/Strings/Strings.DE.xaml+++ b/WaveDudeNext.WPF/Strings/Strings.DE.xaml@@ -45,6 +45,13 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<s:String x:Key="TipAutoBrightness">Die Helligkeit einmal an das gezeigte Bild anpassen: das hellste halbe Prozent erreicht das obere Ende des Farbschemas. Die Helligkeit bleibt danach, wie sie ist.</s:String><s:String x:Key="MenuExportProbeCsv">Sonden_daten als CSV exportieren...</s:String><s:String x:Key="MenuFileExit">_Beenden</s:String>+ <s:String x:Key="MenuEdit">_Bearbeiten</s:String>+ <s:String x:Key="MenuEditUndo">_Rückgängig</s:String>+ <s:String x:Key="MenuEditRedo">_Wiederholen</s:String>+ <s:String x:Key="MenuEditCut">_Ausschneiden</s:String>+ <s:String x:Key="MenuEditCopy">_Kopieren</s:String>+ <s:String x:Key="MenuEditPaste">_Einfügen</s:String>+ <s:String x:Key="MenuEditDelete">_Löschen</s:String><s:String x:Key="MenuView">_Ansicht</s:String><s:String x:Key="MenuViewPanes">_Fenster</s:String><s:String x:Key="DockWindowPosition">Fensterposition</s:String>diff --git a/WaveDudeNext.WPF/Strings/Strings.EN.xaml b/WaveDudeNext.WPF/Strings/Strings.EN.xamlindex 6f519ab..edb7708 100644--- a/WaveDudeNext.WPF/Strings/Strings.EN.xaml+++ b/WaveDudeNext.WPF/Strings/Strings.EN.xaml@@ -45,6 +45,13 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<s:String x:Key="TipAutoBrightness">Fit the brightness once to the frame shown: the brightest half percent of it reaches the top of the colour scheme. The brightness then stays as it is.</s:String><s:String x:Key="MenuExportProbeCsv">Export probe _data as CSV...</s:String><s:String x:Key="MenuFileExit">E_xit</s:String>+ <s:String x:Key="MenuEdit">_Edit</s:String>+ <s:String x:Key="MenuEditUndo">_Undo</s:String>+ <s:String x:Key="MenuEditRedo">_Redo</s:String>+ <s:String x:Key="MenuEditCut">Cu_t</s:String>+ <s:String x:Key="MenuEditCopy">_Copy</s:String>+ <s:String x:Key="MenuEditPaste">_Paste</s:String>+ <s:String x:Key="MenuEditDelete">_Delete</s:String><s:String x:Key="MenuView">_View</s:String><s:String x:Key="MenuViewPanes">_Panes</s:String><!-- the dock panes' header buttons and the position menu -->diff --git a/WaveDudeNext.WPF/Strings/Strings.FR.xaml b/WaveDudeNext.WPF/Strings/Strings.FR.xamlindex e1cb16e..2ecfdae 100644--- a/WaveDudeNext.WPF/Strings/Strings.FR.xaml+++ b/WaveDudeNext.WPF/Strings/Strings.FR.xaml@@ -45,6 +45,13 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<s:String x:Key="TipAutoBrightness">Ajuster une fois la luminosité à l'image affichée : le demi-pour-cent le plus clair atteint le haut du jeu de couleurs. La luminosité reste ensuite telle quelle.</s:String><s:String x:Key="MenuExportProbeCsv">Exporter les _données de la sonde en CSV...</s:String><s:String x:Key="MenuFileExit">_Quitter</s:String>+ <s:String x:Key="MenuEdit">_Édition</s:String>+ <s:String x:Key="MenuEditUndo">_Annuler</s:String>+ <s:String x:Key="MenuEditRedo">_Rétablir</s:String>+ <s:String x:Key="MenuEditCut">Co_uper</s:String>+ <s:String x:Key="MenuEditCopy">Co_pier</s:String>+ <s:String x:Key="MenuEditPaste">C_oller</s:String>+ <s:String x:Key="MenuEditDelete">_Supprimer</s:String><s:String x:Key="MenuView">_Affichage</s:String><s:String x:Key="MenuViewPanes">_Panneaux</s:String><s:String x:Key="DockWindowPosition">Position du panneau</s:String>diff --git a/WaveDudeNext.WPF/Strings/Strings.NL.xaml b/WaveDudeNext.WPF/Strings/Strings.NL.xamlindex b941cb9..8826df8 100644--- a/WaveDudeNext.WPF/Strings/Strings.NL.xaml+++ b/WaveDudeNext.WPF/Strings/Strings.NL.xaml@@ -45,6 +45,13 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<s:String x:Key="TipAutoBrightness">De helderheid eenmalig aan het getoonde beeld aanpassen: de helderste halve procent bereikt de bovenkant van het kleurenschema. De helderheid blijft daarna zoals ze is.</s:String><s:String x:Key="MenuExportProbeCsv">Sonde_gegevens als CSV exporteren...</s:String><s:String x:Key="MenuFileExit">A_fsluiten</s:String>+ <s:String x:Key="MenuEdit">Be_werken</s:String>+ <s:String x:Key="MenuEditUndo">_Ongedaan maken</s:String>+ <s:String x:Key="MenuEditRedo">Opn_ieuw</s:String>+ <s:String x:Key="MenuEditCut">K_nippen</s:String>+ <s:String x:Key="MenuEditCopy">_Kopiëren</s:String>+ <s:String x:Key="MenuEditPaste">_Plakken</s:String>+ <s:String x:Key="MenuEditDelete">_Verwijderen</s:String><s:String x:Key="MenuView">Beel_d</s:String><s:String x:Key="MenuViewPanes">_Panelen</s:String><s:String x:Key="DockWindowPosition">Positie van het paneel</s:String>diff --git a/WaveDudeNext.WPF/Themes/Controls.xaml b/WaveDudeNext.WPF/Themes/Controls.xamlindex eadc214..12a281e 100644--- a/WaveDudeNext.WPF/Themes/Controls.xaml+++ b/WaveDudeNext.WPF/Themes/Controls.xaml@@ -474,6 +474,9 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<Setter Property="Background" Value="Transparent" /><Setter Property="Padding" Value="3,1" /><Setter Property="HorizontalContentAlignment" Value="Left" />+ <!-- set so the system theme's binding to the parent ItemsControl never applies (the template does not use it): it+ logged an error for every row dropped when a list was cleared and refilled, as Undo and Redo do -->+ <Setter Property="VerticalContentAlignment" Value="Center" /><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="{x:Type TreeViewItem}">diff --git a/WaveDudeNext/Model/ProjectHistory.cs b/WaveDudeNext/Model/ProjectHistory.csnew file mode 100644index 0000000..feec85f--- /dev/null+++ b/WaveDudeNext/Model/ProjectHistory.cs@@ -0,0 +1,183 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 Alexander Graef <[email protected]>+//+// This file is part of WaveDude Next, a 2D wave simulator.+//+// Based on the work of+// Jeroen Vleggaar (Huygens Optics), author of Wave Dude 2D, Copyright (C) 2026+// <https://www.youtube.com/@HuygensOptics>, <https://www.huygensoptics.com>+// 0x23 (Diffraction Limited), author of WaveSimulator2D+// <https://www.youtube.com/@DiffractionLimited>, <https://github.com/0x23/WaveSimulator2D>+//+// WaveDude Next is free software: you can redistribute it and/or modify it under+// the terms of the GNU General Public License as published by the Free Software+// Foundation, either version 3 of the License, or (at your option) any later+// version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or+// <https://www.gnu.org/licenses/>.++using System.Collections;+using System.Reflection;+using System.Xml;+using System.Xml.Serialization;++namespace WaveDudeNext.Model;++/// <summary>+/// Undo and redo for a <see cref="Project"/> (2026-10-22, the user's request: unlimited, the project file being nearly the+/// whole state): a list of snapshots of everything the file holds, one per step, with a current position. A snapshot is+/// the project's XML without the embedded scene image, and the image's bytes by reference; an unchanged image (the same+/// array, or equal bytes) is shared with the step before, so a step costs the XML alone. <see cref="Record"/> adds a step+/// when the project differs from the current one; <see cref="Undo"/> and <see cref="Redo"/> write a step back into the same+/// project object, property by property, so its watchers report the change as an edit and nothing is replaced. The caller+/// decides when a step ends (after a quiet moment, never in the middle of a drag). UI thread, like the model.+/// </summary>+public sealed class ProjectHistory+{+ /// <summary>The project file's serializer without the scene image (<see cref="Scene.ImageData"/>), which a snapshot keeps by reference.</summary>+ private static readonly XmlSerializer Serializer = CreateSerializer();++ /// <summary>The persisted top-level properties, written back in declaration order: the lists' contents, the other values themselves.</summary>+ private static readonly PropertyInfo[] Persisted = [.. typeof(Project).GetProperties(BindingFlags.Public | BindingFlags.Instance)+ .Where(property => property.CanRead && property.CanWrite && property.GetCustomAttribute<XmlIgnoreAttribute>() == null)];++ private readonly Project _project;+ private readonly List<Snapshot> _steps = [];+ private int _current;+ private int _saved;++ /// <summary>Starts the history of <paramref name="project"/> with its present state as the first step, taken as saved.</summary>+ public ProjectHistory(Project project)+ {+ _project = project;+ _steps.Add(Capture(null));+ }++ /// <summary>Whether there is a step to go back to.</summary>+ public bool CanUndo => _current > 0;++ /// <summary>Whether there is an undone step to go forward to.</summary>+ public bool CanRedo => _current < _steps.Count - 1;++ /// <summary>Whether the current step is the one last saved (or the first, for a project never saved), so the file holds it.</summary>+ public bool IsAtSaved => _current == _saved;++ /// <summary>The number of steps, the first included.</summary>+ public int Count => _steps.Count;++ /// <summary>The current step's index, 0 for the first.</summary>+ public int Position => _current;++ /// <summary>+ /// Ends a step: when the project differs from the current step, its state becomes a new step after it, and the undone+ /// steps beyond are dropped. Returns whether a step was added; a change that leaves the file as it was adds none.+ /// </summary>+ public bool Record()+ {+ Snapshot snapshot = Capture(_steps[_current].Image);+ if (snapshot == _steps[_current])+ {+ return false;+ }+ _steps.RemoveRange(_current + 1, _steps.Count - _current - 1);+ if (_saved > _current)+ {+ // the saved step was undone and is now replaced: no step matches the file any more+ _saved = -1;+ }+ _steps.Add(snapshot);+ _current++;+ return true;+ }++ /// <summary>Marks the current step as the one the file holds (after a save, with the saved state recorded first).</summary>+ public void MarkSaved() => _saved = _current;++ /// <summary>Writes the step before the current one back into the project; false when there is none.</summary>+ public bool Undo()+ {+ if (!CanUndo)+ {+ return false;+ }+ Apply(_steps[--_current]);+ return true;+ }++ /// <summary>Writes the step after the current one back into the project; false when there is none.</summary>+ public bool Redo()+ {+ if (!CanRedo)+ {+ return false;+ }+ Apply(_steps[++_current]);+ return true;+ }++ /// <summary>The project's state now; its image shares <paramref name="previous"/> when the bytes are the same.</summary>+ private Snapshot Capture(byte[]? previous)+ {+ var text = new StringWriter();+ using (var writer = XmlWriter.Create(text, new XmlWriterSettings { Indent = false }))+ {+ Serializer.Serialize(writer, _project);+ }+ byte[]? image = _project.Scene.ImageData;+ if (image != null && previous != null && !ReferenceEquals(image, previous) && image.AsSpan().SequenceEqual(previous))+ {+ image = previous;+ }+ return new Snapshot(text.ToString(), image);+ }++ /// <summary>+ /// Writes <paramref name="snapshot"/> into the project: read into a project of its own (normalised, so the sources'+ /// emitters are generated again), then each persisted top-level property moved over: a list's contents replaced (the+ /// list objects stay, and with them what is bound to them), any other value set.+ /// </summary>+ private void Apply(Snapshot snapshot)+ {+ Project state;+ using (var reader = XmlReader.Create(new StringReader(snapshot.Xml)))+ {+ state = (Project)Serializer.Deserialize(reader)!;+ }+ state.Scene.ImageData = snapshot.Image;+ state.Normalize();+ foreach (PropertyInfo property in Persisted)+ {+ object? value = property.GetValue(state);+ if (value is IList items && property.GetValue(_project) is IList target)+ {+ object[] moved = [.. items.Cast<object>()];+ items.Clear();+ target.Clear();+ foreach (object item in moved)+ {+ target.Add(item);+ }+ }+ else+ {+ property.SetValue(_project, value);+ }+ }+ }++ private static XmlSerializer CreateSerializer()+ {+ var overrides = new XmlAttributeOverrides();+ overrides.Add(typeof(Scene), nameof(Scene.ImageData), new XmlAttributes { XmlIgnore = true });+ return new XmlSerializer(typeof(Project), overrides);+ }++ /// <summary>One step: the project's XML without the scene image, and the image's bytes (shared between steps while unchanged).</summary>+ private sealed record Snapshot(string Xml, byte[]? Image)+ {+ /// <summary>Equal when the XML is and the image is the same array (equal bytes were made the same array by <see cref="Capture"/>).</summary>+ public bool Equals(Snapshot? other) => other != null && ReferenceEquals(Image, other.Image) && Xml == other.Xml;++ /// <inheritdoc/>+ public override int GetHashCode() => Xml.GetHashCode();+ }+}diff --git a/_tools/library_check/Program.cs b/_tools/library_check/Program.csindex 8c88e42..87b8018 100644--- a/_tools/library_check/Program.cs+++ b/_tools/library_check/Program.cs@@ -267,6 +267,7 @@ internal static class ProgramCheckDecimalLevels(W, H);CheckMovable();CheckRanges();+ CheckHistory();CheckOpenEdges(W, H);CheckFrameStore(scene);CheckPreviewQuality(scene, W, H);@@ -426,6 +427,77 @@ internal static class Program}}+ /// <summary>+ /// Undo and redo (<see cref="ProjectHistory"/>): a step written back gives the file it was recorded from, image+ /// included, into the same project object and lists; an edit that leaves the file as it was is no step; equal image+ /// bytes are shared between steps; a new edit after an undo drops the redo; the saved mark follows the steps.+ /// </summary>+ private static void CheckHistory()+ {+ Console.WriteLine("--- undo and redo (ProjectHistory)");+ static string FileOf(Project project)+ {+ using var stream = new MemoryStream();+ project.Save(stream);+ return System.Text.Encoding.UTF8.GetString(stream.ToArray());+ }+ var project = new Project { Seed = 7 };+ byte[] image = [1, 2, 3, 4, 5];+ project.Scene.ImageData = image;+ var history = new ProjectHistory(project);+ string first = FileOf(project);+ Check(history.Count == 1 && !history.CanUndo && !history.CanRedo && history.IsAtSaved, "a new history: one step, the saved one, nothing to undo or redo");+ Check(!history.Record(), "an unchanged project records no step");++ var sources = project.Sources;+ var parts = project.Parts;+ project.Seed = 8;+ project.AddSource().X = 40;+ project.AddPart<FiberPart>().Nodes[0].OutY = 30;+ project.AddProbe();+ project.Display.Field.Brightness = 2.5;+ project.Scene.ImageData = [9, 9, 9];+ Check(history.Record() && history.Count == 2 && !history.IsAtSaved, "an edit (seed, a source, a fibre node, a probe, a layer, the image) records a step");+ string second = FileOf(project);+ Scene secondScene = project.Scene;++ project.Scene.ImageData = [9, 9, 9];+ byte[] shared = project.Scene.ImageData!;+ Check(!history.Record(), "an image with equal bytes is no step");++ Check(history.Undo() && FileOf(project) == first && ReferenceEquals(project.Scene.ImageData, image) && history.IsAtSaved,+ "Undo writes the first step back: the same file, the first image's own bytes, the saved step");+ Check(ReferenceEquals(project.Sources, sources) && ReferenceEquals(project.Parts, parts) && project.Sources.Count == 0 && project.Parts.Count == 0,+ "the lists are the project's own, emptied: what is bound to them stays bound");+ Check(!ReferenceEquals(project.Scene, secondScene), "the settings objects are replaced by the step's");++ Check(history.Redo() && FileOf(project) == second && project.Sources.Count == 1 && project.Sources[0].Elements.Count > 0,+ "Redo writes the second step back, the source's emitters generated again");+ Check(project.Parts[0] is FiberPart { Nodes: [{ OutY: 30 }, _] }, "a fibre node's handle comes back with its part");+ Check(project.Scene.ImageData != null && !ReferenceEquals(project.Scene.ImageData, image) && project.Scene.ImageData.SequenceEqual(shared),+ "the second step's image comes back");++ history.Undo();+ project.Description = "another way";+ Check(history.Record() && !history.CanRedo && history.Count == 2 && !history.IsAtSaved,+ "an edit after an undo drops the undone step, and the saved state is no longer reachable by redo");+ history.MarkSaved();+ Check(history.IsAtSaved && history.Undo() && !history.IsAtSaved && history.Redo() && history.IsAtSaved, "the saved mark moves to the step saved");++ // 100 steps of a few kilobytes: unlimited is affordable+ for (int i = 0; i < 100; i++)+ {+ project.Seed = 100 + i;+ history.Record();+ }+ int undone = 0;+ while (history.Undo())+ {+ undone++;+ }+ Check(undone == 101 && history.Count == 102 && FileOf(project) == first, $"{undone} undos walk back through {history.Count} steps to the first");+ }+/// <summary>"bench-render [w h]": what colouring a stored frame costs, per layer, at that size (the presenter's cost per picture).</summary>private static void BenchRender(int w, int h, bool load = false){diff --git a/_tools/ui_check/KeyboardCheck.ps1 b/_tools/ui_check/KeyboardCheck.ps1index 17504e7..b26b335 100644--- a/_tools/ui_check/KeyboardCheck.ps1+++ b/_tools/ui_check/KeyboardCheck.ps1@@ -82,6 +82,7 @@ try {FocusOn "PreviewPlay"Step "F10" 0x79 150 # the menu bar, File headerStep "Down" $VK_DOWN 150 # opens File+ Step "Right" $VK_RIGHT 150 # moves to Edit and opens itStep "Right" $VK_RIGHT 150 # moves to View and opens it on its first entry (Panes)Step "Right" $VK_RIGHT 150 # opens the Panes submenu on its first entryfor ($i = 0; $i -lt 5 -and (FocusedId) -notlike "*'Messages')"; $i++) { Step "Down" $VK_DOWN 120 }diff --git a/_tools/ui_check/LanguageCheck.ps1 b/_tools/ui_check/LanguageCheck.ps1index 1ecdcb8..3a2758a 100644--- a/_tools/ui_check/LanguageCheck.ps1+++ b/_tools/ui_check/LanguageCheck.ps1@@ -15,7 +15,7 @@# version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or# <https://www.gnu.org/licenses/>.-# Drives View > Language by keyboard (F10 focuses the menu bar, Down opens a menu, Left/Right move between menus, Enter picks): switches to+# Drives View > Language by keyboard (F10 focuses the menu bar, Down opens a menu, Left/Right move between menus, Edit lying between File and View, Enter picks): switches to# German, checks that menus, tooltips and property labels change at once, closes the app, starts it again# and checks the choice was kept (the Language user setting), then switches back to System and checks the# strings are English again. Posted keys and UI Automation properties only, as in the other harnesses.@@ -46,6 +46,7 @@ function Step([string]$what, [int]$vk, [int]$settle) {function ChooseLanguage([int]$index) {Step "F10" 0x79 150 # the menu bar's first header (File)Step "Down" 0x28 150 # opens File+ Step "Right" $VK_RIGHT 150 # moves to Edit and opens itStep "Right" $VK_RIGHT 150 # moves to View and opens it on its first entryStep "Down" 0x28 100; Step "Down" 0x28 100 # Theme, LanguageStep "Right" $VK_RIGHT 150 # opens Language on System@@ -55,12 +56,12 @@ function ChooseLanguage([int]$index) {Start-App $exe $projecttry {- Check "menus are English to begin with" ((MenuNames) -eq "File|View|Simulation|Help") (MenuNames)- Key 0x79 200; Key 0x28 200; Key $VK_RIGHT 500- Check "F10, Down, Right opens the View menu by keyboard" (MenuItemVisible "Panes") (MenuNames)+ Check "menus are English to begin with" ((MenuNames) -eq "File|Edit|View|Simulation|Help") (MenuNames)+ Key 0x79 200; Key 0x28 200; Key $VK_RIGHT 300; Key $VK_RIGHT 500+ Check "F10, Down, Right, Right opens the View menu by keyboard (Edit between)" (MenuItemVisible "Panes") (MenuNames)Key $VK_ESCAPE 150; Key $VK_ESCAPE 150ChooseLanguage 2- Check "View > Language > Deutsch relabels the menus at once" ((MenuNames) -eq "Datei|Ansicht|Simulation|Hilfe") (MenuNames)+ Check "View > Language > Deutsch relabels the menus at once" ((MenuNames) -eq "Datei|Bearbeiten|Ansicht|Simulation|Hilfe") (MenuNames)Check "tooltips follow (Play)" ((Find "PreviewPlay").Current.Name -eq "Wiedergabe (Leertaste)") ((Find "PreviewPlay").Current.Name)FocusOn "Source:Source 1"$c = New-Object System.Windows.Automation.PropertyCondition($A::NameProperty, "Frequenz")@@ -76,9 +77,9 @@ finally { Stop-App }# the choice is a user setting: a fresh start comes up GermanStart-App $exe $projecttry {- Check "after a restart the menus are still German (setting kept)" ((MenuNames) -eq "Datei|Ansicht|Simulation|Hilfe") (MenuNames)+ Check "after a restart the menus are still German (setting kept)" ((MenuNames) -eq "Datei|Bearbeiten|Ansicht|Simulation|Hilfe") (MenuNames)ChooseLanguage 0- Check "View > Language > System brings English back" ((MenuNames) -eq "File|View|Simulation|Help") (MenuNames)+ Check "View > Language > System brings English back" ((MenuNames) -eq "File|Edit|View|Simulation|Help") (MenuNames)Check "the folders are English again (Probes, Colour schemes)" ((MenuItemVisible "Probes") -and (MenuItemVisible "Colour schemes") -and -not (MenuItemVisible "Sonden"))Check "the app never took the foreground" ((Foreground) -ne "APP") (Foreground)}diff --git a/_tools/ui_check/PreviewQualityCheck.ps1 b/_tools/ui_check/PreviewQualityCheck.ps1index cde1fb5..af1b5fb 100644--- a/_tools/ui_check/PreviewQualityCheck.ps1+++ b/_tools/ui_check/PreviewQualityCheck.ps1@@ -16,7 +16,7 @@# <https://www.gnu.org/licenses/>.# Drives View > Preview resolution / frames / samples by keyboard (F10 focuses the menu bar, Down opens a menu, Right moves-# to View, Down walks its entries, Right opens a submenu, Enter picks) on tiny.wdproj (64 x 48, 200 steps, a frame every+# over Edit to View, Down walks its entries, Right opens a submenu, Enter picks) on tiny.wdproj (64 x 48, 200 steps, a frame every# 2 steps): a run is made, then each choice marks it stale and the automatic re-run follows in the reduced shape (the# status bar, the frame readout and the log file next to the exe are the witnesses: "50 of 100 frames stored as 32x24# (1/2 resolution, every 2. frame, 8-bit)"). The timeline never changes: with every second frame stored, frames 98 and@@ -45,10 +45,11 @@ function LogText() {try { $sr = New-Object IO.StreamReader($fs); return $sr.ReadToEnd() } finally { $fs.Dispose() }}function LogHas([string]$text) { return (LogText).Contains($text) }-# View (2nd header) > entry $entry (0 Panes, 1 Theme, 2 Language, 3 Preview resolution, 4 Preview frames, 5 Preview samples) > item $item+# View (3rd header, after File and Edit) > entry $entry (0 Panes, 1 Theme, 2 Language, 3 Preview resolution, 4 Preview frames, 5 Preview samples) > item $itemfunction ChooseView([int]$entry, [int]$item) {Step "F10" 0x79 150 # the menu bar's first header (File)Step "Down" 0x28 150 # opens File+ Step "Right" $VK_RIGHT 150 # moves to Edit and opens itStep "Right" $VK_RIGHT 150 # moves to View and opens it on its first entryfor ($i = 0; $i -lt $entry; $i++) { Step "Down" 0x28 100 }Step "Right" $VK_RIGHT 150 # opens the submenu on its first item