diff --git a/OpenNest.Avalonia/Controls/PlateCanvas.cs b/OpenNest.Avalonia/Controls/PlateCanvas.cs index 80bd9e72..2380c5c5 100644 --- a/OpenNest.Avalonia/Controls/PlateCanvas.cs +++ b/OpenNest.Avalonia/Controls/PlateCanvas.cs @@ -189,6 +189,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(); @@ -549,6 +563,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 { join, remove } }; + menu.Open(canvas); + } + + private async void OnExpandSpacing(object sender, RoutedEventArgs e) + { + const string title = "Expand Spacing"; + if (!await CanStartSpacingAsync(title)) + return; + var view = ActiveView; + var canvas = view.PlateView; + var parts = PlateArrange.EditableSelection(canvas); + if (parts is not { Count: >= 2 }) + { + await ConfirmDialog.ShowAsync(this, title, PlateArrange.ExpandNeedsTwoPartsNotice); + return; + } + // Complex layouts can search for minutes; run behind a Cancel window. + await RunSpacingAsync(view, title, begin => PlateArrange.ExpandSpacingAsync(canvas.Plate, parts, + canvas.CutOffSettings, begin, work => OperationProgressDialog.RunAsync(this, title, + "Expanding spacing between the selected parts...", work))); + } + + private async void OnFixSpacing(object sender, RoutedEventArgs e) + { + const string title = "Fix Spacing"; + if (!await CanStartSpacingAsync(title)) + return; + var view = ActiveView; + var canvas = view.PlateView; + var parts = PlateArrange.EditableSelection(canvas) ?? Array.Empty(); + await RunSpacingAsync(view, title, begin => PlateArrange.FixSpacingAsync(canvas.Plate, parts, + canvas.CutOffSettings, begin, work => OperationProgressDialog.RunAsync(this, title, + "Pushing apart the overlapping and too-close parts...", work))); + } + + // The search reads the plate on a worker, so a nest that can still add parts must finish first. + private async Task CanStartSpacingAsync(string title) + { + if (ArrangeCanvas == null || arrangingTab != null) + return false; + if (ActiveView.Tab != nestingTab) + return true; + await ConfirmDialog.ShowAsync(this, title, PlateArrange.BusyNotice(title)); + return false; + } + + // Locks the nest's plate while the search runs: the window is modal once shown and the + // caller blocks until then, and the open undo step keeps Undo and Redo off. + private async Task RunSpacingAsync(NestView view, string title, + Func, Task>> command) + { + var canvas = view.PlateView; + var tab = view.Tab; + var locked = canvas.EditsLocked; + arrangingTab = tab; + canvas.EditsLocked = true; + try + { + var outcome = await command(label => tab.Undo.BeginChange(label)); + if (outcome != null) + ShowNotice(outcome.Status); + } + catch (Exception ex) + { + // The open step rolls back whatever the failed run changed. + ShowNotice($"{title} failed: {ex.Message}"); + } + finally + { + canvas.EditsLocked = locked; + arrangingTab = null; + canvas.InvalidateVisual(); + UpdateUndoMenu(); + } + } + } +} diff --git a/OpenNest.Avalonia/MainWindow.axaml b/OpenNest.Avalonia/MainWindow.axaml index d70d4cb0..83de9dd3 100644 --- a/OpenNest.Avalonia/MainWindow.axaml +++ b/OpenNest.Avalonia/MainWindow.axaml @@ -38,6 +38,32 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenNest.Avalonia/MainWindow.axaml.cs b/OpenNest.Avalonia/MainWindow.axaml.cs index 99ab51ad..3371c0d3 100644 --- a/OpenNest.Avalonia/MainWindow.axaml.cs +++ b/OpenNest.Avalonia/MainWindow.axaml.cs @@ -215,6 +215,7 @@ namespace OpenNest.Avalonia view.PlateView.PlacementOrder = ReadClonePlacementOrder; RestoreViewToggles(view); view.ViewChanged += (_, _) => { if (view == ActiveView) UpdateStatus(); }; + 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); + } +}