Skip to content

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#

Copy, cut, paste and drag and drop of project objects, between windows and text editors

Alexander Graefc882bcd0cf68
diff --git a/WaveDudeNext.WPF/Controls/SceneOverlay.cs b/WaveDudeNext.WPF/Controls/SceneOverlay.cs
index dbcd872..b0da3b3 100644
--- a/WaveDudeNext.WPF/Controls/SceneOverlay.cs
+++ b/WaveDudeNext.WPF/Controls/SceneOverlay.cs
@@ -25,7 +25,9 @@ using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
+using NLog;
using WaveDudeNext.Model;
+using WaveDudeNext.WPF.Panes;
namespace WaveDudeNext.WPF.Controls;
@@ -121,6 +123,8 @@ public sealed class SceneOverlay : Panel
private const int KeyStepFast = 10;
private const double LabelOffset = 13.0;
+ private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();
+
/// <summary>Least distance of a rotation handle from its source's centre, in pixels.</summary>
private const double AngleHandleReach = 28.0;
@@ -155,6 +159,8 @@ public sealed class SceneOverlay : Panel
Background = Brushes.Transparent;
IsHitTestVisible = true;
Focusable = false;
+ // objects dragged from another window's tree are dropped onto the picture (2026-10-23)
+ AllowDrop = true;
}
/// <summary>The project whose sources and probes are shown; null shows nothing.</summary>
@@ -967,6 +973,70 @@ public sealed class SceneOverlay : Panel
}
}
+ // ---------------------------------------------------------------- dropping objects from another window
+
+ /// <summary>The dragged text last parsed during a drag over this picture, and what it held.</summary>
+ private (string Text, ProjectClipboard.Clip? Clip)? _dropCache;
+
+ /// <summary>
+ /// The objects a drag from another window carries, when it carries sources, parts, probes or schemes (as Copy writes
+ /// them, through <see cref="ProjectTree.ObjectsText"/>); null for anything else, and for a drag from this window, which
+ /// the tree reorders.
+ /// </summary>
+ private ProjectClipboard.Clip? DroppableClip(IDataObject data)
+ {
+ if (Project is not { } project || ProjectTree.IsFromThisWindow(data, project) || ProjectTree.ObjectsText(data) is not { } text)
+ {
+ return null;
+ }
+ if (_dropCache is not { } cache || cache.Text != text)
+ {
+ _dropCache = cache = (text, ProjectClipboard.Read(text));
+ }
+ return cache.Clip is { HasItems: true } clip ? clip : null;
+ }
+
+ /// <inheritdoc/>
+ protected override void OnDragOver(DragEventArgs e)
+ {
+ base.OnDragOver(e);
+ e.Effects = DroppableClip(e.Data) != null ? DragDropEffects.Copy : DragDropEffects.None;
+ e.Handled = true;
+ }
+
+ /// <summary>
+ /// A drop of objects from another window (the user's choice, 2026-10-23): pasted as Paste does, at the end of their
+ /// lists, then moved as a group so the first one sits on the canvas pixel under the mouse, held inside the canvas as a
+ /// group drag is; the dropped objects become the selection. One undo step.
+ /// </summary>
+ protected override void OnDrop(DragEventArgs e)
+ {
+ base.OnDrop(e);
+ e.Handled = true;
+ // read afresh: the paste takes the clip's objects into the project, so the parsed one of the drag-over is dropped
+ if (Project is not { } project || DroppableClip(e.Data) == null || ProjectTree.ObjectsText(e.Data) is not { } text
+ || ProjectClipboard.Read(text) is not { } clip)
+ {
+ return;
+ }
+ _dropCache = null;
+ (double x, double y) = ToCanvasExact(e.GetPosition(this));
+ int canvasX = (int)Math.Floor(x);
+ int canvasY = (int)Math.Floor(y);
+ IReadOnlyList<object> pasted = ProjectClipboard.Paste(project, clip, null);
+ ProjectClipboard.PlaceAt(pasted, canvasX, canvasY, CanvasWidth, CanvasHeight);
+ Logger.Debug("Dropped {Count} object(s) from another window onto the picture at ({X}, {Y})", pasted.Count, canvasX, canvasY);
+ if (SelectedItems is { } selection)
+ {
+ selection.Clear();
+ foreach (object item in pasted)
+ {
+ selection.Add(item);
+ }
+ }
+ SelectedItem = pasted.LastOrDefault();
+ }
+
// ---------------------------------------------------------------- the marquee
/// <inheritdoc/>
diff --git a/WaveDudeNext.WPF/MainWindow.Clipboard.cs b/WaveDudeNext.WPF/MainWindow.Clipboard.cs
new file mode 100644
index 0000000..725f97d
--- /dev/null
+++ b/WaveDudeNext.WPF/MainWindow.Clipboard.cs
@@ -0,0 +1,149 @@
+// 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.Runtime.InteropServices;
+using System.Windows;
+using System.Windows.Input;
+using WaveDudeNext.Model;
+using WaveDudeNext.Rendering;
+using WaveDudeNext.WPF.Commands;
+
+namespace WaveDudeNext.WPF;
+
+/// <summary>
+/// Cut, Copy and Paste of project objects (2026-10-23, the user's choices): WPF's commands bound on the window, so a
+/// focused text box handles them for its text first and everywhere else they act on the selection (the tree, the handles
+/// on the pictures, the Edit menu, a tree row's menu). The objects go to the Windows clipboard through
+/// <see cref="ProjectClipboard"/> (its format and the same XML as plain text, which Paste takes back too, from a text editor
+/// for instance); Paste puts them behind the current item and
+/// selects them, a settings object pastes onto its own row or the project root; Cut is Copy and Remove, for list items.
+/// Each is one undo step.
+/// UI thread.
+/// </summary>
+public partial class MainWindow
+{
+ /// <summary>The clipboard text last looked at and what it held, so the menus' frequent "can paste" checks parse it once.</summary>
+ private (string Text, ProjectClipboard.Clip? Clip)? _clipCache;
+
+ /// <summary>The copyable objects the command acts on: the row given, or the selection it belongs to.</summary>
+ private object[] CopyGroup(object? parameter) => [.. Group(parameter).Where(item => ProjectClipboard.CanCopy(Project, item))];
+
+ /// <summary>The list items among them (sources, parts, probes, schemes): what Cut takes away.</summary>
+ private object[] CutGroup(object? parameter) => [.. Group(parameter).Where(item => item is Source or OpticalPart or Probe or ColorScheme)];
+
+ private void CanCopyObjects(object sender, CanExecuteRoutedEventArgs e) => e.CanExecute = CopyGroup(e.Parameter).Length > 0;
+
+ private void CanCutObjects(object sender, CanExecuteRoutedEventArgs e) => e.CanExecute = CutGroup(e.Parameter).Length > 0;
+
+ private void CanPasteObjects(object sender, CanExecuteRoutedEventArgs e) =>
+ e.CanExecute = ClipboardClip() is { } clip && clip.CanPaste(Project, Target(e.Parameter));
+
+ private void OnCopyObjects(object sender, ExecutedRoutedEventArgs e) => CopyToClipboard(CopyGroup(e.Parameter));
+
+ private void OnCutObjects(object sender, ExecutedRoutedEventArgs e)
+ {
+ object[] group = CutGroup(e.Parameter);
+ if (group.Length > 0 && CopyToClipboard(group))
+ {
+ ProjectCommands.Remove.Execute(group.Length == 1 ? group[0] : e.Parameter, this);
+ }
+ }
+
+ private void OnPasteObjects(object sender, ExecutedRoutedEventArgs e)
+ {
+ // read afresh: a paste takes the clip's objects into the project, so each paste needs its own
+ if (ReadClipboard() is not { } text || ProjectClipboard.Read(text) is not { } clip)
+ {
+ return;
+ }
+ IReadOnlyList<object> pasted = ProjectClipboard.Paste(Project, clip, Target(e.Parameter));
+ if (pasted.Count == 0)
+ {
+ return;
+ }
+ Logger.Debug("Pasted {Count} object(s): {Names}", pasted.Count, string.Join(", ", pasted.Select(NameOrKind)));
+ SelectedItems.Clear();
+ foreach (object item in pasted.Where(item => item is Source or OpticalPart or Probe or ColorScheme))
+ {
+ SelectedItems.Add(item);
+ }
+ SelectedItem = pasted[^1];
+ }
+
+ /// <summary>Puts <paramref name="items"/> on the clipboard in the app's format and as text; false when the clipboard refused.</summary>
+ private bool CopyToClipboard(object[] items)
+ {
+ if (items.Length == 0)
+ {
+ return false;
+ }
+ string text = ProjectClipboard.Write(Project, items);
+ var data = new DataObject();
+ data.SetData(ProjectClipboard.Format, text);
+ data.SetText(text);
+ try
+ {
+ Clipboard.SetDataObject(data, copy: true);
+ }
+ catch (COMException ex)
+ {
+ // another program holds the clipboard open
+ Logger.Warn(ex, "The clipboard is busy: nothing was copied");
+ return false;
+ }
+ Logger.Debug("Copied {Count} object(s): {Names}", items.Length, string.Join(", ", items.Select(NameOrKind)));
+ _clipCache = null;
+ return true;
+ }
+
+ /// <summary>The objects on the clipboard as last parsed, for the "can paste" checks; null without any.</summary>
+ private ProjectClipboard.Clip? ClipboardClip()
+ {
+ if (ReadClipboard() is not { } text)
+ {
+ return null;
+ }
+ if (_clipCache is not { } cache || cache.Text != text)
+ {
+ _clipCache = cache = (text, ProjectClipboard.Read(text));
+ }
+ return cache.Clip;
+ }
+
+ /// <summary>The objects on the clipboard as text (the app's format, or plain text that may hold them), or null.</summary>
+ private static string? ReadClipboard()
+ {
+ try
+ {
+ return Clipboard.GetDataObject() is { } data ? Panes.ProjectTree.ObjectsText(data) : null;
+ }
+ catch (COMException)
+ {
+ // another program holds the clipboard open; the next check tries again
+ return null;
+ }
+ }
+
+ private static string NameOrKind(object item) => item switch
+ {
+ Source source => source.Name,
+ OpticalPart part => part.Name,
+ Probe probe => probe.Name,
+ ColorScheme scheme => scheme.Name,
+ _ => item.GetType().Name,
+ };
+}
diff --git a/WaveDudeNext.WPF/MainWindow.xaml b/WaveDudeNext.WPF/MainWindow.xaml
index 1cf6449..01c352d 100644
--- a/WaveDudeNext.WPF/MainWindow.xaml
+++ b/WaveDudeNext.WPF/MainWindow.xaml
@@ -40,7 +40,7 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or
MinWidth="800" MinHeight="500"
WindowStartupLocation="CenterScreen"
ResizeMode="CanResizeWithGrip"
- AllowDrop="True" Drop="OnDrop">
+ AllowDrop="True" DragOver="OnDragOver" Drop="OnDrop">
<Window.Resources>
<converters:EqualityConverter x:Key="Equality" />
@@ -180,7 +180,11 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or
<!-- 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) -->
+ <!-- Cut, Copy and Paste of project objects; handlers in MainWindow.Clipboard.cs. A focused text box handles them first, for its text -->
+ <CommandBinding Command="ApplicationCommands.Cut" CanExecute="CanCutObjects" Executed="OnCutObjects" />
+ <CommandBinding Command="ApplicationCommands.Copy" CanExecute="CanCopyObjects" Executed="OnCopyObjects" />
+ <CommandBinding Command="ApplicationCommands.Paste" CanExecute="CanPasteObjects" Executed="OnPasteObjects" />
+ <!-- Edit > Delete; handlers in MainWindow.Project.cs -->
<CommandBinding Command="{x:Static commands:EditCommands.Delete}" CanExecute="CanDelete" Executed="OnDelete" />
<!-- project structure; handlers in MainWindow.Project.cs -->
diff --git a/WaveDudeNext.WPF/MainWindow.xaml.cs b/WaveDudeNext.WPF/MainWindow.xaml.cs
index 1aaa415..7dd79bf 100644
--- a/WaveDudeNext.WPF/MainWindow.xaml.cs
+++ b/WaveDudeNext.WPF/MainWindow.xaml.cs
@@ -488,6 +488,17 @@ public partial class MainWindow : Window
messagesPane.FocusList();
}
+ /// <summary>
+ /// The window takes files dropped on it (a project, a scheme, Jeroen's configuration file); anything else is refused
+ /// where nothing inside took it (the tree takes project objects, the text boxes text), so the cursor shows what a drop
+ /// does. Without this a dragged tree object showed as allowed over the pictures and was then ignored (2026-10-23).
+ /// </summary>
+ private void OnDragOver(object sender, DragEventArgs e)
+ {
+ e.Effects = e.Data.GetDataPresent(DataFormats.FileDrop) ? DragDropEffects.Copy : DragDropEffects.None;
+ e.Handled = true;
+ }
+
private void OnDrop(object sender, DragEventArgs e)
{
if (e.Data.GetData(DataFormats.FileDrop) is string[] { Length: > 0 } files && ConfirmDiscard())
diff --git a/WaveDudeNext.WPF/Panes/ProjectTree.xaml b/WaveDudeNext.WPF/Panes/ProjectTree.xaml
index 6d9b4cd..0613551 100644
--- a/WaveDudeNext.WPF/Panes/ProjectTree.xaml
+++ b/WaveDudeNext.WPF/Panes/ProjectTree.xaml
@@ -184,6 +184,9 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or
<Separator />
<MenuItem Header="{DynamicResource MenuProjectToggleEnabled}" Command="{x:Static commands:ProjectCommands.ToggleEnabled}" InputGestureText="Space" controls:MenuIcon.Glyph="&#xE73A;" />
<MenuItem Header="{DynamicResource MenuProjectDuplicate}" Command="{x:Static commands:ProjectCommands.Duplicate}" InputGestureText="Ctrl+D" controls:MenuIcon.Glyph="&#xF413;" />
+ <MenuItem Header="{DynamicResource MenuEditCut}" controls:MenuIcon.Glyph="&#xE8C6;" Command="ApplicationCommands.Cut" />
+ <MenuItem Header="{DynamicResource MenuEditCopy}" controls:MenuIcon.Glyph="&#xE8C8;" Command="ApplicationCommands.Copy" />
+ <MenuItem Header="{DynamicResource MenuEditPaste}" controls:MenuIcon.Glyph="&#xE77F;" Command="ApplicationCommands.Paste" />
<MenuItem Header="{DynamicResource MenuProjectRemove}" Command="{x:Static commands:ProjectCommands.Remove}" InputGestureText="Del" controls:MenuIcon.Glyph="&#xE738;" />
<Separator />
<MenuItem Header="{DynamicResource MenuProjectMoveUp}" Command="{x:Static commands:ProjectCommands.MoveUp}" InputGestureText="Alt+Up" controls:MenuIcon.Glyph="&#xE74A;" />
diff --git a/WaveDudeNext.WPF/Panes/ProjectTree.xaml.cs b/WaveDudeNext.WPF/Panes/ProjectTree.xaml.cs
index 11c6b91..86da3b5 100644
--- a/WaveDudeNext.WPF/Panes/ProjectTree.xaml.cs
+++ b/WaveDudeNext.WPF/Panes/ProjectTree.xaml.cs
@@ -25,6 +25,7 @@ using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
+using NLog;
using WaveDudeNext.Model;
using WaveDudeNext.WPF.Controls;
using WaveDudeNext.WPF.Converters;
@@ -44,6 +45,8 @@ public partial class ProjectTree : UserControl
{
private const string DragFormat = "WaveDudeNext.ProjectTree.Item";
+ private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();
+
/// <summary>Identifies the <see cref="Project"/> property.</summary>
public static readonly DependencyProperty ProjectProperty = DependencyProperty.Register(
nameof(Project), typeof(Project), typeof(ProjectTree));
@@ -88,6 +91,10 @@ public partial class ProjectTree : UserControl
}
private object? _dragCandidate;
+ /// <summary>Whether a drag started in this tree is under way: its drops reorder, and never paste a copy of themselves.</summary>
+ private bool _dragging;
+ /// <summary>The dragged text last parsed during a drag over this tree, and what it held.</summary>
+ private (string Text, ProjectClipboard.Clip? Clip)? _dropCache;
private Point _dragStart;
private InsertionAdorner? _adorner;
private object? _anchor;
@@ -311,7 +318,11 @@ public partial class ProjectTree : UserControl
return false;
}
- // ----- drag-and-drop reordering -----
+ // ----- drag and drop: reordering within the tree, copying between windows -----
+ // A drag carries the item itself, for reordering within its list here, and the item as Copy writes it (the app's
+ // clipboard format and plain text, 2026-10-23), so another WaveDude Next window takes a copy as Paste would and a
+ // text editor takes the XML. A drop from another window is placed by the paste logic: before or after a row of a list
+ // (by the half of the row), at the end of a folder's list, or onto Scene, Simulation, Display or the project root.
private void OnPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
@@ -321,9 +332,9 @@ public partial class ProjectTree : UserControl
{
return; // row buttons are clicks, not drags
}
- if (FindAncestor<TreeViewItem>(origin) is { DataContext: Source or OpticalPart or Probe or ColorScheme } row)
+ if (FindAncestor<TreeViewItem>(origin) is { } row && Project is { } project && ProjectClipboard.CanCopy(project, row.DataContext))
{
- if (TryModifiedClick(row.DataContext))
+ if (row.DataContext is Source or OpticalPart or Probe or ColorScheme && TryModifiedClick(row.DataContext))
{
e.Handled = true; // the TreeView would make the row its plain selection
return;
@@ -335,7 +346,7 @@ public partial class ProjectTree : UserControl
private void OnPreviewMouseMove(object sender, MouseEventArgs e)
{
- if (_dragCandidate == null || e.LeftButton != MouseButtonState.Pressed)
+ if (_dragCandidate == null || e.LeftButton != MouseButtonState.Pressed || Project is not { } project)
{
return;
}
@@ -347,8 +358,25 @@ public partial class ProjectTree : UserControl
}
object item = _dragCandidate;
_dragCandidate = null;
- DragDrop.DoDragDrop(tree, new DataObject(DragFormat, item), DragDropEffects.Move);
- ClearAdorner();
+ var data = new DataObject();
+ if (ListOf(item) != null)
+ {
+ data.SetData(DragFormat, item);
+ }
+ string text = ProjectClipboard.Write(project, [item]);
+ data.SetData(ProjectClipboard.Format, text);
+ data.SetText(text);
+ _dragging = true;
+ try
+ {
+ DragDrop.DoDragDrop(tree, data, DragDropEffects.Move | DragDropEffects.Copy);
+ }
+ finally
+ {
+ _dragging = false;
+ _dropCache = null;
+ ClearAdorner();
+ }
}
private void OnDragOver(object sender, DragEventArgs e)
@@ -356,20 +384,19 @@ public partial class ProjectTree : UserControl
e.Effects = DragDropEffects.None;
e.Handled = true;
ClearAdorner();
- if (e.Data.GetData(DragFormat) is not { } item)
- {
- return;
- }
- DropTarget? target = FindDropTarget(item, e.GetPosition(tree));
- if (target == null)
+ if (OwnItem(e.Data) is { } item)
{
+ if (FindDropTarget(item, e.GetPosition(tree)) is { } target)
+ {
+ e.Effects = DragDropEffects.Move;
+ ShowAdorner(target.Row, target.Header, target.Placement);
+ }
return;
}
- e.Effects = DragDropEffects.Move;
- if (AdornerLayer.GetAdornerLayer(target.Row) is { } layer && tree.TryFindResource("Accent") is Brush brush)
+ if (!_dragging && DraggedClip(e.Data) is { } clip && FindPasteTarget(clip, e.GetPosition(tree)) is { } paste)
{
- _adorner = new InsertionAdorner(target.Header, brush, target.Placement);
- layer.Add(_adorner);
+ e.Effects = DragDropEffects.Copy;
+ ShowAdorner(paste.Row, paste.Header, paste.Placement);
}
}
@@ -379,24 +406,161 @@ public partial class ProjectTree : UserControl
{
e.Handled = true;
ClearAdorner();
- if (Project == null || e.Data.GetData(DragFormat) is not { } item)
+ if (Project is not { } project)
+ {
+ return;
+ }
+ if (OwnItem(e.Data) is { } item)
+ {
+ if (FindDropTarget(item, e.GetPosition(tree)) is not { } target)
+ {
+ return;
+ }
+ bool moved = item switch
+ {
+ Source source => project.Move(source, target.Index),
+ OpticalPart part => project.Move(part, target.Index),
+ Probe probe => project.Move(probe, target.Index),
+ _ => false,
+ };
+ if (moved)
+ {
+ Select(item);
+ }
+ return;
+ }
+ // read afresh: the paste takes the clip's objects into the project
+ if (_dragging || ObjectsText(e.Data) is not { } text || ProjectClipboard.Read(text) is not { } clip
+ || FindPasteTarget(clip, e.GetPosition(tree)) is not { } paste)
{
return;
}
- if (FindDropTarget(item, e.GetPosition(tree)) is not { } target)
+ IReadOnlyList<object> pasted = ProjectClipboard.Paste(project, clip, paste.Current, paste.Before);
+ _dropCache = null;
+ if (pasted.Count == 0)
{
return;
}
- bool moved = item switch
+ Logger.Debug("Dropped {Count} object(s) from another window", pasted.Count);
+ if (SelectedItems is { } selection)
+ {
+ selection.Clear();
+ foreach (object added in pasted.Where(added => added is Source or OpticalPart or Probe or ColorScheme))
+ {
+ selection.Add(added);
+ }
+ }
+ Select(pasted[^1]);
+ }
+
+ /// <summary>
+ /// Whether a drag started in this window: it carries a live item of <paramref name="project"/>'s lists (a drag from
+ /// another window carries none that can be read here). The pictures refuse such drops: they take objects from other
+ /// windows only.
+ /// </summary>
+ internal static bool IsFromThisWindow(IDataObject data, Project project)
+ {
+ try
+ {
+ return data.GetDataPresent(DragFormat) && data.GetData(DragFormat) is { } item
+ && ((IList[])[project.Sources, project.Parts, project.Probes, project.ColorSchemes]).Any(list => list.Contains(item));
+ }
+ catch (Exception ex) when (ex is System.Runtime.InteropServices.COMException or InvalidOperationException)
+ {
+ return false;
+ }
+ }
+
+ /// <summary>The dragged item when the drag started in this tree and the item is in this project's lists; null otherwise (a drag from another window carries no live object).</summary>
+ private object? OwnItem(IDataObject data)
+ {
+ try
+ {
+ return data.GetDataPresent(DragFormat) && data.GetData(DragFormat) is { } item && ListOf(item)?.Contains(item) == true ? item : null;
+ }
+ catch (Exception ex) when (ex is System.Runtime.InteropServices.COMException or InvalidOperationException)
+ {
+ return null;
+ }
+ }
+
+ /// <summary>
+ /// The objects a drag or the clipboard carries, as Copy writes them: the app's format, else plain text that may hold
+ /// them (2026-10-23: copied back from a text editor, which keeps text only; <see cref="ProjectClipboard.Read"/> decides,
+ /// and text not starting with an element is not even parsed). Null for neither. Shared by the tree, the pictures and
+ /// Paste.
+ /// </summary>
+ internal static string? ObjectsText(IDataObject data)
+ {
+ try
+ {
+ if (data.GetDataPresent(ProjectClipboard.Format))
+ {
+ return data.GetData(ProjectClipboard.Format) as string;
+ }
+ return data.GetDataPresent(DataFormats.UnicodeText) && data.GetData(DataFormats.UnicodeText) is string text && text.TrimStart().StartsWith('<')
+ ? text
+ : null;
+ }
+ catch (Exception ex) when (ex is System.Runtime.InteropServices.COMException or InvalidOperationException)
+ {
+ return null;
+ }
+ }
+
+ /// <summary>The dragged objects as last parsed, for the many drag-over events of one drag; null without any.</summary>
+ private ProjectClipboard.Clip? DraggedClip(IDataObject data)
+ {
+ if (ObjectsText(data) is not { } text)
+ {
+ return null;
+ }
+ if (_dropCache is not { } cache || cache.Text != text)
+ {
+ _dropCache = cache = (text, ProjectClipboard.Read(text));
+ }
+ return cache.Clip;
+ }
+
+ /// <summary>Where a drop from another window would go, as the paste logic takes it: the current item it is placed by, and before it or not.</summary>
+ private sealed record PasteTarget(TreeViewItem Row, FrameworkElement Header, InsertionPlacement Placement, object? Current, bool Before);
+
+ /// <summary>
+ /// Resolves a drop of <paramref name="clip"/> from another window: on a list item before or after it (by the half of the
+ /// row), on a folder at the end of its list, on Scene, Simulation, Display or the project root as a paste onto them. Null
+ /// where the clip has nothing to give (settings onto a list row without list items, for instance).
+ /// </summary>
+ private PasteTarget? FindPasteTarget(ProjectClipboard.Clip clip, Point position)
+ {
+ if (Project is not { } project || tree.InputHitTest(position) is not DependencyObject hit
+ || FindAncestor<TreeViewItem>(hit) is not { } row
+ || row.Template.FindName("PART_Header", row) is not FrameworkElement header)
{
- Source source => Project.Move(source, target.Index),
- OpticalPart part => Project.Move(part, target.Index),
- Probe probe => Project.Move(probe, target.Index),
- _ => false,
- };
- if (moved)
+ return null;
+ }
+ switch (row.DataContext)
+ {
+ case Source or OpticalPart or Probe or ColorScheme:
+ bool before = position.Y < header.TransformToAncestor(tree).Transform(new Point(0, header.ActualHeight / 2)).Y;
+ return clip.CanPaste(project, row.DataContext)
+ ? new PasteTarget(row, header, before ? InsertionPlacement.Before : InsertionPlacement.After, row.DataContext, before)
+ : null;
+ case NamedCollection:
+ // the folder's list takes its items at the end, as do the others
+ return clip.HasItems ? new PasteTarget(row, header, InsertionPlacement.Into, null, false) : null;
+ case { } other when clip.CanPaste(project, other):
+ return new PasteTarget(row, header, InsertionPlacement.Into, other, false);
+ default:
+ return null;
+ }
+ }
+
+ private void ShowAdorner(TreeViewItem row, FrameworkElement header, InsertionPlacement placement)
+ {
+ if (AdornerLayer.GetAdornerLayer(row) is { } layer && tree.TryFindResource("Accent") is Brush brush)
{
- Select(item);
+ _adorner = new InsertionAdorner(header, brush, placement);
+ layer.Add(_adorner);
}
}
diff --git a/WaveDudeNext/Model/Project.cs b/WaveDudeNext/Model/Project.cs
index d334f86..dbf2759 100644
--- a/WaveDudeNext/Model/Project.cs
+++ b/WaveDudeNext/Model/Project.cs
@@ -474,7 +474,7 @@ public sealed class Project : ObservableObject
}
/// <summary>"name copy", then "name copy 2", ... skipping names already in <paramref name="taken"/>.</summary>
- private static string CopyName(string name, IEnumerable<string> taken)
+ internal static string CopyName(string name, IEnumerable<string> taken)
{
var names = taken.ToHashSet(StringComparer.OrdinalIgnoreCase);
string stem = $"{name} copy";
diff --git a/WaveDudeNext/Model/ProjectClipboard.cs b/WaveDudeNext/Model/ProjectClipboard.cs
new file mode 100644
index 0000000..0ed0b92
--- /dev/null
+++ b/WaveDudeNext/Model/ProjectClipboard.cs
@@ -0,0 +1,229 @@
+// 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.Reflection;
+using System.Xml;
+using System.Xml.Serialization;
+using WaveDudeNext.Rendering;
+
+namespace WaveDudeNext.Model;
+
+/// <summary>
+/// Copy and paste of project objects (2026-10-23, the user's request and choices): sources, parts, probes and colour
+/// schemes, and the Scene, Simulation and Display settings. The clipboard text is an XML fragment of the objects' own
+/// elements, as the project file writes them (<c>&lt;Source …/&gt;&lt;Fiber …&gt;…&lt;/Fiber&gt;</c>, defaults left out) and
+/// nothing else: no wrapper, seed or version. The element names come from the <see cref="XmlElementAttribute"/>s on
+/// <see cref="Project"/>, so the fragment cannot drift from the file. <see cref="Paste"/> puts the objects into a project as
+/// Duplicate does: behind the current item when that is in the same list, else at the end, at the same canvas position, a
+/// name with " copy" only when the name is taken; a settings object replaces the project's, pasted onto its own row or the
+/// project root (2026-10-23, the user's addition).
+/// UI thread, like the model.
+/// </summary>
+public static class ProjectClipboard
+{
+ /// <summary>The clipboard format of the objects (the same text is offered as plain text too).</summary>
+ public const string Format = "WaveDudeNext.Objects";
+
+ /// <summary>The settings objects of a project: replaced as a whole by a paste onto their row or the project root.</summary>
+ private static readonly (Type Type, Func<Project, object> Get, Action<Project, object> Set)[] SettingsObjects =
+ [
+ (typeof(Scene), project => project.Scene, (project, value) => project.Scene = (Scene)value),
+ (typeof(Simulation), project => project.Simulation, (project, value) => project.Simulation = (Simulation)value),
+ (typeof(Display), project => project.Display, (project, value) => project.Display = (Display)value),
+ ];
+
+ /// <summary>Each copyable type's element name in the project file, and back.</summary>
+ private static readonly Dictionary<Type, string> ElementOf = ElementNames();
+ private static readonly Dictionary<string, Type> TypeOf = ElementOf.ToDictionary(entry => entry.Value, entry => entry.Key);
+
+ /// <summary>One serializer per type, made once: a serializer with its own root makes a new assembly each time it is created.</summary>
+ private static readonly Dictionary<Type, XmlSerializer> Serializers = [];
+ private static readonly XmlSerializerNamespaces NoNamespaces = new([XmlQualifiedName.Empty]);
+
+ /// <summary>Whether <paramref name="item"/> of <paramref name="project"/> can be copied: a list item or a settings object.</summary>
+ public static bool CanCopy(Project project, object item) =>
+ item is Source or OpticalPart or Probe or ColorScheme || SettingsObjects.Any(entry => ReferenceEquals(entry.Get(project), item));
+
+ /// <summary>The clipboard text for <paramref name="items"/> of <paramref name="project"/>: their elements in tree order; items that cannot be copied are left out.</summary>
+ public static string Write(Project project, IEnumerable<object> items)
+ {
+ var chosen = items.ToHashSet(ReferenceEqualityComparer.Instance);
+ IEnumerable<object> ordered = SettingsObjects.Select(entry => entry.Get(project))
+ .Concat(project.Sources).Concat(project.Parts).Concat(project.Probes).Concat(project.ColorSchemes)
+ .Where(chosen.Contains);
+ // one writer per element: the serializer starts a document, which a fragment writer refuses; the elements are then
+ // joined line by line into the fragment
+ var settings = new XmlWriterSettings { Indent = true, IndentChars = "\t", OmitXmlDeclaration = true };
+ return string.Join(Environment.NewLine, ordered.Select(item =>
+ {
+ var text = new StringWriter();
+ using (var writer = XmlWriter.Create(text, settings))
+ {
+ // written as it is: serialising does not change the object
+ SerializerOf(item.GetType()).Serialize(writer, item, NoNamespaces);
+ }
+ return text.ToString();
+ }));
+ }
+
+ /// <summary>The objects in clipboard text made by <see cref="Write"/>, normalised; null for text holding anything else or nothing.</summary>
+ public static Clip? Read(string text)
+ {
+ var objects = new List<object>();
+ try
+ {
+ using var reader = XmlReader.Create(new StringReader(text), new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Fragment });
+ while (reader.MoveToContent() == XmlNodeType.Element)
+ {
+ if (!TypeOf.TryGetValue(reader.LocalName, out Type? type))
+ {
+ return null;
+ }
+ object item = SerializerOf(type).Deserialize(reader)!;
+ Normalize(item);
+ objects.Add(item);
+ }
+ }
+ catch (Exception e) when (e is XmlException or InvalidOperationException)
+ {
+ return null;
+ }
+ return objects.Count > 0 ? new Clip(objects) : null;
+ }
+
+ /// <summary>
+ /// Puts the objects of <paramref name="clip"/> into <paramref name="project"/>: each list's items behind
+ /// <paramref name="current"/> when it is in that list (the later ones behind the earlier), else at its end; a settings
+ /// object replaces the project's when <paramref name="current"/> is the project's object of that kind or the project itself. Returns what was
+ /// put in, in that order. With <paramref name="before"/> (a drop on the upper half of a row) the items go in front of
+ /// <paramref name="current"/> instead. A clip is used once: its objects become the project's.
+ /// </summary>
+ public static IReadOnlyList<object> Paste(Project project, Clip clip, object? current, bool before = false)
+ {
+ var pasted = new List<object>();
+ foreach ((Type type, Func<Project, object> get, Action<Project, object> set) in SettingsObjects)
+ {
+ if (Accepts(project, get, current) && clip.Objects.FirstOrDefault(type.IsInstanceOfType) is { } value)
+ {
+ set(project, value);
+ pasted.Add(value);
+ }
+ }
+ Insert(project.Sources, clip.Objects.OfType<Source>(), current, before, source => source.Name, (source, name) => source.Name = name, pasted);
+ Insert(project.Parts, clip.Objects.OfType<OpticalPart>(), current, before, part => part.Name, (part, name) => part.Name = name, pasted);
+ Insert(project.Probes, clip.Objects.OfType<Probe>(), current, before, probe => probe.Name, (probe, name) => probe.Name = name, pasted);
+ Insert(project.ColorSchemes, clip.Objects.OfType<ColorScheme>(), current, before, scheme => scheme.Name, (scheme, name) => scheme.Name = name, pasted);
+ foreach (Source source in pasted.OfType<Source>())
+ {
+ // the emitters follow the seed of the project they are in now
+ source.GenerateElements(project.Seed);
+ }
+ return pasted;
+ }
+
+ /// <summary>
+ /// Moves pasted objects as a group so that the first movable one's first anchor (a source's or part's position, a
+ /// probe's point A) lands on canvas pixel (<paramref name="x"/>, <paramref name="y"/>), held inside a canvas of
+ /// <paramref name="width"/> × <paramref name="height"/> as a group drag is (<see cref="Movable.Limit"/>): a drop onto the
+ /// picture (2026-10-23, the user's choice). Schemes and settings objects do not move.
+ /// </summary>
+ public static void PlaceAt(IEnumerable<object> pasted, int x, int y, int width, int height)
+ {
+ List<IMovable> movables = [.. pasted.OfType<IMovable>()];
+ if (movables.Count == 0 || !movables[0].Anchors.Any())
+ {
+ return;
+ }
+ (int anchorX, int anchorY) = movables[0].Anchors.First();
+ (int dx, int dy) = Movable.Limit(movables, x - anchorX, y - anchorY, width, height);
+ Movable.MoveAll(movables, dx, dy);
+ }
+
+ private static void Insert<T>(IList<T> list, IEnumerable<T> items, object? current, bool before, Func<T, string> nameOf, Action<T, string> rename, List<object> pasted)
+ where T : class
+ {
+ int at = current is T anchor && list.IndexOf(anchor) is >= 0 and var index ? (before ? index : index + 1) : list.Count;
+ foreach (T item in items)
+ {
+ string name = nameOf(item);
+ if (list.Any(other => string.Equals(nameOf(other), name, StringComparison.OrdinalIgnoreCase)))
+ {
+ rename(item, Project.CopyName(name, list.Select(nameOf)));
+ }
+ list.Insert(at++, item);
+ pasted.Add(item);
+ }
+ }
+
+ /// <summary>Whether a settings object pastes with <paramref name="current"/> the current item: onto its own row, or onto the project root.</summary>
+ private static bool Accepts(Project project, Func<Project, object> get, object? current) =>
+ ReferenceEquals(get(project), current) || ReferenceEquals(project, current);
+
+ /// <summary>Clamps a read object into range, as loading a project does.</summary>
+ private static void Normalize(object item)
+ {
+ switch (item)
+ {
+ case Scene scene: scene.Normalize(); break;
+ case Simulation simulation: simulation.Normalize(); break;
+ case Display display: display.Normalize(); break;
+ case Source source: source.Normalize(); break;
+ case OpticalPart part: part.Normalize(); break;
+ case Probe probe: probe.Normalize(); break;
+ case ColorScheme scheme: scheme.Normalize(); break;
+ }
+ }
+
+ private static XmlSerializer SerializerOf(Type type)
+ {
+ if (!Serializers.TryGetValue(type, out XmlSerializer? serializer))
+ {
+ serializer = new XmlSerializer(type, new XmlRootAttribute(ElementOf[type]));
+ Serializers[type] = serializer;
+ }
+ return serializer;
+ }
+
+ /// <summary>The element name of every type a project's elements hold, read from <see cref="Project"/>'s own attributes.</summary>
+ private static Dictionary<Type, string> ElementNames()
+ {
+ var names = new Dictionary<Type, string>();
+ foreach (PropertyInfo property in typeof(Project).GetProperties(BindingFlags.Public | BindingFlags.Instance))
+ {
+ foreach (XmlElementAttribute element in property.GetCustomAttributes<XmlElementAttribute>())
+ {
+ Type type = element.Type ?? (property.PropertyType.IsGenericType ? property.PropertyType.GetGenericArguments()[0] : property.PropertyType);
+ names[type] = string.IsNullOrEmpty(element.ElementName) ? property.Name : element.ElementName;
+ }
+ }
+ // the description is a plain string, not an object one copies
+ names.Remove(typeof(string));
+ return names;
+ }
+
+ /// <summary>Objects read from the clipboard, in the order they were written.</summary>
+ /// <param name="Objects">Sources, parts, probes, schemes and settings objects, not in any project yet.</param>
+ public sealed record Clip(IReadOnlyList<object> Objects)
+ {
+ /// <summary>Whether the clip holds list items (sources, parts, probes, schemes).</summary>
+ public bool HasItems => Objects.Any(item => item is Source or OpticalPart or Probe or ColorScheme);
+
+ /// <summary>Whether the clip can be pasted with <paramref name="current"/> the project's current item: it has list items, or a settings object of the current row's kind, or of any kind onto the project root.</summary>
+ public bool CanPaste(Project project, object? current) =>
+ HasItems || SettingsObjects.Any(entry => Accepts(project, entry.Get, current) && Objects.Any(entry.Type.IsInstanceOfType));
+ }
+}
diff --git a/_tools/library_check/Program.cs b/_tools/library_check/Program.cs
index 87b8018..feadc72 100644
--- a/_tools/library_check/Program.cs
+++ b/_tools/library_check/Program.cs
@@ -268,6 +268,7 @@ internal static class Program
CheckMovable();
CheckRanges();
CheckHistory();
+ CheckClipboard();
CheckOpenEdges(W, H);
CheckFrameStore(scene);
CheckPreviewQuality(scene, W, H);
@@ -498,6 +499,73 @@ internal static class Program
Check(undone == 101 && history.Count == 102 && FileOf(project) == first, $"{undone} undos walk back through {history.Count} steps to the first");
}
+ /// <summary>
+ /// Copy and paste (<see cref="ProjectClipboard"/>): the objects travel as clipboard text into another project, behind
+ /// its current item, renamed only on a clash, their emitters from the new project's seed; a settings object replaces on its
+ /// own row or the project root only; text that is no clip is refused.
+ /// </summary>
+ private static void CheckClipboard()
+ {
+ Console.WriteLine("--- copy and paste (ProjectClipboard)");
+ var from = new Project { Seed = 3 };
+ Source one = from.AddSource();
+ one.X = 40;
+ from.AddSource();
+ var fiber = from.AddPart<FiberPart>();
+ fiber.Nodes[0].OutY = 30;
+ Probe probe = from.AddProbe();
+ ColorScheme scheme = from.AddColorScheme();
+ from.Scene.Width = 333;
+ string text = ProjectClipboard.Write(from, [probe, fiber, one, from.Sources[1], scheme, new object()]);
+ Check(text.StartsWith("<Source", StringComparison.Ordinal) && text.Contains("<Fiber") && text.Contains("<Probe") && text.Contains("<ColorScheme")
+ && !text.Contains("Project") && !text.Contains("Seed") && !text.Contains("Version") && !text.Contains("<Scene"),
+ "a copy is a fragment of the objects' own elements, in tree order: no wrapper, seed, version or settings not chosen; unknown objects left out");
+
+ var to = new Project { Seed = 9 };
+ Source existing = to.AddSource();
+ Source last = to.AddSource();
+ ProjectClipboard.Clip? clip = ProjectClipboard.Read(text);
+ Check(clip is { HasItems: true } && clip.CanPaste(to, null), "the text reads back as a clip with items");
+ IReadOnlyList<object> pasted = ProjectClipboard.Paste(to, clip!, existing);
+ Check(pasted.Count == 5 && to.Sources.Select(s => s.Name).SequenceEqual(["Source 1", "Source 1 copy", "Source 2 copy", "Source 2"]),
+ "sources paste behind the current one, in order, renamed only where the name is taken: " + string.Join(", ", to.Sources.Select(s => s.Name)));
+ Check(to.Sources[1] is { X: 40 } pastedOne && !ReferenceEquals(pastedOne, one) && pastedOne.Elements.Count > 0,
+ "a pasted source keeps its position, is a copy, and has its emitters");
+ Check(to.Parts is [FiberPart { Name: "Fiber 1", Nodes: [{ OutY: 30 }, _] }] && to.Probes is [{ Name: "Probe 1" }] && to.ColorSchemes.Count == 1,
+ "a part (with its nodes), a probe and a scheme paste at the end of their lists, their free names kept");
+
+ string scene = ProjectClipboard.Write(from, [from.Scene]);
+ ProjectClipboard.Clip? sceneClip = ProjectClipboard.Read(scene);
+ Check(sceneClip is { HasItems: false } && !sceneClip.CanPaste(to, to.Sources[0]) && sceneClip.CanPaste(to, to.Scene),
+ "a copied scene can be pasted only onto the scene row");
+ ProjectClipboard.Paste(to, sceneClip!, to.Scene);
+ Check(to.Scene.Width == 333, "pasted onto the scene row, it replaces the scene");
+ from.Simulation.Steps = 777;
+ from.Display.Field.Brightness = 4.5;
+ ProjectClipboard.Clip? settingsClip = ProjectClipboard.Read(ProjectClipboard.Write(from, [from.Simulation, from.Display]));
+ Check(settingsClip != null && settingsClip.CanPaste(to, to) && !settingsClip.CanPaste(to, to.Scene), "settings can be pasted onto the project root, not onto another settings row");
+ ProjectClipboard.Paste(to, settingsClip!, to);
+ Check(to.Simulation.Steps == 777 && to.Display.Field.Brightness == 4.5 && to.Scene.Width == 333,
+ "pasted onto the project root, each copied settings object replaces the project's, the others stay");
+
+ ProjectClipboard.Paste(to, ProjectClipboard.Read(ProjectClipboard.Write(from, [from.Sources[1]]))!, to.Sources[0], before: true);
+ Check(to.Sources[0].Name == "Source 2 copy 2" && to.Sources[1].Name == "Source 1",
+ "a drop on the upper half of a row puts the item in front of it: " + string.Join(", ", to.Sources.Select(s => s.Name)));
+ // a drop onto the picture: the first object's anchor on the drop pixel, the group's formation kept, inside the canvas
+ var group = new Project();
+ Source left = group.AddSource();
+ (left.X, left.Y) = (100, 100);
+ Probe right = group.AddProbe();
+ (right.AX, right.AY) = (150, 120);
+ var onto = new Project();
+ IReadOnlyList<object> dropped = ProjectClipboard.Paste(onto, ProjectClipboard.Read(ProjectClipboard.Write(group, [left, right]))!, null);
+ ProjectClipboard.PlaceAt(dropped, 300, 200, 1920, 1080);
+ Check(onto.Sources[0] is { X: 300, Y: 200 } && onto.Probes[0] is { AX: 350, AY: 220 }, "dropped onto the picture, the first object lands on the drop pixel and the rest keep their offsets");
+ ProjectClipboard.PlaceAt(dropped, 1910, 5, 1920, 1080);
+ Check(onto.Sources[0] is { X: 1869, Y: 5 } && onto.Probes[0] is { AX: 1919, AY: 25 }, "near the edge the group stops as a whole inside the canvas, as a group drag does");
+ Check(ProjectClipboard.Read("<Project />") == null && ProjectClipboard.Read("just text") == null, "other text is no clip");
+ }
+
/// <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)
{