diff --git a/OpenNest.Avalonia/AutomaticCutOffDialog.cs b/OpenNest.Avalonia/AutomaticCutOffDialog.cs new file mode 100644 index 00000000..78c2993d --- /dev/null +++ b/OpenNest.Avalonia/AutomaticCutOffDialog.cs @@ -0,0 +1,390 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Threading.Tasks; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Layout; +using Avalonia.Media; +using OpenNest.Avalonia.Controls; +using OpenNest.Data; +using OpenNest.Forms; +using OpenNest.Undo; + +namespace OpenNest.Avalonia +{ + /// + /// Plate > Automatic Scrap Cutoffs and Nest > Automatic Scrap Cutoffs (All Plates), as the + /// WinForms dialog, over the shared : spacing, minimum + /// strip (half the spacing until edited) and tail, the head-height lock and its overcut; the + /// active plate's detached preview on the sheet, its measurements, a per-plate table for All + /// Plates, the issues and a colored status line. Apply replans every plate and adds the + /// definitions as one "Automatic Scrap Cutoffs" step, then keeps the head-lock choice for new + /// cut-offs; a blocked or empty plan adds nothing and keeps the dialog open. + /// + internal sealed class AutomaticCutOffDialog : Window + { + private static readonly IBrush ReadyBrush = new SolidColorBrush(Color.FromRgb(0, 102, 0)); + private static readonly IBrush BlockedBrush = new SolidColorBrush(Color.FromRgb(192, 0, 0)); + private static readonly IBrush UnchangedBrush = new SolidColorBrush(Color.FromRgb(109, 109, 109)); + private static readonly IBrush WarningBrush = new SolidColorBrush(Color.FromRgb(120, 70, 0)); + + private readonly AutomaticCutOffSession session; + private readonly PlateCanvas canvas; + private readonly Func beginChange; + private readonly TextBox spacing = new() { Name = "Spacing", Width = 110 }; + private readonly TextBox minimumStrip = new() { Name = "MinimumStrip", Width = 110 }; + private readonly TextBox minimumTail = new() { Name = "MinimumTail", Width = 110 }; + private readonly CheckBox headLock = new() { Name = "HeadLock" }; + private readonly TextBox headLockOvercut = new() { Name = "HeadLockOvercut", Width = 110 }; + private readonly TextBlock sheet = new() { TextWrapping = TextWrapping.Wrap }; + private readonly TextBlock status = new() { FontWeight = FontWeight.Bold, FontSize = 15, TextWrapping = TextWrapping.Wrap }; + private readonly TextBlock occupied = Value(); + private readonly TextBlock used = Value(); + private readonly TextBlock separator = Value(); + private readonly TextBlock tail = Value(); + private readonly TextBlock stripCuts = new() { Text = AutomaticCutOffSession.Unmeasured }; + private readonly DataGrid plates = new() + { + Name = "Plates", + IsReadOnly = true, + AutoGenerateColumns = false, + CanUserSortColumns = false, + Height = 150, + HeadersVisibility = DataGridHeadersVisibility.Column, + }; + private readonly TextBox details = new() + { + Name = "Details", + IsReadOnly = true, + AcceptsReturn = true, + TextWrapping = TextWrapping.Wrap, + Height = 110, + }; + private readonly Button apply = new() { Name = "Apply", MinWidth = 90 }; + private bool minimumStripEdited; + private bool settingMinimumStrip; + // The settings last previewed or reset: a box that raises a change without one (as a + // text box can when it is first laid out) keeps the preview. + private string shownSettings; + + /// Whether Apply added cut-offs. + public bool Applied { get; private set; } + + private AutomaticCutOffDialog(AutomaticCutOffSession session, PlateCanvas canvas, + Func beginChange) + { + this.session = session; + this.canvas = canvas; + this.beginChange = beginChange; + Title = session.DialogTitle; + Width = 680; + SizeToContent = SizeToContent.Height; + CanResize = false; + ShowInTaskbar = false; + WindowStartupLocation = WindowStartupLocation.CenterOwner; + + spacing.Text = session.DefaultSpacingText; + minimumStrip.Text = AutomaticCutOffSession.MinimumStripFor(spacing.Text); + minimumTail.Text = session.DefaultMinimumTailText; + headLock.Content = session.HeadLockLabel; + headLock.IsChecked = canvas.CutOffSettings.LockHeadHeight; + ToolTip.SetTip(headLock, "Stock can arrive wider than nominal. New cut-offs cut past the far sheet edge by " + + "this much with the head height locked, and Plan Cutting may start them there. Posting needs the " + + "post's head-height lock codes."); + headLockOvercut.Text = canvas.CutOffSettings.HeadLockOvercut.ToString(CultureInfo.CurrentCulture); + headLockOvercut.IsEnabled = headLock.IsChecked == true; + sheet.Text = session.InitialSheetText; + + spacing.TextChanged += (_, _) => OnSpacingChanged(); + minimumStrip.TextChanged += (_, _) => + { + if (!settingMinimumStrip) + minimumStripEdited = true; + OnSettingsChanged(); + }; + minimumTail.TextChanged += (_, _) => OnSettingsChanged(); + headLockOvercut.TextChanged += (_, _) => OnSettingsChanged(); + headLock.IsCheckedChanged += (_, _) => + { + headLockOvercut.IsEnabled = headLock.IsChecked == true; + OnSettingsChanged(); + }; + + var settings = new Grid + { + ColumnDefinitions = new ColumnDefinitions("*,Auto"), + RowDefinitions = new RowDefinitions("Auto,Auto,Auto,Auto"), + ColumnSpacing = 8, + RowSpacing = 6, + }; + AddSetting(settings, 0, new TextBlock { Text = session.SpacingLabel }, spacing); + AddSetting(settings, 1, new TextBlock { Text = session.MinimumStripLabel }, minimumStrip); + AddSetting(settings, 2, new TextBlock { Text = session.MinimumTailLabel }, minimumTail); + AddSetting(settings, 3, headLock, headLockOvercut); + + var metrics = new Grid + { + ColumnDefinitions = new ColumnDefinitions("*,*,*,*"), + RowDefinitions = new RowDefinitions("Auto,Auto"), + ColumnSpacing = 8, + }; + AddMetric(metrics, 0, "Occupied span", occupied, + "Distance from the sheet origin to the furthest real material."); + AddMetric(metrics, 1, "Used span", used, "Span through the proposed used area, from the sheet origin."); + AddMetric(metrics, 2, "Separator X", separator, + "Signed X of the verified separator cut. A negative value means the separator is on the origin side."); + AddMetric(metrics, 3, "Retained tail", tail, + "Length along X of the reusable tail beyond the verified separator, at full sheet width."); + + var warning = new TextBlock + { + Text = "⚠ Nominal spacing is not the cut-line length — verify scrap separation and hopper fit.", + Foreground = WarningBrush, + TextWrapping = TextWrapping.Wrap, + }; + ToolTip.SetTip(warning, "Nominal spacing differs from cut-line length. Clearances and omitted segments can " + + "leave bridges. Confirm disconnected scrap and hopper fit before relying on it. Tail dimensions " + + "describe a proposed program; verify the physical separation."); + + foreach (var (header, path) in new[] + { + ("Plate", nameof(AutomaticCutOffPlateRow.Plate)), + ("Cut-offs", nameof(AutomaticCutOffPlateRow.CutOffs)), + ("Occupied", nameof(AutomaticCutOffPlateRow.Occupied)), + ("Used", nameof(AutomaticCutOffPlateRow.Used)), + ("Tail", nameof(AutomaticCutOffPlateRow.Tail)), + ("Status", nameof(AutomaticCutOffPlateRow.Status)), + }) + { + plates.Columns.Add(new DataGridTextColumn + { + Header = header, + Binding = new global::Avalonia.Data.Binding(path), + Width = new DataGridLength(1, DataGridLengthUnitType.Star), + }); + } + plates.LoadingRow += (_, e) => + { + if (e.Row.DataContext is AutomaticCutOffPlateRow row) + e.Row.Foreground = BrushOf(row.Tone); + }; + plates.IsVisible = session.AllPlates; + + var preview = new Button { Name = "Preview", Content = "_Preview", MinWidth = 90, IsDefault = true }; + preview.Click += (_, _) => ShowPreview(); + apply.Content = session.ApplyText.Replace('&', '_'); + apply.Click += (_, _) => OnApply(); + var cancel = new Button { Content = "Cancel", IsCancel = true, MinWidth = 90 }; + cancel.Click += (_, _) => Close(); + + Content = new StackPanel + { + Margin = new Thickness(12), + Spacing = 8, + Children = + { + sheet, + settings, + status, + metrics, + stripCuts, + warning, + plates, + new TextBlock { Text = session.DetailsLabel }, + details, + new StackPanel + { + Orientation = Orientation.Horizontal, + HorizontalAlignment = HorizontalAlignment.Right, + Spacing = 8, + Children = { preview, apply, cancel }, + }, + }, + }; + SetStatus("Preparing preview…", null); + Opened += (_, _) => ShowPreview(); + Closed += (_, _) => ClearPreview(); + } + + /// Shows the dialog over ; true when Apply added cut-offs. + public static async Task ShowAsync(Window owner, AutomaticCutOffSession session, PlateCanvas canvas, + Func beginChange) + { + var dialog = new AutomaticCutOffDialog(session, canvas, beginChange); + await dialog.ShowDialog(owner); + return dialog.Applied; + } + + private static TextBlock Value() => new() + { + Text = AutomaticCutOffSession.Unmeasured, + FontWeight = FontWeight.Bold, + }; + + private static void AddSetting(Grid grid, int row, Control label, Control box) + { + label.VerticalAlignment = VerticalAlignment.Center; + Grid.SetRow(label, row); + grid.Children.Add(label); + Grid.SetRow(box, row); + Grid.SetColumn(box, 1); + grid.Children.Add(box); + } + + private static void AddMetric(Grid grid, int column, string caption, TextBlock value, string tip) + { + var label = new TextBlock { Text = caption }; + ToolTip.SetTip(label, tip); + Grid.SetColumn(label, column); + grid.Children.Add(label); + Grid.SetRow(value, 1); + Grid.SetColumn(value, column); + grid.Children.Add(value); + } + + private static IBrush BrushOf(AutomaticCutOffTone tone) => tone switch + { + AutomaticCutOffTone.Ready => ReadyBrush, + AutomaticCutOffTone.Blocked => BlockedBrush, + AutomaticCutOffTone.Unchanged => UnchangedBrush, + _ => null, + }; + + private void SetStatus(string text, IBrush brush) + { + status.Text = text; + if (brush == null) + status.ClearValue(TextBlock.ForegroundProperty); + else + status.Foreground = brush; + } + + private void OnSpacingChanged() + { + if (!minimumStripEdited && AutomaticCutOffSession.MinimumStripFor(spacing.Text) is { } half) + { + settingMinimumStrip = true; + try + { + minimumStrip.Text = half; + } + finally + { + settingMinimumStrip = false; + } + } + OnSettingsChanged(); + } + + private string Settings() => + string.Join("\n", spacing.Text, minimumStrip.Text, minimumTail.Text, headLock.IsChecked, headLockOvercut.Text); + + private void OnSettingsChanged() + { + var settings = Settings(); + if (settings == shownSettings) + return; + shownSettings = settings; + ClearPreview(); + ResetSummary(); + SetStatus(AutomaticCutOffSession.SettingsChangedStatus, null); + details.Text = string.Empty; + apply.IsEnabled = true; + } + + private void ClearPreview() => canvas.CutOffPreviewParts = null; + + private void ResetSummary() + { + foreach (var value in new[] { occupied, used, separator, tail, stripCuts }) + value.Text = AutomaticCutOffSession.Unmeasured; + plates.ItemsSource = null; + } + + private void ShowError(Exception error) + { + ClearPreview(); + ResetSummary(); + apply.IsEnabled = false; + SetStatus($"Error — {error.Message}", BlockedBrush); + details.Text = error.Message; + } + + // Busy and plate checks come before the settings are read, so their message wins. + private (Plate[] Plates, IReadOnlyList Plans) Calculate() + { + session.EnsureReady(); + return session.Calculate(ParseOptions(), WithHeadLock(), apply: false); + } + + private CutOffs.AutomaticCutOffOptions ParseOptions() => + session.ParseOptions(spacing.Text, minimumStrip.Text, minimumTail.Text); + + private CutOffs.CutOffSettings WithHeadLock() => + session.WithHeadLock(canvas.CutOffSettings, headLock.IsChecked == true, headLockOvercut.Text); + + private void Display(Plate[] planned, IReadOnlyList plans) + { + var summary = session.Summarize(planned, plans); + occupied.Text = summary.Occupied; + used.Text = summary.Used; + separator.Text = summary.Separator; + tail.Text = summary.Tail; + stripCuts.Text = summary.StripCuts; + apply.IsEnabled = summary.CanApply; + details.Text = summary.Details; + SetStatus(summary.Status, BrushOf(summary.StatusTone)); + if (!session.AllPlates) + return; + sheet.Text = summary.SheetText; + plates.ItemsSource = summary.Rows; + } + + private void ShowPreview() + { + shownSettings = Settings(); + ClearPreview(); + try + { + var (planned, plans) = Calculate(); + Display(planned, plans); + canvas.CutOffPreviewParts = session.PreviewParts(planned, plans); + } + catch (Exception ex) + { + ShowError(ex); + } + } + + private void OnApply() + { + ClearPreview(); + try + { + // The batch service replans every plate before mutating any; never accept previews. + session.EnsureReady(); + var chosen = WithHeadLock(); + var (planned, plans) = session.Apply(ParseOptions(), chosen, beginChange); + Display(planned, plans); + if (!AutomaticCutOffSession.Applied(plans)) + return; + + // New cut-offs from here on, the manual tool's included, use the choice. + var saved = session.KeepHeadLock(canvas.CutOffSettings, chosen); + UserSettingsFile.Update(UserSettingsFile.DefaultPath, saved.WriteTo); + Applied = true; + Close(); + } + catch (Exception ex) + { + ShowError(ex); + } + finally + { + ClearPreview(); + canvas.InvalidateVisual(); + } + } + } +} diff --git a/OpenNest.Avalonia/Controls/PlateCanvas.CutOffs.cs b/OpenNest.Avalonia/Controls/PlateCanvas.CutOffs.cs new file mode 100644 index 00000000..aad3c80b --- /dev/null +++ b/OpenNest.Avalonia/Controls/PlateCanvas.CutOffs.cs @@ -0,0 +1,180 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Avalonia; +using Avalonia.Input; +using OpenNest.CutOffs; +using OpenNest.Desktop.Interaction; +using OpenNest.Desktop.Rendering; +using OpenNest.Geometry; +using SkiaSharp; + +namespace OpenNest.Avalonia.Controls +{ + /// + /// Plate > Sheet Cut-Off and Trim/Extend Cut-Off, the Swap Through-Cut junction menu and the + /// Automatic Scrap Cutoffs preview, as the WinForms plate view: the tools are the shared + /// and (Space turns a new line, + /// Tab switches its length or the trim mode); dragging a cut-off is the shared Select tool's. + /// + public sealed partial class PlateCanvas + { + // Kept for the view while its nest is open, as WinForms keeps it per plate view. + private readonly CutOffToolOptions cutOffToolOptions = new(); + private IReadOnlyList cutOffPreviewParts = Array.Empty(); + + /// + /// A right click released on a cut-off junction in Select, while the plate takes edits: + /// the host shows Swap Through-Cut. It takes the place of the part menu there. + /// + public event EventHandler CutOffMenuRequested; + + /// Plate > Sheet Cut-Off: starts the tool that adds cut-off lines. + public void StartSheetCutOff() + { + if (plate != null) + tools.SetTool(new SheetCutOffTool(this, cutOffToolOptions)); + } + + /// Plate > Trim/Extend Cut-Off: starts the tool that trims and extends cut-offs. + public void StartTrimExtendCutOff() + { + if (plate != null) + tools.SetTool(new TrimExtendCutOffTool(this)); + } + + /// + /// The Automatic Scrap Cutoffs dialog's detached preview of the shown plate, drawn as + /// preview lines and never added to it; empty for none. + /// + public IReadOnlyList CutOffPreviewParts + { + get => cutOffPreviewParts; + set + { + cutOffPreviewParts = value ?? Array.Empty(); + InvalidateVisual(); + } + } + + private CutOffJunction JunctionMenuAt(Point at) + { + if (plate == null || EditsLocked || tools.Current is not SelectTool) + return null; + var tolerance = view.LengthToWorld(SelectTool.CutOffPickPixels); + return CutOffEdits.JunctionAt(plate, ToWorld(at), tolerance) is var (through, stopper) + ? new CutOffJunction(plate, through, stopper) + : null; + } + + // Space turns a new line; Tab switches its length, or Trim and Extend. Tab is taken + // before focus navigation sees it, as the WinForms view keeps it while these tools run. + private bool HandleCutOffKey(KeyEventArgs e) + { + if (e.KeyModifiers != KeyModifiers.None) + return false; + switch (tools.Current, e.Key) + { + case (SheetCutOffTool sheet, Key.Space): + sheet.ToggleAxis(); + return true; + case (SheetCutOffTool sheet, Key.Tab): + sheet.ToggleFullLength(); + return true; + case (TrimExtendCutOffTool trim, Key.Tab): + trim.ToggleMode(); + return true; + default: + return false; + } + } + + private void BuildCutOffToolOverlays(Scene scene) + { + foreach (var part in cutOffPreviewParts) + scene.CutOffPreviewStrokes.AddRange(CutOff.CutStrokes(part.Program, part.Location)); + switch (tools.Current) + { + case SheetCutOffTool { Preview: { } preview } sheet: + if (preview.Drawing?.Program is { Codes.Count: > 0 } program) + scene.CutOffPreviewStrokes.AddRange(CutOff.CutStrokes(program)); + if (CursorWorld is { } cursor) + { + scene.CutOffTag = sheet.CursorTag; + scene.CutOffTagAnchor = view.WorldToScreen(cursor.X, cursor.Y); + } + break; + case TrimExtendCutOffTool trim: + scene.TrimPieces = trim.PreviewPieces; + break; + } + } + + private sealed partial class Scene + { + public readonly List CutOffPreviewStrokes = new(); + public string CutOffTag; + public ScreenPoint CutOffTagAnchor; + public IReadOnlyList<(Line Line, bool Added)> TrimPieces; + } + + private sealed partial class PlatePainter + { + // The applied cut-off line's orange-red, translucent so it reads as a preview. + private static readonly SKColor CutOffPreviewColor = new(255, 69, 0, 128); + private static readonly SKColor TrimRemovedColor = new(220, 20, 60, 200); + private static readonly SKColor TrimAddedColor = new(34, 139, 34, 200); + private static readonly SKColor TagBack = new(255, 255, 255, 230); + private static readonly SKColor TagBorder = new(105, 105, 105); // DimGray + + private void DrawCutOffToolOverlays() + { + if (scene.CutOffPreviewStrokes.Count > 0) + { + // GDI+'s dash at 1.5 px: three-pixel-and-a-half dashes, one-and-a-half gaps. + using var pen = Stroke(CutOffPreviewColor, 1.5f, new[] { 4.5f, 1.5f }); + foreach (var stroke in scene.CutOffPreviewStrokes) + canvas.DrawLine(Screen(stroke.StartPoint), Screen(stroke.EndPoint), pen); + } + DrawTrimPieces(); + DrawCutOffTag(); + } + + // Dashed red over the piece a trim removes, dashed green over the piece an extend adds. + private void DrawTrimPieces() + { + if (scene.TrimPieces is not { Count: > 0 } pieces) + return; + using var removed = Stroke(TrimRemovedColor, 2, new[] { 6f, 2f }); + using var added = Stroke(TrimAddedColor, 2, new[] { 6f, 2f }); + foreach (var (line, isAdded) in pieces) + canvas.DrawLine(Screen(line.StartPoint), Screen(line.EndPoint), isAdded ? added : removed); + } + + // Beside the cursor, since the status bar is easy to miss: how to turn the line. + private void DrawCutOffTag() + { + if (string.IsNullOrEmpty(scene.CutOffTag)) + return; + using var text = new SKPaint { Color = SKColors.Black, IsAntialias = true, TextSize = 12 }; + var metrics = text.FontMetrics; + var lineHeight = metrics.Descent - metrics.Ascent; + var lines = scene.CutOffTag.Split('\n'); + var width = lines.Max(l => text.MeasureText(l)); + var anchor = scene.CutOffTagAnchor; + var rect = SKRect.Create((float)anchor.X + 16, (float)anchor.Y + 16, width + 6, + lineHeight * lines.Length + 4); + using var back = Fill(TagBack); + canvas.DrawRect(rect, back); + using var border = Stroke(TagBorder); + border.IsAntialias = false; + canvas.DrawRect(rect, border); + for (var i = 0; i < lines.Length; i++) + canvas.DrawText(lines[i], rect.Left + 3, rect.Top + 2 - metrics.Ascent + i * lineHeight, text); + } + } + } + + /// Where two cut-offs meet on : one runs through, the other stops at it. + public sealed record CutOffJunction(Plate Plate, CutOff Through, CutOff Stopper); +} diff --git a/OpenNest.Avalonia/Controls/PlateCanvas.cs b/OpenNest.Avalonia/Controls/PlateCanvas.cs index b8cb4131..caa6a9b1 100644 --- a/OpenNest.Avalonia/Controls/PlateCanvas.cs +++ b/OpenNest.Avalonia/Controls/PlateCanvas.cs @@ -388,6 +388,7 @@ namespace OpenNest.Avalonia.Controls if (options.DrawSupport) BuildSupport(scene); BuildToolOverlays(scene); + BuildCutOffToolOverlays(scene); } // A selected cut-off is drawn solid blue in place of its dashes, as in WinForms. @@ -570,7 +571,10 @@ 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) + // As WinForms: a cut-off junction's menu comes before the part menu. + if (button == ToolButton.Right && JunctionMenuAt(e.GetPosition(this)) is { } junction) + CutOffMenuRequested?.Invoke(this, junction); + else 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. @@ -637,6 +641,10 @@ namespace OpenNest.Avalonia.Controls tools.Escape(); e.Handled = true; } + else if (HandleCutOffKey(e)) + { + e.Handled = true; + } else if (e.Key == Key.F && e.KeyModifiers == KeyModifiers.None) { ZoomToFit(); @@ -864,6 +872,7 @@ namespace OpenNest.Avalonia.Controls DrawCommonLines(); DrawSupport(); DrawSelectionWindow(); + DrawCutOffToolOverlays(); DrawToolOverlays(); } diff --git a/OpenNest.Avalonia/MainWindow.CutOffs.cs b/OpenNest.Avalonia/MainWindow.CutOffs.cs new file mode 100644 index 00000000..d751e88b --- /dev/null +++ b/OpenNest.Avalonia/MainWindow.CutOffs.cs @@ -0,0 +1,82 @@ +using System.Collections.Generic; +using Avalonia.Controls; +using Avalonia.Interactivity; +using OpenNest.Desktop.Interaction; +using OpenNest.Forms; + +namespace OpenNest.Avalonia +{ + /// + /// Plate > Sheet Cut-Off, Trim/Extend Cut-Off and Automatic Scrap Cutoffs, Nest > + /// Automatic Scrap Cutoffs (All Plates) and the Swap Through-Cut menu on a cut-off junction, + /// as the WinForms main form: each edit is one undo step under the WinForms label (see + /// and ). While Auto Nest works + /// on a nest its plate takes none of them. + /// + public partial class MainWindow + { + /// Shows Swap Through-Cut when a junction on 's plate is right-clicked. + private void WatchCutOffMenu(NestView view) => + view.PlateView.CutOffMenuRequested += (_, junction) => ShowCutOffMenu(view, junction); + + private void OnSheetCutOff(object sender, RoutedEventArgs e) => StartTool(canvas => canvas.StartSheetCutOff()); + + private void OnTrimExtendCutOff(object sender, RoutedEventArgs e) => + StartTool(canvas => canvas.StartTrimExtendCutOff()); + + private void ShowCutOffMenu(NestView view, Controls.CutOffJunction junction) + { + var canvas = view.PlateView; + if (view != ActiveView || !ReferenceEquals(canvas.Plate, junction.Plate)) + return; + var swap = new MenuItem { Header = CutOffEdits.SwapLabel }; + swap.Click += (_, _) => + { + // The view may have moved to another sheet, or Auto Nest started, while the menu was open. + if (!ReferenceEquals(junction.Plate, canvas.Plate) || canvas.EditsLocked || view.Tab == nestingTab) + return; + var (_, status) = CutOffEdits.Swap(junction.Plate, junction.Through, junction.Stopper, + canvas.CutOffSettings, label => view.Tab.Undo.BeginChange(label)); + canvas.InvalidateVisual(); + ShowNotice(status); + UpdateUndoMenu(); + }; + var menu = new ContextMenu { ItemsSource = new List { swap } }; + menu.Open(canvas); + } + + private async void OnAutomaticCutOff(object sender, RoutedEventArgs e) => await ShowAutomaticCutOffAsync(allPlates: false); + + private async void OnNestAutomaticCutOff(object sender, RoutedEventArgs e) => await ShowAutomaticCutOffAsync(allPlates: true); + + private async System.Threading.Tasks.Task ShowAutomaticCutOffAsync(bool allPlates) + { + if (ActiveView is not { PlateView: { Plate: { } plate } canvas } view) + return; + var tab = view.Tab; + bool IsBusy() => PlateWorkGuard.IsBusy(tab == nestingTab || arrangingTab == tab, + new[] { canvas.Tools.Current }); + if (IsBusy()) + { + await ConfirmDialog.ShowAsync(this, AutomaticCutOffSession.Title, PlateWorkGuard.BusyMessage); + return; + } + + try + { + // As WinForms, the dialog opens over Select with nothing selected. + canvas.Tools.Select(); + canvas.Selection.Clear(); + var nest = tab.Document.Nest; + var session = new AutomaticCutOffSession(plate, nest.Units, allPlates ? nest : null, + IsBusy, () => canvas.Plate); + await AutomaticCutOffDialog.ShowAsync(this, session, canvas, label => tab.Undo.BeginChange(label)); + } + finally + { + canvas.CutOffPreviewParts = null; + UpdateUndoMenu(); + } + } + } +} diff --git a/OpenNest.Avalonia/MainWindow.axaml b/OpenNest.Avalonia/MainWindow.axaml index 6b6967e5..83406d1a 100644 --- a/OpenNest.Avalonia/MainWindow.axaml +++ b/OpenNest.Avalonia/MainWindow.axaml @@ -51,12 +51,20 @@ + + + + + + + @@ -146,6 +154,8 @@