diff --git a/OpenNest.Avalonia/Controls/PlateCanvas.cs b/OpenNest.Avalonia/Controls/PlateCanvas.cs
index f4032449..b8cb4131 100644
--- a/OpenNest.Avalonia/Controls/PlateCanvas.cs
+++ b/OpenNest.Avalonia/Controls/PlateCanvas.cs
@@ -191,6 +191,20 @@ namespace OpenNest.Avalonia.Controls
void IPlateToolHost.Invalidate() => InvalidateVisual();
+ ///
+ /// A right click released on a selected part in Select, while the plate takes edits: the
+ /// host shows the part menu (Join and Remove Common Line), as the WinForms plate view.
+ ///
+ public event EventHandler PartMenuRequested;
+
+ private Part PartMenuAt(Point at)
+ {
+ if (plate == null || EditsLocked || tools.Current is not SelectTool)
+ return null;
+ var part = hitTester.PartAt(plate, ToWorld(at));
+ return part != null && selection.Contains(part) ? part : null;
+ }
+
/// Edit > Select All: every part on the plate, cut-off segments excepted.
public void SelectAll() => selection.SelectAll();
@@ -556,6 +570,8 @@ namespace OpenNest.Avalonia.Controls
else if (button != ToolButton.None
&& tools.Current.PointerReleased(ToolPointerAt(e.GetPosition(this), button, e.KeyModifiers)))
e.Handled = true;
+ if (button == ToolButton.Right && PartMenuAt(e.GetPosition(this)) is { } part)
+ PartMenuRequested?.Invoke(this, part);
// Kept while another button is still down: a middle click during a left drag must
// not end the drag.
var held = e.GetCurrentPoint(this).Properties;
diff --git a/OpenNest.Avalonia/MainWindow.Arrange.cs b/OpenNest.Avalonia/MainWindow.Arrange.cs
new file mode 100644
index 00000000..af4f481d
--- /dev/null
+++ b/OpenNest.Avalonia/MainWindow.Arrange.cs
@@ -0,0 +1,182 @@
+using System;
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using Avalonia.Controls;
+using Avalonia.Interactivity;
+using OpenNest.Avalonia.Controls;
+using OpenNest.Desktop;
+using OpenNest.Desktop.Interaction;
+using OpenNest.Undo;
+
+namespace OpenNest.Avalonia
+{
+ ///
+ /// Plate > Arrange on the active nest's plate, through the shared ,
+ /// each one undo step under the WinForms label: align, evenly space and center parts, Expand
+ /// Spacing and Fix Spacing behind a Cancel window, and the common-line commands, which the
+ /// right-click menu on a selected part also offers. While Auto Nest works on the nest its plate
+ /// takes none of them; Expand and Fix Spacing then say why.
+ ///
+ public partial class MainWindow
+ {
+ // The nest whose Expand or Fix Spacing search is running: its plate is locked until the
+ // worker stops, as the WinForms Cancel window keeps it.
+ private NestTab arrangingTab;
+
+ private PlateCanvas ArrangeCanvas =>
+ ActiveView?.PlateView is { Plate: not null } canvas ? canvas : null;
+
+ /// Shows the part menu when a selected part on 's plate is right-clicked.
+ private void WatchPartMenu(NestView view) =>
+ view.PlateView.PartMenuRequested += (_, _) => ShowPartMenu(view);
+
+ // As WinForms (ArrangeMenu_Opening): Cut Common Lines Twice shows the plate's setting.
+ // The other commands do nothing, or say why, when they have nothing to act on.
+ private void OnArrangeMenuOpened(object sender, RoutedEventArgs e)
+ {
+ var canvas = ArrangeCanvas;
+ var editable = canvas is { EditsLocked: false };
+ foreach (var item in new MenuItem[]
+ {
+ AlignLeftMenuItem, AlignRightMenuItem, AlignTopMenuItem, AlignBottomMenuItem,
+ AlignHorizontallyMenuItem, AlignVerticallyMenuItem, EvenlySpaceHorizontallyMenuItem,
+ EvenlySpaceVerticallyMenuItem, CenterPartsMenuItem, JoinCommonLineMenuItem,
+ RemoveCommonLineMenuItem, CutCommonLinesTwiceMenuItem,
+ })
+ item.IsEnabled = editable;
+ // Enabled during Auto Nest so they can say why they wait, as WinForms does.
+ ExpandSpacingMenuItem.IsEnabled = canvas != null && arrangingTab == null;
+ FixSpacingMenuItem.IsEnabled = canvas != null && arrangingTab == null;
+ CutCommonLinesTwiceMenuItem.IsChecked = canvas?.Plate.CutCommonLinesTwice == true;
+ }
+
+ private void OnAlign(object sender, RoutedEventArgs e)
+ {
+ if (ArrangeCanvas is { } canvas && (sender as MenuItem)?.Tag is string tag
+ && Enum.TryParse(tag, out var type))
+ PlateArrange.Align(canvas, type);
+ }
+
+ private void OnCenterParts(object sender, RoutedEventArgs e)
+ {
+ if (ArrangeCanvas is { } canvas)
+ PlateArrange.CenterParts(canvas);
+ }
+
+ private async void OnJoinCommonLine(object sender, RoutedEventArgs e) => await JoinCommonLineAsync();
+
+ private async void OnRemoveCommonLine(object sender, RoutedEventArgs e) => await RemoveCommonLineAsync();
+
+ private void OnCutCommonLinesTwice(object sender, RoutedEventArgs e)
+ {
+ if (ArrangeCanvas is { } canvas)
+ PlateArrange.ToggleCutCommonLinesTwice(canvas);
+ CutCommonLinesTwiceMenuItem.IsChecked = ArrangeCanvas?.Plate.CutCommonLinesTwice == true;
+ }
+
+ // Joined at the kerf of the plate's cutting parameters, as WinForms.
+ private async Task JoinCommonLineAsync()
+ {
+ if (ActiveView is not { PlateView: { Plate: { } plate } canvas } view)
+ return;
+ var kerf = DesktopSettings.Machines.CuttingParametersFor(plate, view.Tab.Document.Nest).Kerf;
+ if (PlateArrange.JoinCommonLine(canvas, kerf) is { Succeeded: false } result)
+ await ConfirmDialog.ShowAsync(this, "Common Line", result.Failure);
+ }
+
+ private async Task RemoveCommonLineAsync()
+ {
+ if (ArrangeCanvas is { } canvas && PlateArrange.RemoveCommonLines(canvas) == false)
+ await ConfirmDialog.ShowAsync(this, "Common Line", PlateArrange.NoCommonLineNotice);
+ }
+
+ // As the WinForms part menu: Join needs two units to bring together, Remove a grouped part.
+ private void ShowPartMenu(NestView view)
+ {
+ var canvas = view.PlateView;
+ if (view != ActiveView || canvas.Plate == null)
+ return;
+ var (canJoin, canRemove) = PlateArrange.CommonLineCommands(canvas.Plate,
+ PlateArrange.EditableSelection(canvas) ?? Array.Empty());
+ var join = new MenuItem { Header = "Join Common Line", IsEnabled = canJoin };
+ join.Click += async (_, _) => await JoinCommonLineAsync();
+ var remove = new MenuItem { Header = "Remove Common Line", IsEnabled = canRemove };
+ remove.Click += async (_, _) => await RemoveCommonLineAsync();
+ var menu = new ContextMenu { ItemsSource = new List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/OpenNest.Avalonia/MainWindow.axaml.cs b/OpenNest.Avalonia/MainWindow.axaml.cs
index 3c9ccbc0..7938f4db 100644
--- a/OpenNest.Avalonia/MainWindow.axaml.cs
+++ b/OpenNest.Avalonia/MainWindow.axaml.cs
@@ -219,6 +219,7 @@ namespace OpenNest.Avalonia
RestoreViewToggles(view);
view.ViewChanged += (_, _) => { if (view == ActiveView) UpdateStatus(); };
WatchLocationClicks(view);
+ WatchPartMenu(view);
views[tab] = view;
WatchHistory(tab);
notice = null;
diff --git a/OpenNest.Avalonia/OperationProgressDialog.cs b/OpenNest.Avalonia/OperationProgressDialog.cs
new file mode 100644
index 00000000..7f4bad05
--- /dev/null
+++ b/OpenNest.Avalonia/OperationProgressDialog.cs
@@ -0,0 +1,132 @@
+using System;
+using System.Diagnostics;
+using System.Threading;
+using System.Threading.Tasks;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Layout;
+using Avalonia.Threading;
+using OpenNest.Forms;
+
+namespace OpenNest.Avalonia
+{
+ ///
+ /// The small "working" window with a Cancel button for a long synchronous plate command run on
+ /// a worker, as the WinForms OperationProgressForm (rules in ).
+ /// Cancel, Escape and the close box only request cancellation: the window stays open showing
+ /// "Canceling..." until the worker has actually stopped, so the caller never continues while it
+ /// is still running.
+ ///
+ internal sealed class OperationProgressDialog : Window
+ {
+ private readonly Task task;
+ private readonly CancellationTokenSource cts;
+ private readonly Stopwatch stopwatch = Stopwatch.StartNew();
+ private readonly TextBlock statusText;
+ private readonly Button cancelButton;
+ private readonly DispatcherTimer elapsedTimer;
+ private bool finished;
+
+ private OperationProgressDialog(string title, string message, Task task, CancellationTokenSource cts)
+ {
+ this.task = task;
+ this.cts = cts;
+ Title = title;
+ Width = 380;
+ SizeToContent = SizeToContent.Height;
+ CanResize = false;
+ ShowInTaskbar = false;
+ WindowStartupLocation = WindowStartupLocation.CenterOwner;
+
+ statusText = new TextBlock();
+ // IsCancel makes Escape click it; the click only requests cancellation.
+ cancelButton = new Button { Content = "Cancel", IsCancel = true, HorizontalAlignment = HorizontalAlignment.Right };
+ cancelButton.Click += (_, _) => RequestCancel();
+
+ var panel = new StackPanel { Margin = new Thickness(12), Spacing = 8 };
+ panel.Children.Add(new TextBlock { Text = message, TextTrimming = global::Avalonia.Media.TextTrimming.CharacterEllipsis });
+ panel.Children.Add(new ProgressBar { IsIndeterminate = true, Height = 18 });
+ panel.Children.Add(statusText);
+ panel.Children.Add(cancelButton);
+ Content = panel;
+
+ elapsedTimer = new DispatcherTimer { Interval = OperationProgress.StatusInterval };
+ elapsedTimer.Tick += (_, _) => UpdateStatus();
+ UpdateStatus();
+
+ Opened += (_, _) =>
+ {
+ elapsedTimer.Start();
+ cancelButton.Focus();
+ task.ContinueWith(_ => Dispatcher.UIThread.Post(Finish), CancellationToken.None,
+ TaskContinuationOptions.None, TaskScheduler.Default);
+ };
+ Closing += (_, e) =>
+ {
+ if (finished)
+ return;
+ e.Cancel = true;
+ RequestCancel();
+ };
+ Closed += (_, _) => elapsedTimer.Stop();
+ }
+
+ ///
+ /// Runs on a worker and returns its result, rethrowing its
+ /// exception. The caller's window is blocked for up to , as the
+ /// WinForms window blocks; a run still going then shows this window modally over
+ /// , whose Cancel requests cancellation through the token passed to
+ /// . Completes only once the worker has stopped, whether or not it
+ /// honored the request.
+ ///
+ public static async Task RunAsync(Window owner, string title, string message,
+ Func work, TimeSpan? showDelay = null)
+ {
+ ArgumentNullException.ThrowIfNull(work);
+ using var cts = new CancellationTokenSource();
+ var token = cts.Token;
+ var task = Task.Run(() => work(token));
+
+ if (!OperationProgress.FinishesWithin(task, showDelay ?? OperationProgress.DefaultShowDelay))
+ {
+ var dialog = new OperationProgressDialog(title, message, task, cts);
+ if (owner != null)
+ await dialog.ShowDialog(owner);
+ else
+ {
+ var closed = new TaskCompletionSource();
+ dialog.Closed += (_, _) => closed.TrySetResult();
+ dialog.Show();
+ await closed.Task;
+ }
+ }
+
+ // The window closes only after the worker stops. Should it ever return early, stop
+ // the worker and wait for it rather than continue beside it.
+ if (!task.IsCompleted)
+ cts.Cancel();
+ return await task;
+ }
+
+ private void RequestCancel()
+ {
+ if (finished || cts.IsCancellationRequested)
+ return;
+ cts.Cancel();
+ cancelButton.IsEnabled = false;
+ UpdateStatus();
+ }
+
+ private void Finish()
+ {
+ if (finished)
+ return;
+ finished = true;
+ elapsedTimer.Stop();
+ Close();
+ }
+
+ private void UpdateStatus() =>
+ statusText.Text = OperationProgress.StatusText(stopwatch.Elapsed, cts.IsCancellationRequested);
+ }
+}
diff --git a/OpenNest.Desktop.Tests/Forms/OperationProgressTests.cs b/OpenNest.Desktop.Tests/Forms/OperationProgressTests.cs
new file mode 100644
index 00000000..f5822aca
--- /dev/null
+++ b/OpenNest.Desktop.Tests/Forms/OperationProgressTests.cs
@@ -0,0 +1,35 @@
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+using OpenNest.Forms;
+
+namespace OpenNest.Desktop.Tests.Forms;
+
+public class OperationProgressTests
+{
+ [Theory]
+ [InlineData(0, false, "Elapsed 0:00")]
+ [InlineData(65.9, false, "Elapsed 1:05")]
+ [InlineData(3601, true, "Canceling... waiting for the current step to stop (60:01)")]
+ public void Status_text_shows_the_elapsed_minutes_and_seconds(double seconds, bool canceling, string expected) =>
+ Assert.Equal(expected, OperationProgress.StatusText(TimeSpan.FromSeconds(seconds), canceling));
+
+ [Fact]
+ public void A_finished_or_faulted_run_finishes_within_the_delay()
+ {
+ Assert.True(OperationProgress.FinishesWithin(Task.CompletedTask, TimeSpan.Zero));
+ Assert.True(OperationProgress.FinishesWithin(Task.FromException(new InvalidOperationException()), TimeSpan.Zero));
+ }
+
+ [Fact]
+ public void A_run_still_going_does_not_finish_within_the_delay()
+ {
+ using var release = new ManualResetEventSlim();
+ var task = Task.Run(release.Wait);
+
+ Assert.False(OperationProgress.FinishesWithin(task, TimeSpan.FromMilliseconds(20)));
+
+ release.Set();
+ Assert.True(OperationProgress.FinishesWithin(task, TimeSpan.FromSeconds(10)));
+ }
+}
diff --git a/OpenNest.Desktop.Tests/Interaction/PlateArrangeTests.cs b/OpenNest.Desktop.Tests/Interaction/PlateArrangeTests.cs
new file mode 100644
index 00000000..98f3a733
--- /dev/null
+++ b/OpenNest.Desktop.Tests/Interaction/PlateArrangeTests.cs
@@ -0,0 +1,298 @@
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using OpenNest.Desktop.Interaction;
+using OpenNest.Engine.Fill;
+using OpenNest.Geometry;
+
+namespace OpenNest.Desktop.Tests.Interaction;
+
+public class PlateArrangeTests
+{
+ private readonly Plate plate = InteractionFixtures.Plate();
+ private readonly TestToolHost host;
+
+ public PlateArrangeTests()
+ {
+ host = new TestToolHost(plate);
+ }
+
+ private PlateSelection Selection => host.Selection;
+
+ private static void AssertNear(double expected, double actual) =>
+ Assert.True(System.Math.Abs(expected - actual) < 1e-9, $"expected {expected}, was {actual}");
+
+ [Fact]
+ public void Align_left_lines_the_selection_up_with_the_first_selected_part_as_one_step()
+ {
+ var recorder = host.RecordHistory();
+ var fixedPart = plate.Parts[1];
+ var moving = plate.Parts[4];
+ moving.Offset(7, 0);
+ recorder.Reset();
+ Selection.Select(fixedPart);
+ Selection.Select(moving);
+
+ Assert.True(PlateArrange.Align(host, AlignType.Left));
+
+ AssertNear(fixedPart.BoundingBox.Left, moving.BoundingBox.Left);
+ AssertNear(20, fixedPart.BoundingBox.Left);
+ Assert.Equal("Align", recorder.History.UndoLabel);
+ Assert.Equal(1, recorder.History.UndoCount);
+ Assert.True(host.Invalidations > 0);
+ }
+
+ [Theory]
+ [InlineData(AlignType.Right)]
+ [InlineData(AlignType.Top)]
+ [InlineData(AlignType.Bottom)]
+ [InlineData(AlignType.Horizontally)]
+ [InlineData(AlignType.Vertically)]
+ public void Each_alignment_matches_the_core_alignment(AlignType type)
+ {
+ var fixedPart = plate.Parts[1];
+ var moving = plate.Parts[4];
+ moving.Offset(3, 4);
+ Selection.Select(fixedPart);
+ Selection.Select(moving);
+ var expected = new Part(moving.BaseDrawing, moving.Location);
+ switch (type)
+ {
+ case AlignType.Right: Align.Right(fixedPart, expected); break;
+ case AlignType.Top: Align.Top(fixedPart, expected); break;
+ case AlignType.Bottom: Align.Bottom(fixedPart, expected); break;
+ case AlignType.Horizontally: Align.Horizontally(fixedPart, expected); break;
+ case AlignType.Vertically: Align.Vertically(fixedPart, expected); break;
+ }
+
+ Assert.True(PlateArrange.Align(host, type));
+
+ Assert.True(expected.Location.DistanceTo(moving.Location) < 1e-9);
+ Assert.Equal(new[] { "Align" }, host.ChangeLabels);
+ }
+
+ [Fact]
+ public void Evenly_space_horizontally_spreads_the_middle_part_between_the_outer_ones()
+ {
+ var square = plate.Parts[1].BaseDrawing;
+ var a = new Part(square, new Vector(0, 50));
+ var b = new Part(square, new Vector(13, 50));
+ var c = new Part(square, new Vector(40, 50));
+ plate.Parts.Add(a);
+ plate.Parts.Add(b);
+ plate.Parts.Add(c);
+ Selection.Select(a);
+ Selection.Select(b);
+ Selection.Select(c);
+
+ Assert.True(PlateArrange.Align(host, AlignType.EvenlySpaceHorizontally));
+
+ AssertNear(b.BoundingBox.Left - a.BoundingBox.Right, c.BoundingBox.Left - b.BoundingBox.Right);
+ AssertNear(0, a.BoundingBox.Left);
+ AssertNear(40, c.BoundingBox.Left);
+ }
+
+ [Fact]
+ public void Arrange_commands_do_nothing_without_a_selection_or_while_edits_are_locked()
+ {
+ Assert.False(PlateArrange.Align(host, AlignType.Left));
+ Selection.Select(plate.Parts[1]);
+ host.EditsLocked = true;
+
+ Assert.False(PlateArrange.Align(host, AlignType.Left));
+ Assert.False(PlateArrange.CenterParts(host));
+ Assert.Null(PlateArrange.JoinCommonLine(host, 0.05));
+ Assert.Null(PlateArrange.RemoveCommonLines(host));
+ Assert.False(PlateArrange.ToggleCutCommonLinesTwice(host));
+ Assert.Empty(host.ChangeLabels);
+ }
+
+ [Fact]
+ public void Center_parts_centers_every_part_in_the_work_area()
+ {
+ var recorder = host.RecordHistory();
+
+ Assert.True(PlateArrange.CenterParts(host));
+
+ var center = plate.Parts.GetBoundingBox().Center;
+ var work = plate.WorkArea().Center;
+ Assert.True(center.DistanceTo(work) < 1e-9, $"{center} vs {work}");
+ Assert.Equal("Center Parts", recorder.History.UndoLabel);
+
+ // Already centered: the step records nothing.
+ Assert.True(PlateArrange.CenterParts(host));
+ Assert.Equal(1, recorder.History.UndoCount);
+ }
+
+ [Fact]
+ public void Join_common_line_slides_two_parts_one_kerf_apart_and_groups_them()
+ {
+ var recorder = host.RecordHistory();
+ var square = plate.Parts[1].BaseDrawing;
+ var a = new Part(square, new Vector(0, 60));
+ var b = new Part(square, new Vector(10.5, 60));
+ using (var add = recorder.BeginChange("Add"))
+ {
+ add.MarkChanged();
+ plate.Parts.Add(a);
+ plate.Parts.Add(b);
+ add.Complete();
+ }
+ Selection.Select(a);
+ Selection.Select(b);
+ Assert.Equal((true, false), PlateArrange.CommonLineCommands(plate, Selection.Parts));
+
+ var result = PlateArrange.JoinCommonLine(host, 0.05);
+
+ Assert.True(result.Succeeded, result.Failure);
+ Assert.Same(result.Group, plate.CommonLineGroupOf(a));
+ Assert.Same(result.Group, plate.CommonLineGroupOf(b));
+ AssertNear(0.05, System.Math.Abs(b.BoundingBox.Left - a.BoundingBox.Right));
+ Assert.Equal("Join Common Line", recorder.History.UndoLabel);
+ Assert.Equal((false, true), PlateArrange.CommonLineCommands(plate, Selection.Parts));
+ }
+
+ [Fact]
+ public void A_failed_join_moves_nothing_and_records_nothing()
+ {
+ var recorder = host.RecordHistory();
+ Selection.Select(plate.Parts[1]);
+ var before = plate.Parts[1].Location;
+
+ var result = PlateArrange.JoinCommonLine(host, 0.05);
+
+ Assert.False(result.Succeeded);
+ Assert.Equal("Select at least two parts to share a common line.", result.Failure);
+ Assert.Equal(before, plate.Parts[1].Location);
+ Assert.False(recorder.CanUndo);
+ }
+
+ [Fact]
+ public void Remove_common_line_removes_the_selected_parts_group_and_keeps_them_in_place()
+ {
+ var recorder = host.RecordHistory();
+ var member = plate.Parts[2];
+ var location = member.Location;
+ Selection.Select(member);
+ Assert.Equal((false, true), PlateArrange.CommonLineCommands(plate, Selection.Parts));
+
+ Assert.True(PlateArrange.RemoveCommonLines(host));
+
+ Assert.Empty(plate.CommonLines);
+ Assert.Equal(location, member.Location);
+ Assert.Equal("Remove Common Line", recorder.History.UndoLabel);
+ Assert.False(PlateArrange.RemoveCommonLines(host));
+ Assert.Equal(1, recorder.History.UndoCount);
+ }
+
+ [Fact]
+ public void Join_is_offered_for_a_group_and_a_loose_part()
+ {
+ Selection.Select(plate.Parts[2]); // brings its partner
+ Selection.Select(plate.Parts[1]);
+
+ Assert.Equal((true, true), PlateArrange.CommonLineCommands(plate, Selection.Parts));
+ }
+
+ [Fact]
+ public void Cut_common_lines_twice_toggles_as_an_undoable_edit_named_for_the_new_state()
+ {
+ var recorder = host.RecordHistory();
+
+ Assert.True(PlateArrange.ToggleCutCommonLinesTwice(host));
+ Assert.True(plate.CutCommonLinesTwice);
+ Assert.Equal("Cut Common Lines Twice", recorder.History.UndoLabel);
+
+ Assert.True(PlateArrange.ToggleCutCommonLinesTwice(host));
+ Assert.False(plate.CutCommonLinesTwice);
+ Assert.Equal("Cut Common Lines Once", recorder.History.UndoLabel);
+ Assert.False(PlateArrange.SetCutCommonLinesTwice(plate, false, label => host.BeginChange(label)));
+ }
+
+ [Fact]
+ public async Task Expand_spacing_needs_two_parts_and_opens_no_step_without_them()
+ {
+ var outcome = await PlateArrange.ExpandSpacingAsync(plate, new[] { plate.Parts[1] },
+ host.CutOffSettings, label => host.BeginChange(label), work => Task.FromResult(work(default)));
+
+ Assert.Null(outcome);
+ Assert.Empty(host.ChangeLabels);
+ }
+
+ [Fact]
+ public async Task Expand_spacing_pushes_the_selection_apart_as_one_step()
+ {
+ var recorder = host.RecordHistory();
+ var parts = new[] { plate.Parts[1], plate.Parts[4] };
+
+ var outcome = await PlateArrange.ExpandSpacingAsync(plate, parts, host.CutOffSettings,
+ label => host.BeginChange(label), work => Task.Run(() => work(CancellationToken.None)));
+
+ Assert.False(outcome.Result.Canceled);
+ Assert.Equal(parts, outcome.MovedParts);
+ Assert.StartsWith("Expanded spacing to ", outcome.Status);
+ Assert.Equal("Expand Spacing", recorder.History.UndoLabel);
+ }
+
+ [Fact]
+ public async Task A_canceled_expand_moves_nothing_and_records_nothing()
+ {
+ var recorder = host.RecordHistory();
+ var parts = new[] { plate.Parts[1], plate.Parts[4] };
+ var before = parts.Select(p => p.Location).ToList();
+ using var canceled = new CancellationTokenSource();
+ canceled.Cancel();
+
+ var outcome = await PlateArrange.ExpandSpacingAsync(plate, parts, host.CutOffSettings,
+ label => host.BeginChange(label), work => Task.FromResult(work(canceled.Token)));
+
+ Assert.True(outcome.Result.Canceled);
+ Assert.Empty(outcome.MovedParts);
+ Assert.Equal("Expand Spacing canceled - no parts were moved", outcome.Status);
+ Assert.Equal(before, parts.Select(p => p.Location));
+ Assert.False(recorder.CanUndo);
+ }
+
+ [Fact]
+ public async Task Fix_spacing_reports_a_clear_plate_without_recording_a_step()
+ {
+ var recorder = host.RecordHistory();
+ var clear = new Plate(new Size(100, 100));
+ var square = plate.Parts[1].BaseDrawing;
+ clear.Parts.Add(new Part(square, new Vector(10, 10)));
+ clear.Parts.Add(new Part(square, new Vector(40, 10)));
+
+ var outcome = await PlateArrange.FixSpacingAsync(clear, System.Array.Empty(), host.CutOffSettings,
+ label => host.BeginChange(label), PlateArrange.Synchronous(null));
+
+ Assert.Equal(0, outcome.Result.FlaggedPairs);
+ Assert.Empty(outcome.MovedParts);
+ Assert.Equal("No overlapping or too-close parts to fix", outcome.Status);
+ Assert.False(recorder.CanUndo);
+ }
+
+ [Fact]
+ public async Task Fix_spacing_pushes_apart_parts_closer_than_the_part_spacing_as_one_step()
+ {
+ var recorder = host.RecordHistory();
+ var square = plate.Parts[1].BaseDrawing;
+ var a = new Part(square, new Vector(20, 60));
+ var b = new Part(square, new Vector(30.5, 60));
+ using (var add = recorder.BeginChange("Add"))
+ {
+ add.MarkChanged();
+ plate.PartSpacing = 1;
+ plate.Parts.Add(a);
+ plate.Parts.Add(b);
+ add.Complete();
+ }
+
+ var outcome = await PlateArrange.FixSpacingAsync(plate, new[] { a }, host.CutOffSettings,
+ label => host.BeginChange(label), work => Task.Run(() => work(CancellationToken.None)));
+
+ Assert.True(outcome.Result.FlaggedPairs > 0);
+ Assert.NotEmpty(outcome.MovedParts);
+ Assert.StartsWith("Fixed ", outcome.Status);
+ Assert.Equal("Fix Spacing", recorder.History.UndoLabel);
+ }
+}
diff --git a/OpenNest.Desktop/Forms/OperationProgress.cs b/OpenNest.Desktop/Forms/OperationProgress.cs
new file mode 100644
index 00000000..d8f0bd57
--- /dev/null
+++ b/OpenNest.Desktop/Forms/OperationProgress.cs
@@ -0,0 +1,41 @@
+using System;
+using System.Threading.Tasks;
+
+namespace OpenNest.Forms
+{
+ ///
+ /// The rules of the small "working" window both desktop apps show with a Cancel button while
+ /// a long plate command (Expand Spacing, Fix Spacing) runs on a worker: the window appears only
+ /// once the run outlasts , shows the elapsed time, and after
+ /// Cancel says it is waiting for the worker to stop. Cancel, Escape and closing only request
+ /// cancellation; the window closes once the worker has actually stopped.
+ ///
+ public static class OperationProgress
+ {
+ /// Runs that finish within this delay never show the window.
+ public static readonly TimeSpan DefaultShowDelay = TimeSpan.FromMilliseconds(300);
+
+ /// How often the window updates its elapsed time.
+ public static readonly TimeSpan StatusInterval = TimeSpan.FromMilliseconds(500);
+
+ ///
+ /// Waits up to for , blocking the caller as
+ /// the window's owner is blocked; true when it finished, faulted or was canceled in time.
+ ///
+ public static bool FinishesWithin(Task task, TimeSpan delay)
+ {
+ ArgumentNullException.ThrowIfNull(task);
+ // A wait handle, unlike Task.Wait, does not throw for a faulted run.
+ return ((IAsyncResult)task).AsyncWaitHandle.WaitOne(delay);
+ }
+
+ /// "Elapsed 1:05", or after Cancel "Canceling... waiting for the current step to stop (1:05)".
+ public static string StatusText(TimeSpan elapsed, bool canceling)
+ {
+ var time = $"{(int)elapsed.TotalMinutes}:{elapsed.Seconds:00}";
+ return canceling
+ ? $"Canceling... waiting for the current step to stop ({time})"
+ : $"Elapsed {time}";
+ }
+ }
+}
diff --git a/OpenNest.Desktop/Interaction/PlateArrange.cs b/OpenNest.Desktop/Interaction/PlateArrange.cs
new file mode 100644
index 00000000..838cf672
--- /dev/null
+++ b/OpenNest.Desktop/Interaction/PlateArrange.cs
@@ -0,0 +1,369 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using OpenNest.CommonLines;
+using OpenNest.CutOffs;
+using OpenNest.Engine.Fill;
+using OpenNest.Undo;
+
+namespace OpenNest.Desktop.Interaction;
+
+///
+/// The Plate > Arrange commands, toolkit-neutral: align, evenly space and center parts, join
+/// and remove common lines (see docs/common-line-cutting.md), cut them twice, Expand Spacing and
+/// Fix Spacing. Each is one undo step under the WinForms label, opened through
+/// beginChange; the caller redraws the parts it reports moved.
+///
+public static class PlateArrange
+{
+ ///
+ /// Aligns or evenly spaces : an alignment lines them up with
+ /// . False, opening no step, without a selection; an unknown
+ /// records nothing.
+ ///
+ public static bool Align(IReadOnlyList selected, Part fixedPart, AlignType type,
+ Func beginChange)
+ {
+ ArgumentNullException.ThrowIfNull(beginChange);
+ if (selected == null || selected.Count == 0)
+ return false;
+
+ using var change = beginChange("Align");
+ var parts = selected.ToList();
+ switch (type)
+ {
+ case AlignType.Bottom:
+ change.MarkChanged();
+ OpenNest.Align.Bottom(fixedPart, parts);
+ break;
+ case AlignType.Horizontally:
+ change.MarkChanged();
+ OpenNest.Align.Horizontally(fixedPart, parts);
+ break;
+ case AlignType.Left:
+ change.MarkChanged();
+ OpenNest.Align.Left(fixedPart, parts);
+ break;
+ case AlignType.Right:
+ change.MarkChanged();
+ OpenNest.Align.Right(fixedPart, parts);
+ break;
+ case AlignType.Top:
+ change.MarkChanged();
+ OpenNest.Align.Top(fixedPart, parts);
+ break;
+ case AlignType.Vertically:
+ change.MarkChanged();
+ OpenNest.Align.Vertically(fixedPart, parts);
+ break;
+ case AlignType.EvenlySpaceHorizontally:
+ change.MarkChanged();
+ OpenNest.Align.EvenlyDistributeHorizontally(parts);
+ break;
+ case AlignType.EvenlySpaceVertically:
+ change.MarkChanged();
+ OpenNest.Align.EvenlyDistributeVertically(parts);
+ break;
+ default:
+ // An unknown alignment moves nothing; completing records nothing either.
+ change.Complete();
+ return false;
+ }
+
+ change.Complete();
+ return true;
+ }
+
+ ///
+ /// Center Parts: moves every part on the plate so their bounds center in its work area. False,
+ /// opening no step, without a plate or parts; a layout already centered records nothing.
+ ///
+ public static bool CenterParts(Plate plate, Func beginChange)
+ {
+ ArgumentNullException.ThrowIfNull(beginChange);
+ if (plate == null || plate.Parts.Count == 0)
+ return false;
+
+ var offset = plate.OffsetToCenterPartsInWorkArea();
+ using var change = beginChange("Center Parts");
+ if (offset.X != 0 || offset.Y != 0)
+ change.MarkChanged();
+ foreach (var part in plate.Parts)
+ part.Offset(offset);
+ change.Complete();
+ return true;
+ }
+
+ ///
+ /// How far apart facing edges may start and still be joined: a few part spacings, at least
+ /// an inch.
+ ///
+ public static double JoinGap(Plate plate) => System.Math.Max(1.0, 4 * plate.PartSpacing);
+
+ ///
+ /// Join Common Line: slides one apart
+ /// along their facing straight edges and groups them; parts already in a group move with it.
+ /// Nothing changes, and no step is recorded, when the join fails.
+ ///
+ public static CommonLineJoinResult JoinCommonLine(Plate plate, IReadOnlyList selected, double kerf,
+ Func beginChange)
+ {
+ ArgumentNullException.ThrowIfNull(plate);
+ ArgumentNullException.ThrowIfNull(beginChange);
+ using var change = beginChange("Join Common Line");
+ var result = CommonLineJoiner.Join(plate, selected ?? Array.Empty(), kerf, JoinGap(plate));
+ if (!result.Succeeded)
+ return result;
+ change.MarkChanged();
+ change.Complete();
+ return result;
+ }
+
+ /// The notice shown when none of the selected parts is in a common-line group.
+ public const string NoCommonLineNotice = "None of the selected parts share a common line.";
+
+ ///
+ /// Remove Common Line: removes the common-line groups of ; the
+ /// parts stay where they are. False, recording nothing, when none is in a group.
+ ///
+ public static bool RemoveCommonLines(Plate plate, IReadOnlyList selected,
+ Func beginChange)
+ {
+ ArgumentNullException.ThrowIfNull(beginChange);
+ if (plate == null || selected == null)
+ return false;
+ var groups = selected.Select(plate.CommonLineGroupOf).Where(group => group != null).Distinct().ToList();
+ if (groups.Count == 0)
+ return false;
+ using var change = beginChange("Remove Common Line");
+ change.MarkChanged();
+ foreach (var group in groups)
+ plate.CommonLines.Remove(group);
+ change.Complete();
+ return true;
+ }
+
+ ///
+ /// Cut Common Lines Twice: sets as an undoable edit.
+ /// False when nothing changed.
+ ///
+ public static bool SetCutCommonLinesTwice(Plate plate, bool twice, Func beginChange)
+ {
+ ArgumentNullException.ThrowIfNull(beginChange);
+ if (plate == null || plate.CutCommonLinesTwice == twice)
+ return false;
+ using var change = beginChange(twice ? "Cut Common Lines Twice" : "Cut Common Lines Once");
+ change.MarkChanged();
+ plate.CutCommonLinesTwice = twice;
+ change.Complete();
+ return true;
+ }
+
+ ///
+ /// Which common-line commands the part right-click menu enables for :
+ /// Join needs two units to bring together (two loose parts, or a group and anything outside
+ /// it), Remove a part in a group.
+ ///
+ public static (bool CanJoin, bool CanRemove) CommonLineCommands(Plate plate, IReadOnlyList selected)
+ {
+ if (plate == null || selected == null)
+ return (false, false);
+ var groups = selected.Select(plate.CommonLineGroupOf).ToList();
+ var units = groups.Where(g => g != null).Distinct().Count() + groups.Count(g => g == null);
+ return (units >= 2, groups.Any(g => g != null));
+ }
+
+ /// The notice shown when Expand Spacing has fewer than two parts to move.
+ public const string ExpandNeedsTwoPartsNotice = "Select at least two parts on the plate to expand.";
+
+ /// The notice shown when a nest or fill could still add parts to the plate.
+ public static string BusyNotice(string command) =>
+ $"Finish or cancel the current nesting or fill before {command}.";
+
+ ///
+ /// What a spacing command did: whether it ran, the parts it moved (redraw them) and the status
+ /// line to show.
+ ///
+ public sealed record SpacingOutcome(TResult Result, IReadOnlyList MovedParts, string Status);
+
+ ///
+ /// Expand Spacing: pushes apart as far as the plate allows
+ /// (). executes the search, off the UI thread
+ /// behind a Cancel window, and may cancel it; a canceled run moves no part and records
+ /// nothing. Null, opening no step, with fewer than two parts.
+ ///
+ public static async Task> ExpandSpacingAsync(Plate plate,
+ IReadOnlyList selected, CutOffSettings cutOffSettings, Func beginChange,
+ Func, Task> run)
+ {
+ ArgumentNullException.ThrowIfNull(beginChange);
+ ArgumentNullException.ThrowIfNull(run);
+ var movingParts = selected?.ToList() ?? new List();
+ if (plate == null || movingParts.Count < 2)
+ return null;
+
+ Expander.Result Work(CancellationToken token) => Expander.Expand(movingParts, plate, null, token);
+
+ // Opened before the search: it moves the live parts once it finishes.
+ using var change = beginChange("Expand Spacing");
+ var result = await run(Work);
+
+ if (result.Canceled)
+ {
+ change.Complete();
+ return new(result, Array.Empty(), "Expand Spacing canceled - no parts were moved");
+ }
+
+ change.MarkChanged();
+ if (plate.CutOffs.Count > 0)
+ plate.RegenerateCutOffs(cutOffSettings);
+
+ var status = result.KeptPattern
+ ? (result.PatternMoved
+ ? $"Spread the repeating pattern - smallest gap {result.AchievedSpacing:0.###}"
+ : $"The repeating pattern has no room to spread - smallest gap {result.AchievedSpacing:0.###}")
+ : $"Expanded spacing to {result.AchievedSpacing:0.###}"
+ + (result.Violations.Count > 0 ? $" - {result.Violations.Count} blocked pairs" : "");
+
+ change.Complete();
+ return new(result, movingParts, status);
+ }
+
+ ///
+ /// Fix Spacing: pushes apart only the parts the overlap check flags, by just enough to reach
+ /// the part spacing (). With parts selected, only flagged pairs
+ /// touching the selection are fixed. executes the search as for
+ /// ; a canceled run moves no part. Null without a plate.
+ ///
+ public static async Task> FixSpacingAsync(Plate plate,
+ IReadOnlyList selected, CutOffSettings cutOffSettings, Func beginChange,
+ Func, Task> run)
+ {
+ ArgumentNullException.ThrowIfNull(beginChange);
+ ArgumentNullException.ThrowIfNull(run);
+ if (plate == null)
+ return null;
+ var scope = selected?.ToList() ?? new List();
+ SpacingFixer.Result Work(CancellationToken token) => SpacingFixer.Fix(plate, scope, token);
+
+ using var change = beginChange("Fix Spacing");
+ var result = await run(Work);
+ var where = scope.Count > 0 ? " among the selected parts" : "";
+ IReadOnlyList moved = Array.Empty();
+ string status;
+
+ if (result.Canceled)
+ status = "Fix Spacing canceled - no parts were moved";
+ else if (result.FlaggedPairs == 0)
+ status = $"No overlapping or too-close parts{where} to fix";
+ else if (result.MovedParts.Count == 0)
+ status = $"Fix Spacing found no room to clear the {Pairs(result.FlaggedPairs)}{where}";
+ else
+ {
+ change.MarkChanged();
+ moved = result.MovedParts;
+ if (plate.CutOffs.Count > 0)
+ plate.RegenerateCutOffs(cutOffSettings);
+ var fixedPairs = result.FlaggedPairs - result.RemainingPairs;
+ status = $"Fixed {fixedPairs} of {Pairs(result.FlaggedPairs)} - moved {result.MovedParts.Count} "
+ + $"part{(result.MovedParts.Count == 1 ? "" : "s")}, largest move {result.LargestMove:0.####}"
+ + (result.TurnedParts.Count > 0
+ ? $", {result.TurnedParts.Count} tilted up to {OpenNest.Math.Angle.ToDegrees(result.LargestTurn):0.##} deg"
+ : "")
+ + (result.RemainingPairs > 0 ? $" - {Pairs(result.RemainingPairs)} left" : "");
+ }
+
+ change.Complete();
+ return new(result, moved, status);
+
+ static string Pairs(int count) => $"{count} flagged pair{(count == 1 ? "" : "s")}";
+ }
+
+ ///
+ /// The selected parts still on 's plate, in selection order; null
+ /// without a plate or while its edits are locked ().
+ ///
+ public static IReadOnlyList EditableSelection(IPlateToolHost host)
+ {
+ ArgumentNullException.ThrowIfNull(host);
+ if (host.Plate == null || host.EditsLocked)
+ return null;
+ host.Selection.Prune();
+ return host.Selection.Parts.ToList();
+ }
+
+ ///
+ /// on the
+ /// host's selection, lined up with its first selected part.
+ ///
+ public static bool Align(IPlateToolHost host, AlignType type)
+ {
+ if (EditableSelection(host) is not { Count: > 0 } parts)
+ return false;
+ var aligned = Align(parts, parts[0], type, label => host.BeginChange(label));
+ if (aligned)
+ host.Invalidate();
+ return aligned;
+ }
+
+ /// on the host's plate.
+ public static bool CenterParts(IPlateToolHost host)
+ {
+ if (EditableSelection(host) == null)
+ return false;
+ var centered = CenterParts(host.Plate, label => host.BeginChange(label));
+ if (centered)
+ host.Invalidate();
+ return centered;
+ }
+
+ ///
+ ///
+ /// on the host's selection; null while edits are locked.
+ ///
+ public static CommonLineJoinResult JoinCommonLine(IPlateToolHost host, double kerf)
+ {
+ if (EditableSelection(host) is not { } parts)
+ return null;
+ var result = JoinCommonLine(host.Plate, parts, kerf, label => host.BeginChange(label));
+ if (result.Succeeded)
+ host.Invalidate();
+ return result;
+ }
+
+ ///
+ /// on
+ /// the host's selection; null while edits are locked.
+ ///
+ public static bool? RemoveCommonLines(IPlateToolHost host)
+ {
+ if (EditableSelection(host) is not { } parts)
+ return null;
+ var removed = RemoveCommonLines(host.Plate, parts, label => host.BeginChange(label));
+ if (removed)
+ host.Invalidate();
+ return removed;
+ }
+
+ /// Toggles the host plate's .
+ public static bool ToggleCutCommonLinesTwice(IPlateToolHost host)
+ {
+ if (EditableSelection(host) == null)
+ return false;
+ var plate = host.Plate;
+ var changed = SetCutCommonLinesTwice(plate, !plate.CutCommonLinesTwice, label => host.BeginChange(label));
+ if (changed)
+ host.Invalidate();
+ return changed;
+ }
+
+ ///
+ /// Runs a spacing command synchronously, as the WinForms Cancel window does: the task the
+ /// command returns has completed once returns.
+ ///
+ public static Func, Task> Synchronous(
+ Func, T> run) =>
+ work => Task.FromResult(run != null ? run(work) : work(CancellationToken.None));
+}
diff --git a/OpenNest/Controls/PartMenuHandler.cs b/OpenNest/Controls/PartMenuHandler.cs
index cd020642..ea230d96 100644
--- a/OpenNest/Controls/PartMenuHandler.cs
+++ b/OpenNest/Controls/PartMenuHandler.cs
@@ -3,6 +3,7 @@ using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using OpenNest.Actions;
+using OpenNest.Desktop.Interaction;
namespace OpenNest.Controls
{
@@ -54,19 +55,16 @@ namespace OpenNest.Controls
if (part == null || !view.SelectedParts.Contains(part))
return null;
- var selected = view.SelectedParts.Select(p => p.BasePart).ToList();
- var groups = selected.Select(plate.CommonLineGroupOf).ToList();
- // Join needs two units to bring together: two loose parts, or a group and anything outside it.
- var units = groups.Where(g => g != null).Distinct().Count() + groups.Count(g => g == null);
- var anyGrouped = groups.Any(g => g != null);
+ var (canJoin, canRemove) = PlateArrange.CommonLineCommands(plate,
+ view.SelectedParts.Select(p => p.BasePart).ToList());
menu ??= new ContextMenuStrip();
while (menu.Items.Count > 0)
menu.Items[0].Dispose();
if (view.JoinCommonLineCommand is { } join)
- menu.Items.Add("Join Common Line", null, (_, _) => join()).Enabled = units >= 2;
+ menu.Items.Add("Join Common Line", null, (_, _) => join()).Enabled = canJoin;
if (view.RemoveCommonLineCommand is { } remove)
- menu.Items.Add("Remove Common Line", null, (_, _) => remove()).Enabled = anyGrouped;
+ menu.Items.Add("Remove Common Line", null, (_, _) => remove()).Enabled = canRemove;
return menu;
}
diff --git a/OpenNest/Controls/PlateView.cs b/OpenNest/Controls/PlateView.cs
index b838aee6..49ee14c2 100644
--- a/OpenNest/Controls/PlateView.cs
+++ b/OpenNest/Controls/PlateView.cs
@@ -985,33 +985,22 @@ namespace OpenNest.Controls
public CommonLineJoinResult JoinSelectedCommonLine(double kerf)
{
var parts = SelectedParts.Select(p => p.BasePart).ToList();
- // Facing edges up to a few part spacings apart (and at least an inch) are joined.
- var maxGap = System.Math.Max(1.0, 4 * Plate.PartSpacing);
- using var change = BeginChange("Join Common Line");
- var result = CommonLineJoiner.Join(Plate, parts, kerf, maxGap);
+ var result = Desktop.Interaction.PlateArrange.JoinCommonLine(Plate, parts, kerf, label => BeginChange(label));
if (!result.Succeeded)
return result;
- change.MarkChanged();
foreach (var layout in this.parts.Where(p => result.Group.Contains(p.BasePart)))
layout.IsDirty = true;
Invalidate();
- change.Complete();
return result;
}
/// Removes the common-line groups of the selected parts; the parts stay where they are.
public bool RemoveSelectedCommonLines()
{
- var groups = SelectedParts.Select(p => Plate.CommonLineGroupOf(p.BasePart))
- .Where(group => group != null).Distinct().ToList();
- if (groups.Count == 0)
+ if (!Desktop.Interaction.PlateArrange.RemoveCommonLines(Plate, SelectedParts.Select(p => p.BasePart).ToList(),
+ label => BeginChange(label)))
return false;
- using var change = BeginChange("Remove Common Line");
- change.MarkChanged();
- foreach (var group in groups)
- Plate.CommonLines.Remove(group);
Invalidate();
- change.Complete();
return true;
}
@@ -1021,13 +1010,9 @@ namespace OpenNest.Controls
///
public bool SetCutCommonLinesTwice(bool twice)
{
- if (Plate == null || Plate.CutCommonLinesTwice == twice)
+ if (!Desktop.Interaction.PlateArrange.SetCutCommonLinesTwice(Plate, twice, label => BeginChange(label)))
return false;
- using var change = BeginChange(twice ? "Cut Common Lines Twice" : "Cut Common Lines Once");
- change.MarkChanged();
- Plate.CutCommonLinesTwice = twice;
Invalidate();
- change.Complete();
return true;
}
diff --git a/OpenNest/Controls/SelectionManager.cs b/OpenNest/Controls/SelectionManager.cs
index cf924bad..1fc03cea 100644
--- a/OpenNest/Controls/SelectionManager.cs
+++ b/OpenNest/Controls/SelectionManager.cs
@@ -6,6 +6,7 @@ using System.Runtime.CompilerServices;
using System.Threading;
using OpenNest.CNC;
using OpenNest.CutOffs;
+using OpenNest.Desktop.Interaction;
using OpenNest.Engine.Fill;
using OpenNest.Geometry;
@@ -170,56 +171,12 @@ namespace OpenNest.Controls
if (selectedParts.Count == 0)
return;
- using var change = view.BeginChange("Align");
- change.MarkChanged();
- switch (alignType)
- {
- case AlignType.Bottom:
- Align.Bottom(
- fixedPart.BasePart,
- selectedParts.Select(p => p.BasePart).ToList()
- );
- break;
- case AlignType.Horizontally:
- Align.Horizontally(
- fixedPart.BasePart,
- selectedParts.Select(p => p.BasePart).ToList()
- );
- break;
- case AlignType.Left:
- Align.Left(fixedPart.BasePart, selectedParts.Select(p => p.BasePart).ToList());
- break;
- case AlignType.Right:
- Align.Right(fixedPart.BasePart, selectedParts.Select(p => p.BasePart).ToList());
- break;
- case AlignType.Top:
- Align.Top(fixedPart.BasePart, selectedParts.Select(p => p.BasePart).ToList());
- break;
- case AlignType.Vertically:
- Align.Vertically(
- fixedPart.BasePart,
- selectedParts.Select(p => p.BasePart).ToList()
- );
- break;
- case AlignType.EvenlySpaceHorizontally:
- Align.EvenlyDistributeHorizontally(
- selectedParts.Select(p => p.BasePart).ToList()
- );
- break;
- case AlignType.EvenlySpaceVertically:
- Align.EvenlyDistributeVertically(
- selectedParts.Select(p => p.BasePart).ToList()
- );
- break;
- default:
- // An unknown alignment moves nothing; completing records nothing either.
- change.Complete();
- return;
- }
+ var parts = selectedParts.Select(p => p.BasePart).ToList();
+ if (!PlateArrange.Align(parts, fixedPart.BasePart, alignType, label => view.BeginChange(label)))
+ return;
selectedParts.ForEach(p => p.IsDirty = true);
view.Invalidate();
- change.Complete();
}
///
@@ -277,41 +234,18 @@ namespace OpenNest.Controls
Func, Expander.Result> run = null
)
{
- var movingParts = selectedParts.Select(p => p.BasePart).ToList();
-
- if (movingParts.Count < 2)
+ var outcome = PlateArrange.ExpandSpacingAsync(view.Plate, selectedParts.Select(p => p.BasePart).ToList(),
+ view.CutOffSettings, label => view.BeginChange(label), PlateArrange.Synchronous(run))
+ .GetAwaiter().GetResult();
+ if (outcome == null)
return false;
- var plate = view.Plate;
- Expander.Result Work(CancellationToken token) =>
- Expander.Expand(movingParts, plate, null, token);
-
- using var change = view.BeginChange("Expand Spacing");
- var result = run != null ? run(Work) : Work(CancellationToken.None);
-
- if (result.Canceled)
+ if (outcome.MovedParts.Count > 0)
{
- view.Status = "Expand Spacing canceled - no parts were moved";
- change.Complete();
- return true;
+ selectedParts.ForEach(p => p.IsDirty = true);
+ view.Invalidate();
}
-
- change.MarkChanged();
- selectedParts.ForEach(p => p.IsDirty = true);
-
- if (view.Plate.CutOffs.Count > 0)
- view.Plate.RegenerateCutOffs(view.CutOffSettings);
-
- view.Invalidate();
-
- view.Status = result.KeptPattern
- ? (result.PatternMoved
- ? $"Spread the repeating pattern - smallest gap {result.AchievedSpacing:0.###}"
- : $"The repeating pattern has no room to spread - smallest gap {result.AchievedSpacing:0.###}")
- : $"Expanded spacing to {result.AchievedSpacing:0.###}"
- + (result.Violations.Count > 0 ? $" - {result.Violations.Count} blocked pairs" : "");
-
- change.Complete();
+ view.Status = outcome.Status;
return true;
}
@@ -325,42 +259,21 @@ namespace OpenNest.Controls
Func, SpacingFixer.Result> run = null
)
{
- var plate = view.Plate;
- var scope = selectedParts.Select(p => p.BasePart).ToList();
- SpacingFixer.Result Work(CancellationToken token) => SpacingFixer.Fix(plate, scope, token);
-
- using var change = view.BeginChange("Fix Spacing");
- var result = run != null ? run(Work) : Work(CancellationToken.None);
- var where = scope.Count > 0 ? " among the selected parts" : "";
-
- if (result.Canceled)
- view.Status = "Fix Spacing canceled - no parts were moved";
- else if (result.FlaggedPairs == 0)
- view.Status = $"No overlapping or too-close parts{where} to fix";
- else if (result.MovedParts.Count == 0)
- view.Status = $"Fix Spacing found no room to clear the {Pairs(result.FlaggedPairs)}{where}";
- else
+ var outcome = PlateArrange.FixSpacingAsync(view.Plate, selectedParts.Select(p => p.BasePart).ToList(),
+ view.CutOffSettings, label => view.BeginChange(label), PlateArrange.Synchronous(run))
+ .GetAwaiter().GetResult();
+ if (outcome == null)
+ return null;
+ if (outcome.MovedParts.Count > 0)
{
- change.MarkChanged();
+ var moved = new HashSet(outcome.MovedParts);
foreach (var part in view.LayoutParts)
- if (result.MovedParts.Contains(part.BasePart))
+ if (moved.Contains(part.BasePart))
part.IsDirty = true;
- if (plate.CutOffs.Count > 0)
- plate.RegenerateCutOffs(view.CutOffSettings);
view.Invalidate();
- var fixedPairs = result.FlaggedPairs - result.RemainingPairs;
- view.Status = $"Fixed {fixedPairs} of {Pairs(result.FlaggedPairs)} - moved {result.MovedParts.Count} "
- + $"part{(result.MovedParts.Count == 1 ? "" : "s")}, largest move {result.LargestMove:0.####}"
- + (result.TurnedParts.Count > 0
- ? $", {result.TurnedParts.Count} tilted up to {OpenNest.Math.Angle.ToDegrees(result.LargestTurn):0.##} deg"
- : "")
- + (result.RemainingPairs > 0 ? $" - {Pairs(result.RemainingPairs)} left" : "");
}
-
- change.Complete();
- return result;
-
- static string Pairs(int count) => $"{count} flagged pair{(count == 1 ? "" : "s")}";
+ view.Status = outcome.Status;
+ return outcome.Result;
}
public LayoutPart GetPartAtControlPoint(Point pt)
diff --git a/OpenNest/Forms/MainForm.Tools.cs b/OpenNest/Forms/MainForm.Tools.cs
index 46cca508..7ba11393 100644
--- a/OpenNest/Forms/MainForm.Tools.cs
+++ b/OpenNest/Forms/MainForm.Tools.cs
@@ -2,6 +2,7 @@ using System;
using System.Windows.Forms;
using OpenNest.Actions;
using OpenNest.Data;
+using OpenNest.Desktop.Interaction;
using OpenNest.Geometry;
namespace OpenNest.Forms
@@ -53,9 +54,7 @@ namespace OpenNest.Forms
// add parts must finish first.
if (IsExpandSpacingBusy(editForm))
{
- ShowExpandSpacingNotice(
- "Finish or cancel the current nesting or fill before Expand Spacing."
- );
+ ShowExpandSpacingNotice(PlateArrange.BusyNotice("Expand Spacing"));
return;
}
@@ -70,7 +69,7 @@ namespace OpenNest.Forms
);
if (!expanded)
- ShowExpandSpacingNotice("Select at least two parts on the plate to expand.");
+ ShowExpandSpacingNotice(PlateArrange.ExpandNeedsTwoPartsNotice);
}
private void FixSpacing_Click(object sender, EventArgs e)
@@ -82,7 +81,7 @@ namespace OpenNest.Forms
// The search reads the plate on a worker, like Expand Spacing.
if (IsExpandSpacingBusy(editForm))
{
- ShowExpandSpacingNotice("Finish or cancel the current nesting or fill before Fix Spacing.", "Fix Spacing");
+ ShowExpandSpacingNotice(PlateArrange.BusyNotice("Fix Spacing"), "Fix Spacing");
return;
}
@@ -129,7 +128,7 @@ namespace OpenNest.Forms
if (activeForm?.PlateView?.Plate == null)
return;
if (!activeForm.PlateView.RemoveSelectedCommonLines())
- ShowCommonLineNotice("None of the selected parts share a common line.");
+ ShowCommonLineNotice(PlateArrange.NoCommonLineNotice);
}
private void CutCommonLinesTwice_Click(object sender, EventArgs e)
diff --git a/OpenNest/Forms/OperationProgressForm.cs b/OpenNest/Forms/OperationProgressForm.cs
index 11f88b76..fb0a9bec 100644
--- a/OpenNest/Forms/OperationProgressForm.cs
+++ b/OpenNest/Forms/OperationProgressForm.cs
@@ -16,7 +16,7 @@ namespace OpenNest.Forms;
internal sealed class OperationProgressForm : Form
{
/// Runs that finish within this delay never show the window.
- internal static readonly TimeSpan DefaultShowDelay = TimeSpan.FromMilliseconds(300);
+ internal static readonly TimeSpan DefaultShowDelay = OperationProgress.DefaultShowDelay;
private readonly Task task;
private readonly CancellationTokenSource cts;
@@ -78,7 +78,7 @@ internal sealed class OperationProgressForm : Form
CancelButton = cancelButton;
cancelButton.DialogResult = DialogResult.None;
- elapsedTimer = new System.Windows.Forms.Timer { Interval = 500 };
+ elapsedTimer = new System.Windows.Forms.Timer { Interval = (int)OperationProgress.StatusInterval.TotalMilliseconds };
elapsedTimer.Tick += (_, _) => UpdateStatus();
UpdateStatus();
@@ -112,8 +112,7 @@ internal sealed class OperationProgressForm : Form
var token = cts.Token;
var task = Task.Run(() => work(token));
- // A wait handle, unlike Task.Wait, does not throw for a faulted run.
- if (!((IAsyncResult)task).AsyncWaitHandle.WaitOne(showDelay ?? DefaultShowDelay))
+ if (!OperationProgress.FinishesWithin(task, showDelay ?? DefaultShowDelay))
{
using var form = new OperationProgressForm(title, message, task, cts);
form.ShowDialog(owner);
@@ -185,10 +184,6 @@ internal sealed class OperationProgressForm : Form
private void UpdateStatus()
{
- var elapsed = stopwatch.Elapsed;
- var time = $"{(int)elapsed.TotalMinutes}:{elapsed.Seconds:00}";
- statusLabel.Text = cts.IsCancellationRequested
- ? $"Canceling... waiting for the current step to stop ({time})"
- : $"Elapsed {time}";
+ statusLabel.Text = OperationProgress.StatusText(stopwatch.Elapsed, cts.IsCancellationRequested);
}
}