mirror of
https://github.com/ajisaacs/OpenNest.git
synced 2026-12-01 06:41:42 -05:00
Merge M20 sheet cut-offs into the Avalonia port work
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> # Conflicts: # OpenNest.Avalonia/MainWindow.axaml
This commit is contained in:
commit
2d40e76390
21 files changed
+2157
-259
No files matched your search
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// Plate > Automatic Scrap Cutoffs and Nest > Automatic Scrap Cutoffs (All Plates), as the
|
||||
/// WinForms dialog, over the shared <see cref="AutomaticCutOffSession"/>: 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.
|
||||
/// </summary>
|
||||
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<string, ChangeScope> 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;
|
||||
|
||||
/// <summary>Whether Apply added cut-offs.</summary>
|
||||
public bool Applied { get; private set; }
|
||||
|
||||
private AutomaticCutOffDialog(AutomaticCutOffSession session, PlateCanvas canvas,
|
||||
Func<string, ChangeScope> 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();
|
||||
}
|
||||
|
||||
/// <summary>Shows the dialog over <paramref name="owner"/>; true when Apply added cut-offs.</summary>
|
||||
public static async Task<bool> ShowAsync(Window owner, AutomaticCutOffSession session, PlateCanvas canvas,
|
||||
Func<string, ChangeScope> 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<CutOffs.AutomaticCutOffPlan> 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<CutOffs.AutomaticCutOffPlan> 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// <see cref="SheetCutOffTool"/> and <see cref="TrimExtendCutOffTool"/> (Space turns a new line,
|
||||
/// Tab switches its length or the trim mode); dragging a cut-off is the shared Select tool's.
|
||||
/// </summary>
|
||||
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<Part> cutOffPreviewParts = Array.Empty<Part>();
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public event EventHandler<CutOffJunction> CutOffMenuRequested;
|
||||
|
||||
/// <summary>Plate > Sheet Cut-Off: starts the tool that adds cut-off lines.</summary>
|
||||
public void StartSheetCutOff()
|
||||
{
|
||||
if (plate != null)
|
||||
tools.SetTool(new SheetCutOffTool(this, cutOffToolOptions));
|
||||
}
|
||||
|
||||
/// <summary>Plate > Trim/Extend Cut-Off: starts the tool that trims and extends cut-offs.</summary>
|
||||
public void StartTrimExtendCutOff()
|
||||
{
|
||||
if (plate != null)
|
||||
tools.SetTool(new TrimExtendCutOffTool(this));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Automatic Scrap Cutoffs dialog's detached preview of the shown plate, drawn as
|
||||
/// preview lines and never added to it; empty for none.
|
||||
/// </summary>
|
||||
public IReadOnlyList<Part> CutOffPreviewParts
|
||||
{
|
||||
get => cutOffPreviewParts;
|
||||
set
|
||||
{
|
||||
cutOffPreviewParts = value ?? Array.Empty<Part>();
|
||||
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<Line> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Where two cut-offs meet on <paramref name="Plate"/>: one runs through, the other stops at it.</summary>
|
||||
public sealed record CutOffJunction(Plate Plate, CutOff Through, CutOff Stopper);
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
using System.Collections.Generic;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Interactivity;
|
||||
using OpenNest.Desktop.Interaction;
|
||||
using OpenNest.Forms;
|
||||
|
||||
namespace OpenNest.Avalonia
|
||||
{
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// <see cref="CutOffEdits"/> and <see cref="AutomaticCutOffSession"/>). While Auto Nest works
|
||||
/// on a nest its plate takes none of them.
|
||||
/// </summary>
|
||||
public partial class MainWindow
|
||||
{
|
||||
/// <summary>Shows Swap Through-Cut when a junction on <paramref name="view"/>'s plate is right-clicked.</summary>
|
||||
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<MenuItem> { 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -51,12 +51,20 @@
|
||||
<Separator />
|
||||
<MenuItem x:Name="AutoNestMenuItem" Header="_Auto Nest" Click="OnAutoNest" />
|
||||
<MenuItem x:Name="RemoveEmptyPlatesMenuItem" Header="Remove _Empty Plates" Click="OnRemoveEmptyPlates" />
|
||||
<!-- Cut-offs: MainWindow.CutOffs.cs. -->
|
||||
<MenuItem x:Name="NestAutomaticCutOffMenuItem" Header="Automatic _Scrap Cutoffs (All Plates)..."
|
||||
Click="OnNestAutomaticCutOff" />
|
||||
<Separator />
|
||||
<MenuItem x:Name="ClearNestMenuItem" Header="_Clear Nest..." Click="OnClearNest" />
|
||||
</MenuItem>
|
||||
<MenuItem Header="_Plate">
|
||||
<MenuItem x:Name="EditPlateMenuItem" Header="_Edit" Click="OnEditPlate" />
|
||||
<MenuItem x:Name="SetPlateAsDefaultMenuItem" Header="Set as _Default" Click="OnSetPlateAsDefault" />
|
||||
<Separator />
|
||||
<!-- Cut-offs: MainWindow.CutOffs.cs. -->
|
||||
<MenuItem x:Name="SheetCutOffMenuItem" Header="Sheet _Cut-Off" Click="OnSheetCutOff" />
|
||||
<MenuItem x:Name="TrimExtendCutOffMenuItem" Header="_Trim/Extend Cut-Off" Click="OnTrimExtendCutOff" />
|
||||
<MenuItem x:Name="AutomaticCutOffMenuItem" Header="Automatic Scrap Cut_offs..." Click="OnAutomaticCutOff" />
|
||||
<MenuItem x:Name="RotatePlateMenuItem" Header="_Rotate">
|
||||
<MenuItem Header="90° CW" Click="OnRotatePlateCw" />
|
||||
<MenuItem Header="90° CCW" Click="OnRotatePlateCcw" />
|
||||
@@ -146,6 +154,8 @@
|
||||
<ComboBox x:Name="EngineComboBox" Width="150" VerticalAlignment="Center"
|
||||
SelectionChanged="OnEngineSelectionChanged" />
|
||||
<Button x:Name="AutoNestButton" Content="Auto Nest" Click="OnAutoNest" />
|
||||
<Button x:Name="SheetCutOffButton" Content="Sheet Cut-Off" Margin="8,0,0,0" Click="OnSheetCutOff" />
|
||||
<Button x:Name="TrimExtendCutOffButton" Content="Trim/Extend Cut-Off" Click="OnTrimExtendCutOff" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
|
||||
@@ -222,6 +222,7 @@ namespace OpenNest.Avalonia
|
||||
view.ViewChanged += (_, _) => { if (view == ActiveView) UpdateStatus(); };
|
||||
WatchLocationClicks(view);
|
||||
WatchPartMenu(view);
|
||||
WatchCutOffMenu(view);
|
||||
views[tab] = view;
|
||||
WatchHistory(tab);
|
||||
notice = null;
|
||||
|
||||
@@ -230,10 +230,21 @@ namespace OpenNest.Avalonia
|
||||
// new nest shows Plate 1. Files leave empty plates out, so saving is unchanged. The
|
||||
// tab put it there on opening and the manager keeps it, so this only reads.
|
||||
Canvas.ClearCache();
|
||||
PlateList.ItemsSource = PlateListRow.For(nest.Plates);
|
||||
PlateList.SelectedIndex = nest.Plates.Count > 0
|
||||
? System.Math.Clamp(selectIndex, 0, nest.Plates.Count - 1)
|
||||
: -1;
|
||||
// Rebuilding the list clears its selection for a moment; the view shows the plate
|
||||
// once below, so a tool that does not survive a plate change (Sheet Cut-Off after
|
||||
// its click adds segment parts) is not ended by that passing empty selection.
|
||||
rebuildingPlateList = true;
|
||||
try
|
||||
{
|
||||
PlateList.ItemsSource = PlateListRow.For(nest.Plates);
|
||||
PlateList.SelectedIndex = nest.Plates.Count > 0
|
||||
? System.Math.Clamp(selectIndex, 0, nest.Plates.Count - 1)
|
||||
: -1;
|
||||
}
|
||||
finally
|
||||
{
|
||||
rebuildingPlateList = false;
|
||||
}
|
||||
// As the WinForms list: the selected drawing stays selected when the list is rebuilt,
|
||||
// matched as WinForms matches it (by name), so it survives an Undo's new objects.
|
||||
var selected = (DrawingGrid.SelectedItem as DrawingRow)?.Drawing;
|
||||
@@ -306,7 +317,13 @@ namespace OpenNest.Avalonia
|
||||
|
||||
public void StepPlate(int step) => ShowPlate(PlateList.SelectedIndex + step);
|
||||
|
||||
private void OnPlateSelected(object sender, SelectionChangedEventArgs e) => ShowPlate();
|
||||
private bool rebuildingPlateList;
|
||||
|
||||
private void OnPlateSelected(object sender, SelectionChangedEventArgs e)
|
||||
{
|
||||
if (!rebuildingPlateList)
|
||||
ShowPlate();
|
||||
}
|
||||
|
||||
private void ShowPlate()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using OpenNest.CutOffs;
|
||||
using OpenNest.Desktop.Tests.Interaction;
|
||||
using OpenNest.Forms;
|
||||
using OpenNest.Geometry;
|
||||
using OpenNest.Undo;
|
||||
|
||||
namespace OpenNest.Desktop.Tests.Forms;
|
||||
|
||||
public class AutomaticCutOffSessionTests
|
||||
{
|
||||
// A 120 x 60 sheet with a 20 x 20 part at the origin: room for strip lines and a tail.
|
||||
private static Plate Plate()
|
||||
{
|
||||
var plate = new Plate(new Size(120, 60));
|
||||
plate.Parts.Add(new Part(new Drawing("square", InteractionFixtures.Rect(20, 20)), new Vector(0, 0)));
|
||||
return plate;
|
||||
}
|
||||
|
||||
private static AutomaticCutOffOptions Options(AutomaticCutOffSession session) =>
|
||||
session.ParseOptions(session.DefaultSpacingText, AutomaticCutOffSession.MinimumStripFor(session.DefaultSpacingText),
|
||||
session.DefaultMinimumTailText);
|
||||
|
||||
[Fact]
|
||||
public void Defaults_and_labels_follow_the_units()
|
||||
{
|
||||
var inches = new AutomaticCutOffSession(Plate(), Units.Inches);
|
||||
var metric = new AutomaticCutOffSession(Plate(), Units.Millimeters);
|
||||
|
||||
Assert.Equal("35", inches.DefaultSpacingText);
|
||||
Assert.Equal("889", metric.DefaultSpacingText);
|
||||
Assert.Equal(12.ToString(System.Globalization.CultureInfo.CurrentCulture), inches.DefaultMinimumTailText);
|
||||
Assert.Equal("Minimum strip (mm):", metric.MinimumStripLabel);
|
||||
Assert.Equal((17.5).ToString(System.Globalization.CultureInfo.CurrentCulture),
|
||||
AutomaticCutOffSession.MinimumStripFor("35"));
|
||||
Assert.Null(AutomaticCutOffSession.MinimumStripFor("abc"));
|
||||
Assert.Equal(AutomaticCutOffSession.Title, inches.DialogTitle);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Bad_settings_are_refused_with_the_dialog_message()
|
||||
{
|
||||
var session = new AutomaticCutOffSession(Plate(), Units.Inches);
|
||||
|
||||
var error = Assert.Throws<ArgumentException>(() => session.ParseOptions("x", "1", "1"));
|
||||
Assert.Equal("Enter a numeric spacing in in.", error.Message);
|
||||
var overcut = Assert.Throws<ArgumentException>(() =>
|
||||
session.WithHeadLock(new CutOffSettings(), true, "0"));
|
||||
Assert.Equal("Enter a positive head-locked overcut in in.", overcut.Message);
|
||||
// An unchecked lock keeps the view's overcut whatever is typed.
|
||||
Assert.Equal(new CutOffSettings().HeadLockOvercut,
|
||||
session.WithHeadLock(new CutOffSettings(), false, "junk").HeadLockOvercut);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Preview_changes_nothing_and_Apply_adds_definitions_as_one_step()
|
||||
{
|
||||
var plate = Plate();
|
||||
var nest = new Nest { Name = "test" };
|
||||
nest.Drawings.Add(plate.Parts[0].BaseDrawing);
|
||||
nest.Plates.Add(plate);
|
||||
var recorder = new NestUndoRecorder(new Document { Nest = nest });
|
||||
recorder.Reset();
|
||||
var session = new AutomaticCutOffSession(plate, Units.Inches);
|
||||
var settings = new CutOffSettings();
|
||||
|
||||
var (plates, plans) = session.Calculate(Options(session), settings, apply: false);
|
||||
Assert.Empty(plate.CutOffs);
|
||||
var summary = session.Summarize(plates, plans);
|
||||
Assert.True(summary.CanApply);
|
||||
Assert.Equal(AutomaticCutOffTone.Ready, summary.StatusTone);
|
||||
Assert.StartsWith("Ready — ", summary.Status);
|
||||
Assert.NotEmpty(session.PreviewParts(plates, plans));
|
||||
Assert.Empty(summary.Rows);
|
||||
|
||||
var (_, applied) = session.Apply(Options(session), settings, label => recorder.BeginChange(label));
|
||||
|
||||
Assert.True(AutomaticCutOffSession.Applied(applied));
|
||||
Assert.Equal(applied[0].Definitions.Count, plate.CutOffs.Count);
|
||||
Assert.NotEmpty(plate.CutOffs);
|
||||
Assert.Equal(1, recorder.History.UndoCount);
|
||||
Assert.Equal(AutomaticCutOffSession.Title, recorder.History.UndoLabel);
|
||||
// Preview parts are never accepted: every cut-off part belongs to a definition.
|
||||
Assert.All(plate.Parts.Where(p => p.BaseDrawing.IsCutOff),
|
||||
part => Assert.Contains(plate.CutOffs, c => ReferenceEquals(c.Drawing, part.BaseDrawing)));
|
||||
|
||||
// An unchanged rerun adds nothing and records nothing.
|
||||
var (_, again) = session.Apply(Options(session), settings, label => recorder.BeginChange(label));
|
||||
Assert.False(AutomaticCutOffSession.Applied(again));
|
||||
Assert.Equal(1, recorder.History.UndoCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void An_outlined_sheet_is_refused_and_left_unchanged()
|
||||
{
|
||||
var plate = Plate();
|
||||
plate.Outline = new SheetOutline(new List<Vector>
|
||||
{
|
||||
new(0, 0), new(120, 0), new(120, 60), new(60, 60), new(0, 30),
|
||||
});
|
||||
var nest = new Nest { Name = "test" };
|
||||
nest.Drawings.Add(plate.Parts[0].BaseDrawing);
|
||||
nest.Plates.Add(plate);
|
||||
var recorder = new NestUndoRecorder(new Document { Nest = nest });
|
||||
recorder.Reset();
|
||||
var session = new AutomaticCutOffSession(plate, Units.Inches);
|
||||
|
||||
var error = Assert.ThrowsAny<ArgumentException>(() =>
|
||||
session.Apply(Options(session), new CutOffSettings(), label => recorder.BeginChange(label)));
|
||||
|
||||
Assert.Contains("rectangular sheet", error.Message);
|
||||
Assert.Empty(plate.CutOffs);
|
||||
Assert.Equal(0, recorder.History.UndoCount);
|
||||
Assert.False(recorder.IsChangeInProgress);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_blocked_plan_cannot_be_applied_but_its_settings_can_be_chosen()
|
||||
{
|
||||
var plate = Plate();
|
||||
// A manual cut with other limits right on a proposed strip line blocks the whole plan.
|
||||
var session = new AutomaticCutOffSession(plate, Units.Inches);
|
||||
var (_, open) = session.Calculate(Options(session), new CutOffSettings(), apply: false);
|
||||
var proposed = open[0].Definitions[0];
|
||||
plate.CutOffs.Add(new CutOff(proposed.Position, proposed.Axis) { EndLimit = 10 });
|
||||
plate.RegenerateCutOffs(new CutOffSettings());
|
||||
|
||||
var (plates, plans) = session.Calculate(Options(session), new CutOffSettings(), apply: false);
|
||||
var summary = session.Summarize(plates, plans);
|
||||
|
||||
Assert.False(summary.CanApply);
|
||||
Assert.Equal(AutomaticCutOffTone.Blocked, summary.StatusTone);
|
||||
Assert.Contains("BLOCKING", summary.Details);
|
||||
Assert.Empty(session.PreviewParts(plates, plans));
|
||||
Assert.True(session.Summarize(plates, plans, settingsOnly: true).CanApply);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void All_plates_lists_every_plate_and_marks_the_active_one()
|
||||
{
|
||||
var active = Plate();
|
||||
var empty = new Plate(new Size(120, 60));
|
||||
var nest = new Nest { Name = "test" };
|
||||
nest.Plates.Add(empty);
|
||||
nest.Plates.Add(active);
|
||||
var session = new AutomaticCutOffSession(active, Units.Inches, nest);
|
||||
|
||||
var (plates, plans) = session.Calculate(Options(session), new CutOffSettings(), apply: false);
|
||||
var summary = session.Summarize(plates, plans);
|
||||
|
||||
Assert.Equal(AutomaticCutOffSession.AllPlatesTitle, session.DialogTitle);
|
||||
Assert.Equal(2, summary.Rows.Count);
|
||||
Assert.Equal("1", summary.Rows[0].Plate);
|
||||
Assert.Equal(AutomaticCutOffTone.Unchanged, summary.Rows[0].Tone);
|
||||
Assert.Equal("No change", summary.Rows[0].Status);
|
||||
Assert.Equal("2 (active)", summary.Rows[1].Plate);
|
||||
Assert.Equal("Ready", summary.Rows[1].Status);
|
||||
Assert.StartsWith("All 2 plates — preview shows plate 2", summary.SheetText);
|
||||
Assert.Contains("across 1 of 2 plates", summary.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Planning_refuses_while_busy_or_once_the_view_shows_another_plate()
|
||||
{
|
||||
var plate = Plate();
|
||||
var busy = true;
|
||||
Plate shown = plate;
|
||||
var session = new AutomaticCutOffSession(plate, Units.Inches, isBusy: () => busy, shownPlate: () => shown);
|
||||
|
||||
Assert.Equal(AutomaticCutOffSession.BusyMessage,
|
||||
Assert.Throws<InvalidOperationException>(() => session.EnsureReady()).Message);
|
||||
busy = false;
|
||||
shown = new Plate(new Size(10, 10));
|
||||
Assert.Equal(AutomaticCutOffSession.PlateChangedMessage,
|
||||
Assert.Throws<InvalidOperationException>(() => session.EnsureReady()).Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Keeping_the_head_lock_sets_the_view_and_saves_inches()
|
||||
{
|
||||
var session = new AutomaticCutOffSession(Plate(), Units.Millimeters);
|
||||
var view = new CutOffSettings();
|
||||
var chosen = session.WithHeadLock(view, true, "25.4");
|
||||
|
||||
var saved = session.KeepHeadLock(view, chosen);
|
||||
|
||||
Assert.True(view.LockHeadHeight);
|
||||
Assert.Equal(25.4, view.HeadLockOvercut, 9);
|
||||
Assert.Equal(new SavedCutOffHeadLock(true, 1), saved);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
using System.Linq;
|
||||
using OpenNest.CutOffs;
|
||||
using OpenNest.Desktop.Interaction;
|
||||
using OpenNest.Geometry;
|
||||
using OpenNest.Undo;
|
||||
|
||||
namespace OpenNest.Desktop.Tests.Interaction;
|
||||
|
||||
public class CutOffToolsTests
|
||||
{
|
||||
// An empty 100 x 100 sheet with a full-length vertical cut-off at x = 50.
|
||||
private static Plate EmptyPlate()
|
||||
{
|
||||
var plate = new Plate(new Size(100, 100));
|
||||
plate.CutOffs.Add(new CutOff(new Vector(50, 0), CutOffAxis.Vertical));
|
||||
plate.RegenerateCutOffs(new CutOffSettings());
|
||||
return plate;
|
||||
}
|
||||
|
||||
private static CutOff Horizontal(Plate plate) =>
|
||||
plate.CutOffs.Single(c => c.Axis == CutOffAxis.Horizontal);
|
||||
|
||||
private static CutOff Vertical(Plate plate) =>
|
||||
plate.CutOffs.Single(c => c.Axis == CutOffAxis.Vertical);
|
||||
|
||||
[Fact]
|
||||
public void New_cut_off_stops_at_the_first_crossing_unless_full_length()
|
||||
{
|
||||
var plate = EmptyPlate();
|
||||
var settings = new CutOffSettings();
|
||||
|
||||
var (stopped, _) = CutOffEdits.NewCutOff(plate, new Vector(80, 30), CutOffAxis.Horizontal, false, settings);
|
||||
var (full, _) = CutOffEdits.NewCutOff(plate, new Vector(80, 30), CutOffAxis.Horizontal, true, settings);
|
||||
|
||||
Assert.Equal(50, stopped.EndLimit!.Value, 9);
|
||||
Assert.Null(stopped.StartLimit);
|
||||
Assert.Null(full.EndLimit);
|
||||
Assert.Null(full.StartLimit);
|
||||
// Neither is on the plate until a click adds it.
|
||||
Assert.Single(plate.CutOffs);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void New_cut_off_takes_the_head_locked_overcut()
|
||||
{
|
||||
var plate = EmptyPlate();
|
||||
var settings = new CutOffSettings { LockHeadHeight = true, HeadLockOvercut = 1.5 };
|
||||
|
||||
var (cutOff, _) = CutOffEdits.NewCutOff(plate, new Vector(20, 30), CutOffAxis.Vertical, true, settings);
|
||||
|
||||
Assert.Equal(1.5, cutOff.HeadLockOvercut);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sheet_cut_off_click_adds_one_Add_Cut_Off_step()
|
||||
{
|
||||
var plate = EmptyPlate();
|
||||
var host = new TestToolHost(plate);
|
||||
var recorder = host.RecordHistory();
|
||||
var tool = new SheetCutOffTool(host, new CutOffToolOptions());
|
||||
host.Tools.SetTool(tool);
|
||||
|
||||
tool.PointerMoved(host.At(20, 40, ToolButton.None));
|
||||
Assert.NotNull(tool.Preview);
|
||||
host.Click(20, 40);
|
||||
|
||||
Assert.Equal(2, plate.CutOffs.Count);
|
||||
var added = plate.CutOffs[1];
|
||||
Assert.Equal(CutOffAxis.Vertical, added.Axis);
|
||||
Assert.Equal(20, added.Position.X, 9);
|
||||
Assert.Equal(1, recorder.History.UndoCount);
|
||||
Assert.Equal(CutOffEdits.AddLabel, recorder.History.UndoLabel);
|
||||
// The new line's segments are parts on the plate.
|
||||
Assert.NotEmpty(CutOffSegments.Of(plate, added));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Space_turns_the_line_and_Tab_keeps_full_length_for_the_view()
|
||||
{
|
||||
var plate = EmptyPlate();
|
||||
var host = new TestToolHost(plate);
|
||||
var options = new CutOffToolOptions();
|
||||
var tool = new SheetCutOffTool(host, options);
|
||||
host.Tools.SetTool(tool);
|
||||
Assert.StartsWith("Sheet Cut-Off: click to add a vertical line stopped at the first crossing", host.Tools.Status);
|
||||
|
||||
tool.ToggleAxis();
|
||||
Assert.Equal(CutOffAxis.Horizontal, tool.Axis);
|
||||
Assert.Contains("Space: turn vertical", tool.CursorTag);
|
||||
host.Click(80, 30);
|
||||
Assert.Equal(50, Horizontal(plate).EndLimit!.Value, 9);
|
||||
|
||||
tool.ToggleFullLength();
|
||||
Assert.True(options.FullLengthNewLines);
|
||||
Assert.StartsWith("Sheet Cut-Off: click to add a full-length horizontal line", host.Tools.Status);
|
||||
// A new tool for the same view keeps the choice.
|
||||
Assert.True(new SheetCutOffTool(host, options).FullLength);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sheet_cut_off_adds_nothing_while_edits_are_locked()
|
||||
{
|
||||
var plate = EmptyPlate();
|
||||
var host = new TestToolHost(plate) { EditsLocked = true };
|
||||
var tool = new SheetCutOffTool(host, new CutOffToolOptions());
|
||||
host.Tools.SetTool(tool);
|
||||
|
||||
host.Click(20, 40);
|
||||
|
||||
Assert.Single(plate.CutOffs);
|
||||
Assert.Empty(host.ChangeLabels);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Escape_ends_the_sheet_cut_off_tool()
|
||||
{
|
||||
var host = new TestToolHost(EmptyPlate());
|
||||
host.Tools.SetTool(new SheetCutOffTool(host, new CutOffToolOptions()));
|
||||
|
||||
host.Tools.Escape();
|
||||
|
||||
Assert.IsType<SelectTool>(host.Tools.Current);
|
||||
}
|
||||
|
||||
// A full-length horizontal line at y = 30 across the vertical at x = 50.
|
||||
private static Plate CrossedPlate()
|
||||
{
|
||||
var plate = EmptyPlate();
|
||||
plate.CutOffs.Add(new CutOff(new Vector(0, 30), CutOffAxis.Horizontal));
|
||||
plate.RegenerateCutOffs(new CutOffSettings());
|
||||
return plate;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Trim_removes_the_clicked_piece_as_one_Trim_Cut_Off_step()
|
||||
{
|
||||
var plate = CrossedPlate();
|
||||
var host = new TestToolHost(plate);
|
||||
var recorder = host.RecordHistory();
|
||||
var tool = new TrimExtendCutOffTool(host);
|
||||
host.Tools.SetTool(tool);
|
||||
|
||||
tool.PointerMoved(host.At(50, 70, ToolButton.None));
|
||||
Assert.NotNull(tool.Preview);
|
||||
Assert.Contains(tool.PreviewPieces, piece => !piece.Added);
|
||||
host.Click(50, 70);
|
||||
|
||||
Assert.Equal(30, Vertical(plate).EndLimit!.Value, 9);
|
||||
Assert.Equal(CutOffEdits.TrimLabel, recorder.History.UndoLabel);
|
||||
Assert.Equal(1, recorder.History.UndoCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Tab_switches_to_Extend_which_runs_the_end_back_to_the_edge()
|
||||
{
|
||||
var plate = CrossedPlate();
|
||||
Vertical(plate).EndLimit = 30;
|
||||
plate.RegenerateCutOffs(new CutOffSettings());
|
||||
var host = new TestToolHost(plate);
|
||||
var recorder = host.RecordHistory();
|
||||
var tool = new TrimExtendCutOffTool(host);
|
||||
host.Tools.SetTool(tool);
|
||||
|
||||
tool.PointerMoved(host.At(50, 25, ToolButton.None));
|
||||
tool.ToggleMode();
|
||||
Assert.True(tool.Extending);
|
||||
Assert.Contains("Tab switches to Trim", host.Tools.Status);
|
||||
host.Click(50, 25);
|
||||
|
||||
Assert.Null(Vertical(plate).EndLimit);
|
||||
Assert.Equal(CutOffEdits.ExtendLabel, recorder.History.UndoLabel);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_refused_trim_changes_nothing_and_says_why()
|
||||
{
|
||||
var plate = EmptyPlate();
|
||||
var host = new TestToolHost(plate);
|
||||
var recorder = host.RecordHistory();
|
||||
var tool = new TrimExtendCutOffTool(host);
|
||||
host.Tools.SetTool(tool);
|
||||
|
||||
host.Click(50, 70);
|
||||
|
||||
Assert.Null(Vertical(plate).EndLimit);
|
||||
Assert.Equal(0, recorder.History.UndoCount);
|
||||
Assert.Equal(CutOffTrim.NothingToTrimTo, tool.Hint);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Swap_through_cut_makes_the_stopped_line_run_through()
|
||||
{
|
||||
var plate = EmptyPlate();
|
||||
var settings = new CutOffSettings();
|
||||
var (horizontal, _) = CutOffEdits.NewCutOff(plate, new Vector(10, 30), CutOffAxis.Horizontal, false, settings);
|
||||
CutOffEdits.Add(plate, horizontal, settings, _ => ChangeScope.Detached());
|
||||
var host = new TestToolHost(plate);
|
||||
var recorder = host.RecordHistory();
|
||||
|
||||
var junction = CutOffEdits.JunctionAt(plate, new Vector(50, 30), 0.5);
|
||||
Assert.NotNull(junction);
|
||||
Assert.Same(Vertical(plate), junction.Value.Through);
|
||||
var (applied, status) = CutOffEdits.Swap(plate, junction.Value.Through, junction.Value.Stopper, settings,
|
||||
label => host.BeginChange(label));
|
||||
|
||||
Assert.True(applied);
|
||||
Assert.Equal(CutOffEdits.SwappedStatus, status);
|
||||
Assert.Null(Horizontal(plate).EndLimit);
|
||||
Assert.Equal(30, Vertical(plate).EndLimit!.Value, 9);
|
||||
Assert.Equal(CutOffEdits.SwapLabel, recorder.History.UndoLabel);
|
||||
Assert.Null(CutOffEdits.JunctionAt(plate, new Vector(20, 70), 0.5));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dragging_a_cut_off_in_Select_moves_it_and_its_joined_line_as_one_step()
|
||||
{
|
||||
var plate = EmptyPlate();
|
||||
var settings = new CutOffSettings();
|
||||
var (horizontal, _) = CutOffEdits.NewCutOff(plate, new Vector(10, 30), CutOffAxis.Horizontal, false, settings);
|
||||
CutOffEdits.Add(plate, horizontal, settings, _ => ChangeScope.Detached());
|
||||
var host = new TestToolHost(plate);
|
||||
var recorder = host.RecordHistory();
|
||||
var select = Assert.IsType<SelectTool>(host.Tools.Current);
|
||||
|
||||
select.PointerPressed(host.At(50, 70));
|
||||
Assert.True(select.IsDraggingCutOff);
|
||||
select.PointerMoved(host.At(55, 72));
|
||||
select.PointerMoved(host.At(60, 75));
|
||||
select.PointerReleased(host.At(60, 75));
|
||||
|
||||
Assert.False(select.IsDraggingCutOff);
|
||||
Assert.Equal(60, Vertical(plate).Position.X, 9);
|
||||
// The horizontal line stopped on it follows.
|
||||
Assert.Equal(60, Horizontal(plate).EndLimit!.Value, 9);
|
||||
Assert.Equal(1, recorder.History.UndoCount);
|
||||
Assert.Equal(CutOffEdits.MoveLabel, recorder.History.UndoLabel);
|
||||
Assert.Equal(new[] { Vertical(plate) }, host.Selection.CutOffs);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_click_on_a_cut_off_selects_it_and_records_nothing()
|
||||
{
|
||||
var plate = EmptyPlate();
|
||||
var host = new TestToolHost(plate);
|
||||
var recorder = host.RecordHistory();
|
||||
|
||||
host.Click(50, 70);
|
||||
|
||||
Assert.Equal(new[] { Vertical(plate) }, host.Selection.CutOffs);
|
||||
Assert.Equal(0, recorder.History.UndoCount);
|
||||
Assert.False(recorder.HasUnrecordedChange);
|
||||
Assert.False(recorder.IsChangeInProgress);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Cancelling_mid_drag_keeps_the_partial_cut_off_move()
|
||||
{
|
||||
var plate = EmptyPlate();
|
||||
var host = new TestToolHost(plate);
|
||||
var recorder = host.RecordHistory();
|
||||
var select = host.Tools.Current;
|
||||
|
||||
select.PointerPressed(host.At(50, 70));
|
||||
select.PointerMoved(host.At(40, 70));
|
||||
select.Cancel();
|
||||
|
||||
Assert.Equal(40, Vertical(plate).Position.X, 9);
|
||||
Assert.Equal(1, recorder.History.UndoCount);
|
||||
Assert.False(recorder.IsChangeInProgress);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using OpenNest.CutOffs;
|
||||
using OpenNest.Desktop;
|
||||
using OpenNest.Undo;
|
||||
|
||||
namespace OpenNest.Forms;
|
||||
|
||||
/// <summary>How a status line or plate row of the automatic cut-off dialog is colored.</summary>
|
||||
public enum AutomaticCutOffTone
|
||||
{
|
||||
/// <summary>Ordinary text.</summary>
|
||||
Neutral,
|
||||
|
||||
/// <summary>Dark green: the plan is ready to apply.</summary>
|
||||
Ready,
|
||||
|
||||
/// <summary>Dark red: blocked, or an error.</summary>
|
||||
Blocked,
|
||||
|
||||
/// <summary>Gray: a plate the plan leaves unchanged.</summary>
|
||||
Unchanged,
|
||||
}
|
||||
|
||||
/// <summary>One plate's row in the All Plates table.</summary>
|
||||
public sealed record AutomaticCutOffPlateRow(string Plate, string CutOffs, string Occupied, string Used,
|
||||
string Tail, string Status, AutomaticCutOffTone Tone);
|
||||
|
||||
/// <summary>What the dialog shows for a planned batch: the active plate's measurements, the
|
||||
/// details text, the status line and, for All Plates, the table.</summary>
|
||||
public sealed record AutomaticCutOffSummary(
|
||||
string Occupied,
|
||||
string Used,
|
||||
string Separator,
|
||||
string Tail,
|
||||
string StripCuts,
|
||||
string Details,
|
||||
string Status,
|
||||
AutomaticCutOffTone StatusTone,
|
||||
bool CanApply,
|
||||
string SheetText,
|
||||
IReadOnlyList<AutomaticCutOffPlateRow> Rows);
|
||||
|
||||
/// <summary>
|
||||
/// The WinForms Automatic Scrap Cutoffs dialog's logic, toolkit-neutral (Plate > Automatic
|
||||
/// Scrap Cutoffs for the active plate, Nest > Automatic Scrap Cutoffs (All Plates) for every
|
||||
/// plate): the unit-aware defaults and labels, parsing the settings, planning through
|
||||
/// <see cref="AutomaticCutOffBatch"/>, the texts the dialog shows, and Apply as one "Automatic
|
||||
/// Scrap Cutoffs" undo step. The batch replans every plate before mutating any, refuses a
|
||||
/// blocked batch and rolls back on failure; previews are detached and never accepted. Automatic
|
||||
/// cut-offs refuse an outlined sheet (the planner's blocking diagnostic).
|
||||
/// </summary>
|
||||
public sealed class AutomaticCutOffSession
|
||||
{
|
||||
public const string Title = "Automatic Scrap Cutoffs";
|
||||
public const string AllPlatesTitle = "Automatic Scrap Cutoffs — All Plates";
|
||||
public const string SettingsTitle = "Automatic Scrap Cut-offs — Settings for Plan Cutting";
|
||||
public const string BusyMessage = "Wait for the current nesting or plate action to finish before creating cut-offs.";
|
||||
public const string PlateChangedMessage = "The active plate changed. Close this dialog and try again.";
|
||||
public const string PlateRemovedMessage = "The active plate is no longer in this nest. Close this dialog and try again.";
|
||||
public const string SettingsChangedStatus = "Settings changed — press Preview.";
|
||||
public const string NoIssues = "No issues detected.";
|
||||
public const string Unmeasured = "—";
|
||||
|
||||
private readonly Func<bool> isBusy;
|
||||
private readonly Func<Plate> shownPlate;
|
||||
|
||||
/// <param name="plate">The active plate: the one previewed on the sheet.</param>
|
||||
/// <param name="units">The nest's units, for defaults and labels.</param>
|
||||
/// <param name="nest">For All Plates, the nest whose every plate is planned; null for the active plate alone.</param>
|
||||
/// <param name="isBusy">True while a nesting job or plate action forbids planning; null for never.</param>
|
||||
/// <param name="shownPlate">The plate the view shows now (null once it is gone); null to skip the check.</param>
|
||||
public AutomaticCutOffSession(Plate plate, Units units, Nest nest = null, Func<bool> isBusy = null,
|
||||
Func<Plate> shownPlate = null)
|
||||
{
|
||||
Plate = plate ?? throw new ArgumentException("An active plate is required.", nameof(plate));
|
||||
Units = units;
|
||||
Nest = nest;
|
||||
Unit = UnitsHelper.GetShortString(units);
|
||||
this.isBusy = isBusy;
|
||||
this.shownPlate = shownPlate;
|
||||
}
|
||||
|
||||
public Plate Plate { get; }
|
||||
|
||||
public Units Units { get; }
|
||||
|
||||
/// <summary>The nest for All Plates, or null.</summary>
|
||||
public Nest Nest { get; }
|
||||
|
||||
public bool AllPlates => Nest != null;
|
||||
|
||||
/// <summary>The short unit name, "in" or "mm".</summary>
|
||||
public string Unit { get; }
|
||||
|
||||
public string DialogTitle => AllPlates ? AllPlatesTitle : Title;
|
||||
|
||||
public string ApplyText => AllPlates ? "&Apply to All Plates" : "&Apply";
|
||||
|
||||
public string SpacingLabel => $"Nominal spacing along sheet length ({Unit}):";
|
||||
|
||||
public string MinimumStripLabel => $"Minimum strip ({Unit}):";
|
||||
|
||||
public string MinimumTailLabel => $"Minimum tail to keep ({Unit}):";
|
||||
|
||||
public string HeadLockLabel => $"Lock head height and overcut the far edge by ({Unit}):";
|
||||
|
||||
public string DetailsLabel => AllPlates
|
||||
? "Details — issues and notices (the table above lists every plate):"
|
||||
: "Details — issues and notices:";
|
||||
|
||||
/// <summary>The sheet line before the first preview.</summary>
|
||||
public string InitialSheetText => AllPlates
|
||||
? $"All {Nest.Plates.Count} plates — active sheet shown below"
|
||||
: $"Sheet: {Measure(Plate.Size.Length)} length × {Measure(Plate.Size.Width)} width";
|
||||
|
||||
/// <summary>35 in, or 889 mm.</summary>
|
||||
public string DefaultSpacingText => Units == Units.Millimeters ? "889" : "35";
|
||||
|
||||
/// <summary>12 in, or 304.8 mm.</summary>
|
||||
public string DefaultMinimumTailText =>
|
||||
(Units == Units.Millimeters ? 304.8 : 12).ToString(CultureInfo.CurrentCulture);
|
||||
|
||||
/// <summary>
|
||||
/// The minimum strip that follows a spacing typed as <paramref name="spacingText"/> until the
|
||||
/// user edits the minimum strip: half the spacing; null when it is not a finite number.
|
||||
/// </summary>
|
||||
public static string MinimumStripFor(string spacingText) =>
|
||||
double.TryParse(spacingText, NumberStyles.Float, CultureInfo.CurrentCulture, out var spacing)
|
||||
&& double.IsFinite(spacing)
|
||||
? (spacing / 2).ToString(CultureInfo.CurrentCulture)
|
||||
: null;
|
||||
|
||||
public string Measure(double value) => $"{value:0.####} {Unit}";
|
||||
|
||||
public string SignedPosition(double value) => $"{value:+0.####;-0.####;0} {Unit}";
|
||||
|
||||
/// <summary>The settings typed in the dialog; throws <see cref="ArgumentException"/> with the dialog's message.</summary>
|
||||
public AutomaticCutOffOptions ParseOptions(string spacingText, string minimumStripText, string minimumTailText)
|
||||
{
|
||||
if (!double.TryParse(spacingText, NumberStyles.Float, CultureInfo.CurrentCulture, out var spacing))
|
||||
throw new ArgumentException($"Enter a numeric spacing in {Unit}.");
|
||||
if (!double.TryParse(minimumStripText, NumberStyles.Float, CultureInfo.CurrentCulture, out var minimumStrip))
|
||||
throw new ArgumentException($"Enter a numeric minimum strip in {Unit}.");
|
||||
if (!double.TryParse(minimumTailText, NumberStyles.Float, CultureInfo.CurrentCulture, out var minimumTail))
|
||||
throw new ArgumentException($"Enter a numeric minimum tail length in {Unit}.");
|
||||
|
||||
return new AutomaticCutOffOptions
|
||||
{
|
||||
Spacing = spacing,
|
||||
MinimumStripLength = minimumStrip,
|
||||
MinimumTailLength = minimumTail,
|
||||
KeepHorizontalRemnant = true,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A copy of <paramref name="current"/> (the view's settings, which it keeps until Apply) with
|
||||
/// the dialog's head-lock choice; a checked lock needs a positive overcut.
|
||||
/// </summary>
|
||||
public CutOffSettings WithHeadLock(CutOffSettings current, bool lockHeadHeight, string overcutText)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(current);
|
||||
var overcut = current.HeadLockOvercut;
|
||||
if (lockHeadHeight && (!double.TryParse(overcutText, NumberStyles.Float, CultureInfo.CurrentCulture,
|
||||
out overcut) || !double.IsFinite(overcut) || overcut <= 0))
|
||||
throw new ArgumentException($"Enter a positive head-locked overcut in {Unit}.");
|
||||
return new CutOffSettings
|
||||
{
|
||||
PartClearance = current.PartClearance,
|
||||
Overtravel = current.Overtravel,
|
||||
MinSegmentLength = current.MinSegmentLength,
|
||||
CutDirection = current.CutDirection,
|
||||
LockHeadHeight = lockHeadHeight,
|
||||
HeadLockOvercut = overcut,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Keeps the chosen head lock for new cut-offs from here on (the manual tool's and Plan
|
||||
/// Cutting's too): sets it on the view's <paramref name="viewSettings"/> and returns what to
|
||||
/// save between sessions.
|
||||
/// </summary>
|
||||
public SavedCutOffHeadLock KeepHeadLock(CutOffSettings viewSettings, CutOffSettings chosen)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(viewSettings);
|
||||
ArgumentNullException.ThrowIfNull(chosen);
|
||||
viewSettings.LockHeadHeight = chosen.LockHeadHeight;
|
||||
viewSettings.HeadLockOvercut = chosen.HeadLockOvercut;
|
||||
return SavedCutOffHeadLock.From(chosen.LockHeadHeight, chosen.HeadLockOvercut, Units);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Plans every plate in scope (with <paramref name="apply"/>, adds the definitions through
|
||||
/// <see cref="AutomaticCutOffBatch.Apply"/>). Throws <see cref="InvalidOperationException"/>
|
||||
/// while busy or once the view shows another plate.
|
||||
/// </summary>
|
||||
public (Plate[] Plates, IReadOnlyList<AutomaticCutOffPlan> Plans) Calculate(AutomaticCutOffOptions options,
|
||||
CutOffSettings settings, bool apply)
|
||||
{
|
||||
var plates = EnsureReady();
|
||||
var plans = apply
|
||||
? AutomaticCutOffBatch.Apply(plates, options, settings)
|
||||
: AutomaticCutOffBatch.Create(plates, options, settings);
|
||||
return (plates, plans);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The plates in scope, after checking planning may run: throws
|
||||
/// <see cref="InvalidOperationException"/> while busy, once the view shows another plate, or
|
||||
/// when the active plate has left the nest. A dialog checks this before reading its settings.
|
||||
/// </summary>
|
||||
public Plate[] EnsureReady()
|
||||
{
|
||||
if (isBusy?.Invoke() == true)
|
||||
throw new InvalidOperationException(BusyMessage);
|
||||
if (shownPlate != null && !ReferenceEquals(shownPlate(), Plate))
|
||||
throw new InvalidOperationException(PlateChangedMessage);
|
||||
|
||||
var plates = Nest?.Plates.ToArray() ?? new[] { Plate };
|
||||
if (!plates.Contains(Plate))
|
||||
throw new InvalidOperationException(PlateRemovedMessage);
|
||||
return plates;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Apply: replans and adds the definitions as one "Automatic Scrap Cutoffs" step, recorded
|
||||
/// only when the batch was not blocked and added something. A throw leaves the step
|
||||
/// incomplete, so it rolls back.
|
||||
/// </summary>
|
||||
public (Plate[] Plates, IReadOnlyList<AutomaticCutOffPlan> Plans) Apply(AutomaticCutOffOptions options,
|
||||
CutOffSettings settings, Func<string, ChangeScope> beginChange)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(beginChange);
|
||||
using var change = beginChange(Title);
|
||||
var result = Calculate(options, settings, apply: true);
|
||||
if (Applied(result.Plans))
|
||||
change.MarkChanged();
|
||||
change.Complete();
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Whether Apply changed the plates: nothing blocked and something was added.</summary>
|
||||
public static bool Applied(IReadOnlyList<AutomaticCutOffPlan> plans) =>
|
||||
!plans.Any(p => p.HasBlockingDiagnostics) && plans.Any(p => p.Definitions.Count > 0);
|
||||
|
||||
/// <summary>The active plate's detached preview parts, for display only; none when anything is blocked.</summary>
|
||||
public IReadOnlyList<Part> PreviewParts(Plate[] plates, IReadOnlyList<AutomaticCutOffPlan> plans) =>
|
||||
plans.Any(p => p.HasBlockingDiagnostics)
|
||||
? Array.Empty<Part>()
|
||||
: plans[Array.IndexOf(plates, Plate)].PreviewParts.ToList();
|
||||
|
||||
/// <summary>One plan's issues and notices, one per line.</summary>
|
||||
public string DiagnosticLines(AutomaticCutOffPlan plan) => string.Join(Environment.NewLine,
|
||||
plan.Diagnostics.Select(d =>
|
||||
$"{(d.IsBlocking ? "BLOCKING" : "Notice")} [{d.Code}]"
|
||||
+ (d.X.HasValue ? $" X = {SignedPosition(d.X.Value)}" : string.Empty)
|
||||
+ $": {d.Message}"));
|
||||
|
||||
/// <summary>
|
||||
/// What the dialog shows for planned <paramref name="plans"/>; with <paramref name="settingsOnly"/>
|
||||
/// (Plan Cutting's settings), the options may be chosen even when blocked or empty.
|
||||
/// </summary>
|
||||
public AutomaticCutOffSummary Summarize(Plate[] plates, IReadOnlyList<AutomaticCutOffPlan> plans,
|
||||
bool settingsOnly = false)
|
||||
{
|
||||
var currentIndex = Array.IndexOf(plates, Plate);
|
||||
var plan = plans[currentIndex];
|
||||
var saving = plan.FixedGridCutLength - plan.StripCutLength;
|
||||
var stripCuts = $"Strip cuts: {Measure(plan.StripCutLength)} ("
|
||||
+ (saving > 0 ? $"{Measure(saving)} less than the fixed grid" :
|
||||
saving < 0 ? $"{Measure(-saving)} more than the fixed grid" : "same as the fixed grid")
|
||||
+ ")";
|
||||
|
||||
var blocked = plans.Any(p => p.HasBlockingDiagnostics);
|
||||
var definitionCount = plans.Sum(p => p.Definitions.Count);
|
||||
|
||||
var issues = new List<string>();
|
||||
for (var index = 0; index < plans.Count; index++)
|
||||
{
|
||||
var lines = DiagnosticLines(plans[index]);
|
||||
if (lines.Length == 0)
|
||||
continue;
|
||||
issues.Add(AllPlates ? $"Plate {index + 1}: {lines}" : lines);
|
||||
}
|
||||
|
||||
string status;
|
||||
AutomaticCutOffTone tone;
|
||||
if (blocked)
|
||||
{
|
||||
var issueCount = plans.Sum(p => p.Diagnostics.Count(d => d.IsBlocking));
|
||||
status = $"Blocked — {issueCount} blocking issue{(issueCount == 1 ? "" : "s")}; nothing will be applied.";
|
||||
tone = AutomaticCutOffTone.Blocked;
|
||||
}
|
||||
else if (definitionCount == 0)
|
||||
{
|
||||
status = "No new cut-offs to apply.";
|
||||
tone = AutomaticCutOffTone.Neutral;
|
||||
}
|
||||
else if (!AllPlates)
|
||||
{
|
||||
status = $"Ready — {definitionCount} new cut-off{(definitionCount == 1 ? "" : "s")} will be added.";
|
||||
tone = AutomaticCutOffTone.Ready;
|
||||
}
|
||||
else
|
||||
{
|
||||
var touched = plans.Count(p => p.Definitions.Count > 0);
|
||||
status = $"Ready — {definitionCount} cut-off{(definitionCount == 1 ? "" : "s")} across {touched} of {plans.Count} plates. Unchanged plates stay untouched.";
|
||||
tone = AutomaticCutOffTone.Ready;
|
||||
}
|
||||
|
||||
return new AutomaticCutOffSummary(
|
||||
Measure(plan.OccupiedSpan),
|
||||
Measure(plan.UsedSpan),
|
||||
plan.HasSeparatedTail ? SignedPosition(plan.TailSeparatorX.Value) : "none",
|
||||
plan.HasSeparatedTail ? Measure(plan.TailLength) : "none",
|
||||
stripCuts,
|
||||
issues.Count == 0 ? NoIssues : string.Join(Environment.NewLine, issues),
|
||||
status,
|
||||
tone,
|
||||
// Settings may be chosen even when this layout needs no new lines or is blocked:
|
||||
// Plan Cutting reports the blocked plate itself.
|
||||
settingsOnly || !blocked && definitionCount > 0,
|
||||
AllPlates
|
||||
? $"All {plates.Length} plates — preview shows plate {currentIndex + 1} "
|
||||
+ $"({Measure(Plate.Size.Length)} length × {Measure(Plate.Size.Width)} width)"
|
||||
: null,
|
||||
AllPlates ? Rows(plans, currentIndex) : Array.Empty<AutomaticCutOffPlateRow>());
|
||||
}
|
||||
|
||||
private IReadOnlyList<AutomaticCutOffPlateRow> Rows(IReadOnlyList<AutomaticCutOffPlan> plans, int activeIndex)
|
||||
{
|
||||
var rows = new List<AutomaticCutOffPlateRow>();
|
||||
for (var index = 0; index < plans.Count; index++)
|
||||
{
|
||||
var plan = plans[index];
|
||||
var label = (index + 1).ToString(CultureInfo.CurrentCulture);
|
||||
if (index == activeIndex)
|
||||
label += " (active)";
|
||||
var tone = plan.HasBlockingDiagnostics ? AutomaticCutOffTone.Blocked
|
||||
: plan.Definitions.Count > 0 ? AutomaticCutOffTone.Ready
|
||||
: AutomaticCutOffTone.Unchanged;
|
||||
rows.Add(new AutomaticCutOffPlateRow(
|
||||
label,
|
||||
plan.Definitions.Count == 0 ? Unmeasured : plan.Definitions.Count.ToString(CultureInfo.CurrentCulture),
|
||||
Measure(plan.OccupiedSpan),
|
||||
Measure(plan.UsedSpan),
|
||||
plan.HasSeparatedTail ? Measure(plan.TailLength) : Unmeasured,
|
||||
plan.HasBlockingDiagnostics ? "Blocked" : plan.Definitions.Count > 0 ? "Ready" : "No change",
|
||||
tone));
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using OpenNest.CutOffs;
|
||||
using OpenNest.Engine.Sequencing;
|
||||
using OpenNest.Geometry;
|
||||
using OpenNest.Undo;
|
||||
|
||||
namespace OpenNest.Desktop.Interaction;
|
||||
|
||||
/// <summary>
|
||||
/// The WinForms plate view's manual cut-off edits, toolkit-neutral: adding a Sheet Cut-Off line,
|
||||
/// applying a trim, extend or Swap Through-Cut, each one undo step under its WinForms label.
|
||||
/// Every edit changes only the definitions in <see cref="Plate.CutOffs"/> and rebuilds the
|
||||
/// segments through <see cref="Plate.RegenerateCutOffs(CutOffSettings)"/>; preview parts are
|
||||
/// never accepted. See docs/automatic-scrap-cutoffs.md, "Trim and extend".
|
||||
/// </summary>
|
||||
public static class CutOffEdits
|
||||
{
|
||||
public const string AddLabel = "Add Cut-Off";
|
||||
public const string MoveLabel = "Move Cut-Off";
|
||||
public const string TrimLabel = "Trim Cut-Off";
|
||||
public const string ExtendLabel = "Extend Cut-Off";
|
||||
public const string SwapLabel = "Swap Through-Cut";
|
||||
|
||||
/// <summary>What the status bar says after a swap that has no notice of its own.</summary>
|
||||
public const string SwappedStatus = "Swapped the through-cut";
|
||||
|
||||
/// <summary>
|
||||
/// The line Sheet Cut-Off adds at <paramref name="point"/>: along <paramref name="axis"/>,
|
||||
/// with the new cut-off head-lock overcut of <paramref name="settings"/>, and unless
|
||||
/// <paramref name="fullLength"/>, stopped at the first crossing cut-off from its start edge
|
||||
/// (<see cref="CutOffTrim.StopAtFirstCrossing"/>). The line is not added to the plate;
|
||||
/// <c>Notice</c> says when stopping it turned its overcut off.
|
||||
/// </summary>
|
||||
public static (CutOff CutOff, string Notice) NewCutOff(Plate plate, Vector point, CutOffAxis axis,
|
||||
bool fullLength, CutOffSettings settings)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plate);
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
var cutOff = new CutOff(point, axis) { HeadLockOvercut = settings.NewCutOffHeadLockOvercut };
|
||||
var edit = fullLength ? null : CutOffTrim.StopAtFirstCrossing(plate, cutOff, settings);
|
||||
edit?.Apply();
|
||||
return (cutOff, edit?.Notice);
|
||||
}
|
||||
|
||||
/// <summary>Adds <paramref name="cutOff"/> to the plate and rebuilds its cut-offs, as one "Add Cut-Off" step.</summary>
|
||||
public static void Add(Plate plate, CutOff cutOff, CutOffSettings settings, Func<string, ChangeScope> beginChange)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plate);
|
||||
ArgumentNullException.ThrowIfNull(cutOff);
|
||||
ArgumentNullException.ThrowIfNull(beginChange);
|
||||
using var change = beginChange(AddLabel);
|
||||
change.MarkChanged();
|
||||
plate.CutOffs.Add(cutOff);
|
||||
plate.RegenerateCutOffs(settings);
|
||||
change.Complete();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies a trim, extend or swap as one undoable change: the new limits, regenerated
|
||||
/// cut-offs, and the changed cut-offs' segments placed where the cut-off rules need them
|
||||
/// (<see cref="PlateSequencing.PlaceCutOffs"/>). False, changing nothing, when the edit was
|
||||
/// refused. If applying throws, the step is left incomplete, so it rolls back.
|
||||
/// </summary>
|
||||
public static bool Apply(Plate plate, CutOffEdit edit, string label, CutOffSettings settings,
|
||||
Func<string, ChangeScope> beginChange)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plate);
|
||||
ArgumentNullException.ThrowIfNull(beginChange);
|
||||
if (edit == null || !edit.Succeeded)
|
||||
return false;
|
||||
|
||||
using var change = beginChange(label);
|
||||
change.MarkChanged();
|
||||
edit.Apply();
|
||||
plate.RegenerateCutOffs(settings);
|
||||
PlateSequencing.PlaceCutOffs(plate, edit.Changes.Select(c => c.CutOff));
|
||||
change.Complete();
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The junction of two cut-offs at <paramref name="world"/>, one running through and the
|
||||
/// other stopping at it, for the Swap Through-Cut menu; null when there is none.
|
||||
/// </summary>
|
||||
public static (CutOff Through, CutOff Stopper)? JunctionAt(Plate plate, Vector world, double tolerance) =>
|
||||
plate?.CutOffs == null ? null : CutOffTrim.JunctionAt(plate, world, tolerance);
|
||||
|
||||
/// <summary>
|
||||
/// Swap Through-Cut: the stopped line runs through the junction and the through line stops
|
||||
/// at it (<see cref="CutOffTrim.Swap"/>), as one step. Returns whether it was applied and
|
||||
/// the status line WinForms shows: the edit's notice or <see cref="SwappedStatus"/>, or why
|
||||
/// it was refused.
|
||||
/// </summary>
|
||||
public static (bool Applied, string Status) Swap(Plate plate, CutOff through, CutOff stopper,
|
||||
CutOffSettings settings, Func<string, ChangeScope> beginChange)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plate);
|
||||
var edit = CutOffTrim.Swap(plate, through, stopper, settings);
|
||||
return Apply(plate, edit, SwapLabel, settings, beginChange)
|
||||
? (true, edit.Notice ?? SwappedStatus)
|
||||
: (false, edit.Refusal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The stretches a trim or extend preview dashes: each changed cut-off's pieces it removes
|
||||
/// (<c>Added</c> false) and adds (<c>Added</c> true), as lines in plate coordinates.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<(Line Line, bool Added)> PreviewPieces(Plate plate, CutOffEdit edit)
|
||||
{
|
||||
var result = new List<(Line, bool)>();
|
||||
if (plate == null || edit is not { Succeeded: true })
|
||||
return result;
|
||||
foreach (var change in edit.Changes)
|
||||
{
|
||||
var (removed, added) = CutOffTrim.Difference(plate, change);
|
||||
foreach (var (from, to) in removed)
|
||||
AddPiece(result, change.CutOff, from, to, added: false);
|
||||
foreach (var (from, to) in added)
|
||||
AddPiece(result, change.CutOff, from, to, added: true);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void AddPiece(List<(Line, bool)> pieces, CutOff cutOff, double from, double to, bool added)
|
||||
{
|
||||
if (System.Math.Abs(to - from) <= Math.Tolerance.Epsilon)
|
||||
return;
|
||||
var vertical = cutOff.Axis == CutOffAxis.Vertical;
|
||||
var line = vertical ? cutOff.Position.X : cutOff.Position.Y;
|
||||
var a = vertical ? new Vector(line, from) : new Vector(from, line);
|
||||
var b = vertical ? new Vector(line, to) : new Vector(to, line);
|
||||
pieces.Add((new Line(a, b), added));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One drag of a cut-off, as the WinForms plate view's: from the press to the release it is one
|
||||
/// "Move Cut-Off" undo step. The cut-off follows the pointer across its axis and the lines that
|
||||
/// meet it (<see cref="CutOffTrim.Joints"/>) are extended or trimmed with it. On release after a
|
||||
/// real move the plate's cut-offs are rebuilt and the joined lines' segments are placed in the
|
||||
/// cutting order (<see cref="PlateSequencing.PlaceCutOffs"/>); a plain click changes nothing.
|
||||
/// </summary>
|
||||
public sealed class CutOffDrag
|
||||
{
|
||||
private readonly Plate plate;
|
||||
private readonly CutOffSettings settings;
|
||||
private readonly CutOffJoints joints;
|
||||
private Dictionary<Part, Entity> perimeterCache;
|
||||
private ChangeScope scope;
|
||||
private bool moved;
|
||||
|
||||
private CutOffDrag(Plate plate, CutOff cutOff, CutOffSettings settings, ChangeScope scope)
|
||||
{
|
||||
this.plate = plate;
|
||||
CutOff = cutOff;
|
||||
this.settings = settings;
|
||||
this.scope = scope;
|
||||
perimeterCache = Plate.BuildPerimeterCache(plate);
|
||||
joints = CutOffTrim.Joints(plate, cutOff, settings);
|
||||
}
|
||||
|
||||
/// <summary>Starts dragging <paramref name="cutOff"/>, opening its undo step.</summary>
|
||||
public static CutOffDrag Start(Plate plate, CutOff cutOff, CutOffSettings settings,
|
||||
Func<string, ChangeScope> beginChange)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plate);
|
||||
ArgumentNullException.ThrowIfNull(cutOff);
|
||||
ArgumentNullException.ThrowIfNull(beginChange);
|
||||
var scope = beginChange(CutOffEdits.MoveLabel);
|
||||
try
|
||||
{
|
||||
return new CutOffDrag(plate, cutOff, settings, scope);
|
||||
}
|
||||
catch
|
||||
{
|
||||
scope.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The cut-off being dragged.</summary>
|
||||
public CutOff CutOff { get; }
|
||||
|
||||
/// <summary>Whether the drag has ended.</summary>
|
||||
public bool IsEnded => scope == null;
|
||||
|
||||
/// <summary>Moves the cut-off's line through <paramref name="point"/>, taking its joined lines along.</summary>
|
||||
public void MoveTo(Vector point)
|
||||
{
|
||||
if (scope == null)
|
||||
return;
|
||||
scope.MarkChanged();
|
||||
CutOff.Position = CutOff.Axis == CutOffAxis.Vertical
|
||||
? new Vector(point.X, CutOff.Position.Y)
|
||||
: new Vector(CutOff.Position.X, point.Y);
|
||||
CutOff.Regenerate(plate, settings, perimeterCache);
|
||||
moved = true;
|
||||
joints?.MoveTo(CutOff.Axis == CutOffAxis.Vertical ? CutOff.Position.X : CutOff.Position.Y);
|
||||
foreach (var line in joints?.Lines ?? new List<CutOff>())
|
||||
line.Regenerate(plate, settings, perimeterCache);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ends the drag: rebuilds the cut-offs, places the joined lines' segments and records the
|
||||
/// step. If rebuilding throws, the step is disposed incomplete, so the move rolls back, and
|
||||
/// the exception propagates. Ending twice does nothing.
|
||||
/// </summary>
|
||||
public void End()
|
||||
{
|
||||
var ending = scope;
|
||||
scope = null;
|
||||
if (ending == null)
|
||||
return;
|
||||
perimeterCache = null;
|
||||
try
|
||||
{
|
||||
// Only after a real move: rebuilding gives the cut-offs new segment parts, which
|
||||
// would otherwise be an unrecorded change after a plain click.
|
||||
if (moved)
|
||||
{
|
||||
plate.RegenerateCutOffs(settings);
|
||||
if (joints != null)
|
||||
PlateSequencing.PlaceCutOffs(plate, joints.Lines);
|
||||
}
|
||||
ending.Complete();
|
||||
}
|
||||
finally
|
||||
{
|
||||
ending.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,9 @@ namespace OpenNest.Desktop.Interaction;
|
||||
/// <summary>
|
||||
/// The default plate tool, with the WinForms Select action's selection rules:
|
||||
/// <list type="bullet">
|
||||
/// <item>A left click within <see cref="CutOffPickPixels"/> of a cut-off's stroke selects that cut-off alone.</item>
|
||||
/// <item>A left press within <see cref="CutOffPickPixels"/> of a cut-off's stroke selects that cut-off alone
|
||||
/// and drags it across its axis, taking the lines that meet it along, as one "Move Cut-Off" undo
|
||||
/// step (<see cref="CutOffDrag"/>).</item>
|
||||
/// <item>A left click on a part selects it (with its common-line group) in place of the selection;
|
||||
/// with Ctrl alone held, or on a part already selected, it adds to the selection instead.</item>
|
||||
/// <item>Dragging from a part moves every selected part with the pointer, as one "Move" undo
|
||||
@@ -16,9 +18,9 @@ namespace OpenNest.Desktop.Interaction;
|
||||
/// <item>A right click on an unselected part selects it alone, for its menu; on an empty area it
|
||||
/// clears the selection.</item>
|
||||
/// </list>
|
||||
/// Cancelling ends a move in progress where it is (still one undo step) and clears the selection.
|
||||
/// Losing the pointer mid-drag ends a move as a release where it is and keeps the selection; a
|
||||
/// selection window is dropped without selecting.
|
||||
/// Cancelling ends a move or cut-off drag in progress where it is (still one undo step) and
|
||||
/// clears the selection. Losing the pointer mid-drag ends a move or cut-off drag as a release
|
||||
/// where it is and keeps the selection; a selection window is dropped without selecting.
|
||||
/// <para>
|
||||
/// While the host's edits are locked (<see cref="IPlateToolHost.EditsLocked"/>) a press does
|
||||
/// nothing at all, as in WinForms, whose <c>PlateView.OnMouseDown</c> returns before the Select
|
||||
@@ -46,6 +48,11 @@ public sealed class SelectTool : PlateTool
|
||||
/// <summary>Whether a drag is moving the selected parts.</summary>
|
||||
public bool IsMoving => move != null;
|
||||
|
||||
/// <summary>Whether a drag is moving a cut-off.</summary>
|
||||
public bool IsDraggingCutOff => cutOffDrag != null;
|
||||
|
||||
private CutOffDrag cutOffDrag;
|
||||
|
||||
private ChangeScope move;
|
||||
private Vector lastMoveWorld;
|
||||
|
||||
@@ -56,6 +63,7 @@ public sealed class SelectTool : PlateTool
|
||||
{
|
||||
// Parts already dragged stay where they are, so the move is recorded.
|
||||
EndMove();
|
||||
EndCutOffDrag();
|
||||
Window = null;
|
||||
Host.Selection.Clear();
|
||||
Host.Invalidate();
|
||||
@@ -72,12 +80,14 @@ public sealed class SelectTool : PlateTool
|
||||
if (pointer.Button == ToolButton.Left)
|
||||
{
|
||||
EndMove();
|
||||
EndCutOffDrag();
|
||||
Window = null;
|
||||
var tolerance = Host.View.LengthToWorld(CutOffPickPixels);
|
||||
var cutOff = Host.HitTester.CutOffAt(plate, pointer.World, tolerance);
|
||||
if (cutOff != null)
|
||||
{
|
||||
selection.SelectOnly(cutOff);
|
||||
cutOffDrag = CutOffDrag.Start(plate, cutOff, Host.CutOffSettings, label => Host.BeginChange(label));
|
||||
Host.Invalidate();
|
||||
return true;
|
||||
}
|
||||
@@ -121,6 +131,12 @@ public sealed class SelectTool : PlateTool
|
||||
{
|
||||
if (pointer.Button != ToolButton.Left)
|
||||
return false;
|
||||
if (cutOffDrag != null)
|
||||
{
|
||||
cutOffDrag.MoveTo(pointer.World);
|
||||
Host.Invalidate();
|
||||
return true;
|
||||
}
|
||||
if (move != null)
|
||||
{
|
||||
var offset = pointer.World - lastMoveWorld;
|
||||
@@ -142,6 +158,11 @@ public sealed class SelectTool : PlateTool
|
||||
{
|
||||
if (pointer.Button != ToolButton.Left)
|
||||
return false;
|
||||
if (cutOffDrag != null)
|
||||
{
|
||||
EndCutOffDrag();
|
||||
return true;
|
||||
}
|
||||
if (move != null)
|
||||
{
|
||||
FinishMove();
|
||||
@@ -165,6 +186,7 @@ public sealed class SelectTool : PlateTool
|
||||
{
|
||||
if (move != null)
|
||||
FinishMove();
|
||||
EndCutOffDrag();
|
||||
Window = null;
|
||||
Host.Invalidate();
|
||||
}
|
||||
@@ -195,6 +217,23 @@ public sealed class SelectTool : PlateTool
|
||||
}
|
||||
}
|
||||
|
||||
// Ends a cut-off drag as its release does; if rebuilding throws, the drag rolls back.
|
||||
private void EndCutOffDrag()
|
||||
{
|
||||
var drag = cutOffDrag;
|
||||
cutOffDrag = null;
|
||||
if (drag == null)
|
||||
return;
|
||||
try
|
||||
{
|
||||
drag.End();
|
||||
}
|
||||
finally
|
||||
{
|
||||
Host.Invalidate();
|
||||
}
|
||||
}
|
||||
|
||||
private void EndMove()
|
||||
{
|
||||
var scope = move;
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using OpenNest.CutOffs;
|
||||
using OpenNest.Geometry;
|
||||
|
||||
namespace OpenNest.Desktop.Interaction;
|
||||
|
||||
/// <summary>
|
||||
/// Choices the cut-off tools keep for a view while its nest stays open, as the WinForms plate
|
||||
/// view's cut-off handler does.
|
||||
/// </summary>
|
||||
public sealed class CutOffToolOptions
|
||||
{
|
||||
/// <summary>Whether Sheet Cut-Off draws full-length lines instead of stopping at the first crossing.</summary>
|
||||
public bool FullLengthNewLines { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The WinForms Sheet Cut-Off action (Plate > Sheet Cut-Off), toolkit-neutral: as the pointer
|
||||
/// moves, <see cref="Preview"/> is the line a click adds there; a left click adds it as one
|
||||
/// "Add Cut-Off" step (<see cref="CutOffEdits.Add"/>). The line is vertical at first; Space
|
||||
/// (<see cref="ToggleAxis"/>) turns it. Unless the view's <see cref="CutOffToolOptions"/> ask for
|
||||
/// full-length lines, a new line stops at the first crossing cut-off from its start edge; Tab
|
||||
/// (<see cref="ToggleFullLength"/>) switches, and the choice outlasts the tool. The tool stays
|
||||
/// active until Escape; nothing happens while the host's edits are locked.
|
||||
/// </summary>
|
||||
public sealed class SheetCutOffTool : PlateTool
|
||||
{
|
||||
private readonly CutOffToolOptions options;
|
||||
private Dictionary<Part, Entity> perimeterCache;
|
||||
private Vector? lastPoint;
|
||||
private string notice;
|
||||
|
||||
public SheetCutOffTool(IPlateToolHost host, CutOffToolOptions options)
|
||||
: base(host)
|
||||
{
|
||||
this.options = options ?? throw new ArgumentNullException(nameof(options));
|
||||
}
|
||||
|
||||
public override string Name => "Sheet Cut-Off";
|
||||
|
||||
public override bool IsBusy => false;
|
||||
|
||||
/// <summary>The axis the next line runs along.</summary>
|
||||
public CutOffAxis Axis { get; private set; } = CutOffAxis.Vertical;
|
||||
|
||||
/// <summary>Whether new lines run full length rather than stopping at the first crossing.</summary>
|
||||
public bool FullLength => options.FullLengthNewLines;
|
||||
|
||||
/// <summary>The line a click would add at the pointer, its segments regenerated; null before the pointer moves.</summary>
|
||||
public CutOff Preview { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// The tag shown beside the cursor, since the status bar is easy to miss: how to turn the
|
||||
/// line and switch its length.
|
||||
/// </summary>
|
||||
public string CursorTag =>
|
||||
$"Space: turn {AxisName(OtherAxis(Axis))}\nTab: {(FullLength ? "stop at first crossing" : "full length")}";
|
||||
|
||||
public override string Hint
|
||||
{
|
||||
get
|
||||
{
|
||||
var hint = FullLength
|
||||
? $"click to add a full-length {AxisName(Axis)} line, Space turns it {AxisName(OtherAxis(Axis))}, Tab stops it at the first crossing, Esc finishes"
|
||||
: $"click to add a {AxisName(Axis)} line stopped at the first crossing, Space turns it {AxisName(OtherAxis(Axis))}, Tab makes it full length, Esc finishes";
|
||||
return notice == null ? hint : $"{notice} {hint}";
|
||||
}
|
||||
}
|
||||
|
||||
public override void Activate()
|
||||
{
|
||||
if (Host.Plate != null)
|
||||
perimeterCache = Plate.BuildPerimeterCache(Host.Plate);
|
||||
}
|
||||
|
||||
public override void Deactivate()
|
||||
{
|
||||
Preview = null;
|
||||
perimeterCache = null;
|
||||
notice = null;
|
||||
lastPoint = null;
|
||||
Host.Invalidate();
|
||||
}
|
||||
|
||||
public override void Cancel() { }
|
||||
|
||||
public override bool PointerMoved(ToolPointer pointer)
|
||||
{
|
||||
lastPoint = pointer.World;
|
||||
UpdatePreview();
|
||||
return true;
|
||||
}
|
||||
|
||||
public override bool PointerPressed(ToolPointer pointer)
|
||||
{
|
||||
var plate = Host.Plate;
|
||||
if (pointer.Button != ToolButton.Left || plate == null || Host.EditsLocked)
|
||||
return false;
|
||||
var cutOff = NewCutOff(pointer.World);
|
||||
CutOffEdits.Add(plate, cutOff, Host.CutOffSettings, label => Host.BeginChange(label));
|
||||
Host.Invalidate();
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Space: turns the next line to the other axis.</summary>
|
||||
public void ToggleAxis()
|
||||
{
|
||||
Axis = OtherAxis(Axis);
|
||||
RaiseHintChanged();
|
||||
if (Preview != null)
|
||||
UpdatePreview();
|
||||
}
|
||||
|
||||
/// <summary>Tab: switches between full-length lines and lines stopped at the first crossing.</summary>
|
||||
public void ToggleFullLength()
|
||||
{
|
||||
options.FullLengthNewLines = !options.FullLengthNewLines;
|
||||
RaiseHintChanged();
|
||||
if (Preview != null)
|
||||
UpdatePreview();
|
||||
}
|
||||
|
||||
private CutOff NewCutOff(Vector point)
|
||||
{
|
||||
var (cutOff, newNotice) = CutOffEdits.NewCutOff(Host.Plate, point, Axis, FullLength, Host.CutOffSettings);
|
||||
if (notice != newNotice)
|
||||
{
|
||||
notice = newNotice;
|
||||
RaiseHintChanged();
|
||||
}
|
||||
return cutOff;
|
||||
}
|
||||
|
||||
private void UpdatePreview()
|
||||
{
|
||||
var plate = Host.Plate;
|
||||
if (plate == null || lastPoint is not { } point)
|
||||
return;
|
||||
perimeterCache ??= Plate.BuildPerimeterCache(plate);
|
||||
var preview = NewCutOff(point);
|
||||
preview.Regenerate(plate, Host.CutOffSettings, perimeterCache);
|
||||
Preview = preview;
|
||||
Host.Invalidate();
|
||||
}
|
||||
|
||||
private static CutOffAxis OtherAxis(CutOffAxis axis) =>
|
||||
axis == CutOffAxis.Vertical ? CutOffAxis.Horizontal : CutOffAxis.Vertical;
|
||||
|
||||
private static string AxisName(CutOffAxis axis) =>
|
||||
axis == CutOffAxis.Vertical ? "vertical" : "horizontal";
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using OpenNest.CutOffs;
|
||||
using OpenNest.Geometry;
|
||||
|
||||
namespace OpenNest.Desktop.Interaction;
|
||||
|
||||
/// <summary>
|
||||
/// The WinForms Trim/Extend Cut-Off action, toolkit-neutral: trims or extends a cut-off against
|
||||
/// the cut-offs that cross it (see <see cref="CutOffTrim"/>). Trim removes the clicked piece,
|
||||
/// leaving a gap when it lies between two crossing lines; Extend closes the gap or grows the end
|
||||
/// nearer the click. Tab (<see cref="ToggleMode"/>) switches mode. Hovering a cut-off previews
|
||||
/// the edit (<see cref="PreviewPieces"/>), and the status hint says why one is refused; a left
|
||||
/// click applies it as one "Trim Cut-Off" or "Extend Cut-Off" step. The tool stays active until
|
||||
/// Escape; nothing is applied while the host's edits are locked.
|
||||
/// </summary>
|
||||
public sealed class TrimExtendCutOffTool : PlateTool
|
||||
{
|
||||
private CutOff hovered;
|
||||
private CutOffEdit preview;
|
||||
private string message;
|
||||
private Vector? lastPoint;
|
||||
|
||||
public TrimExtendCutOffTool(IPlateToolHost host)
|
||||
: base(host)
|
||||
{
|
||||
}
|
||||
|
||||
public override string Name => "Trim/Extend Cut-Off";
|
||||
|
||||
public override bool IsBusy => false;
|
||||
|
||||
/// <summary>Whether clicks extend rather than trim.</summary>
|
||||
public bool Extending { get; private set; }
|
||||
|
||||
/// <summary>The edit a click at the pointer would make, or null off any cut-off.</summary>
|
||||
public CutOffEdit Preview => preview;
|
||||
|
||||
public override string Hint => message ?? (Extending
|
||||
? "click near the end of a cut-off to extend it or close a gap, Tab switches to Trim, Esc finishes"
|
||||
: "click the piece of a cut-off to remove, Tab switches to Extend, Esc finishes");
|
||||
|
||||
/// <summary>
|
||||
/// The stretches the hovered edit removes (dashed red) and adds (dashed green); empty when
|
||||
/// there is none or it is refused.
|
||||
/// </summary>
|
||||
public IReadOnlyList<(Line Line, bool Added)> PreviewPieces => CutOffEdits.PreviewPieces(Host.Plate, preview);
|
||||
|
||||
public override void Cancel() { }
|
||||
|
||||
public override void Deactivate()
|
||||
{
|
||||
hovered = null;
|
||||
preview = null;
|
||||
lastPoint = null;
|
||||
Host.Invalidate();
|
||||
}
|
||||
|
||||
private double Tolerance => Host.View.LengthToWorld(SelectTool.CutOffPickPixels);
|
||||
|
||||
private CutOffEdit EditAt(CutOff cutOff, Vector point) => Extending
|
||||
? CutOffTrim.Extend(Host.Plate, cutOff, point)
|
||||
: CutOffTrim.Trim(Host.Plate, cutOff, point, Host.CutOffSettings);
|
||||
|
||||
public override bool PointerMoved(ToolPointer pointer)
|
||||
{
|
||||
var plate = Host.Plate;
|
||||
lastPoint = pointer.World;
|
||||
hovered = plate == null ? null : Host.HitTester.CutOffAt(plate, pointer.World, Tolerance);
|
||||
preview = hovered == null ? null : EditAt(hovered, pointer.World);
|
||||
SetMessage(preview?.Refusal);
|
||||
Host.Invalidate();
|
||||
return true;
|
||||
}
|
||||
|
||||
public override bool PointerPressed(ToolPointer pointer)
|
||||
{
|
||||
var plate = Host.Plate;
|
||||
if (pointer.Button != ToolButton.Left || plate == null || Host.EditsLocked)
|
||||
return false;
|
||||
var cutOff = Host.HitTester.CutOffAt(plate, pointer.World, Tolerance);
|
||||
if (cutOff == null)
|
||||
return false;
|
||||
|
||||
var edit = EditAt(cutOff, pointer.World);
|
||||
if (CutOffEdits.Apply(plate, edit, Extending ? CutOffEdits.ExtendLabel : CutOffEdits.TrimLabel,
|
||||
Host.CutOffSettings, label => Host.BeginChange(label)))
|
||||
{
|
||||
hovered = null;
|
||||
preview = null;
|
||||
SetMessage(edit.Notice);
|
||||
}
|
||||
else
|
||||
{
|
||||
SetMessage(edit.Refusal);
|
||||
}
|
||||
Host.Invalidate();
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Tab: switches between Trim and Extend, re-previewing the hovered cut-off.</summary>
|
||||
public void ToggleMode()
|
||||
{
|
||||
Extending = !Extending;
|
||||
preview = hovered == null || lastPoint is not { } at ? null : EditAt(hovered, at);
|
||||
message = preview?.Refusal;
|
||||
RaiseHintChanged();
|
||||
Host.Invalidate();
|
||||
}
|
||||
|
||||
private void SetMessage(string value)
|
||||
{
|
||||
if (message == value)
|
||||
return;
|
||||
message = value;
|
||||
RaiseHintChanged();
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ using System.Windows.Forms;
|
||||
using OpenNest.CNC;
|
||||
using OpenNest.Controls;
|
||||
using OpenNest.CutOffs;
|
||||
using OpenNest.Desktop.Interaction;
|
||||
using OpenNest.Geometry;
|
||||
|
||||
namespace OpenNest.Actions
|
||||
@@ -74,13 +75,10 @@ namespace OpenNest.Actions
|
||||
|
||||
private CutOff NewCutOff(Vector point)
|
||||
{
|
||||
var cutOff = new CutOff(point, lockedAxis) { HeadLockOvercut = settings.NewCutOffHeadLockOvercut };
|
||||
var edit = FullLength ? null : CutOffTrim.StopAtFirstCrossing(plateView.Plate, cutOff, settings);
|
||||
edit?.Apply();
|
||||
|
||||
if (notice != edit?.Notice)
|
||||
var (cutOff, newNotice) = CutOffEdits.NewCutOff(plateView.Plate, point, lockedAxis, FullLength, settings);
|
||||
if (notice != newNotice)
|
||||
{
|
||||
notice = edit?.Notice;
|
||||
notice = newNotice;
|
||||
plateView.RefreshActionStatus();
|
||||
}
|
||||
return cutOff;
|
||||
@@ -101,13 +99,8 @@ namespace OpenNest.Actions
|
||||
return;
|
||||
|
||||
var cutoff = NewCutOff(plateView.CurrentPoint);
|
||||
|
||||
using var change = plateView.BeginChange("Add Cut-Off");
|
||||
change.MarkChanged();
|
||||
plateView.Plate.CutOffs.Add(cutoff);
|
||||
plateView.Plate.RegenerateCutOffs(settings);
|
||||
CutOffEdits.Add(plateView.Plate, cutoff, settings, label => plateView.BeginChange(label));
|
||||
plateView.Invalidate();
|
||||
change.Complete();
|
||||
}
|
||||
|
||||
private void OnKeyDown(object sender, KeyEventArgs e)
|
||||
|
||||
@@ -4,6 +4,7 @@ using System.Drawing.Drawing2D;
|
||||
using System.Windows.Forms;
|
||||
using OpenNest.Controls;
|
||||
using OpenNest.CutOffs;
|
||||
using OpenNest.Desktop.Interaction;
|
||||
using OpenNest.Geometry;
|
||||
|
||||
namespace OpenNest.Actions
|
||||
@@ -81,7 +82,7 @@ namespace OpenNest.Actions
|
||||
return;
|
||||
|
||||
var edit = EditAt(cutOff, point);
|
||||
if (plateView.CutOffs.Apply(edit, extend ? "Extend Cut-Off" : "Trim Cut-Off"))
|
||||
if (plateView.CutOffs.Apply(edit, extend ? CutOffEdits.ExtendLabel : CutOffEdits.TrimLabel))
|
||||
{
|
||||
hovered = null;
|
||||
preview = null;
|
||||
@@ -127,25 +128,11 @@ namespace OpenNest.Actions
|
||||
var width = 2f / plateView.ViewScale;
|
||||
using var removed = new Pen(Color.FromArgb(200, 220, 20, 60), width) { DashStyle = DashStyle.Dash };
|
||||
using var added = new Pen(Color.FromArgb(200, 34, 139, 34), width) { DashStyle = DashStyle.Dash };
|
||||
foreach (var change in preview.Changes)
|
||||
foreach (var (piece, isAdded) in CutOffEdits.PreviewPieces(plateView.Plate, preview))
|
||||
{
|
||||
var (removedPieces, addedPieces) = CutOffTrim.Difference(plateView.Plate, change);
|
||||
foreach (var (from, to) in removedPieces)
|
||||
DrawPiece(e.Graphics, change.CutOff, from, to, removed);
|
||||
foreach (var (from, to) in addedPieces)
|
||||
DrawPiece(e.Graphics, change.CutOff, from, to, added);
|
||||
e.Graphics.DrawLine(isAdded ? added : removed,
|
||||
plateView.PointWorldToGraph(piece.StartPoint), plateView.PointWorldToGraph(piece.EndPoint));
|
||||
}
|
||||
}
|
||||
|
||||
private void DrawPiece(Graphics g, CutOff cutOff, double from, double to, Pen pen)
|
||||
{
|
||||
if (System.Math.Abs(to - from) <= Math.Tolerance.Epsilon)
|
||||
return;
|
||||
var vertical = cutOff.Axis == CutOffAxis.Vertical;
|
||||
var line = vertical ? cutOff.Position.X : cutOff.Position.Y;
|
||||
var a = vertical ? new Vector(line, from) : new Vector(from, line);
|
||||
var b = vertical ? new Vector(line, to) : new Vector(to, line);
|
||||
g.DrawLine(pen, plateView.PointWorldToGraph(a), plateView.PointWorldToGraph(b));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,6 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using OpenNest.CNC;
|
||||
using OpenNest.CutOffs;
|
||||
using OpenNest.Desktop.Interaction;
|
||||
using OpenNest.Engine.Sequencing;
|
||||
using OpenNest.Geometry;
|
||||
using OpenNest.Undo;
|
||||
|
||||
namespace OpenNest.Controls
|
||||
{
|
||||
@@ -13,14 +8,9 @@ namespace OpenNest.Controls
|
||||
{
|
||||
private readonly PlateView view;
|
||||
private readonly PlateHitTester hitTester = new();
|
||||
private Dictionary<Part, Geometry.Entity> dragPerimeterCache;
|
||||
|
||||
// Open from the press on a cut-off to the release: a drag undoes as one move.
|
||||
private ChangeScope drag;
|
||||
|
||||
// The lines that meet the dragged cut-off and follow it.
|
||||
private CutOffJoints joints;
|
||||
private bool moved;
|
||||
private CutOffDrag drag;
|
||||
|
||||
public CutOffHandler(PlateView view)
|
||||
{
|
||||
@@ -38,30 +28,17 @@ namespace OpenNest.Controls
|
||||
if (hitCutOff == null)
|
||||
return null;
|
||||
|
||||
drag = CutOffDrag.Start(view.Plate, hitCutOff, view.CutOffSettings, label => view.BeginChange(label));
|
||||
IsDragging = true;
|
||||
dragPerimeterCache = Plate.BuildPerimeterCache(view.Plate);
|
||||
joints = CutOffTrim.Joints(view.Plate, hitCutOff, view.CutOffSettings);
|
||||
moved = false;
|
||||
drag = view.BeginChange("Move Cut-Off");
|
||||
return hitCutOff;
|
||||
}
|
||||
|
||||
public void UpdateDrag(Vector currentPoint, CutOff cutOff)
|
||||
{
|
||||
if (!IsDragging || cutOff == null)
|
||||
if (!IsDragging || cutOff == null || !ReferenceEquals(cutOff, drag?.CutOff))
|
||||
return;
|
||||
|
||||
drag?.MarkChanged();
|
||||
if (cutOff.Axis == CutOffAxis.Vertical)
|
||||
cutOff.Position = new Vector(currentPoint.X, cutOff.Position.Y);
|
||||
else
|
||||
cutOff.Position = new Vector(cutOff.Position.X, currentPoint.Y);
|
||||
|
||||
cutOff.Regenerate(view.Plate, view.CutOffSettings, dragPerimeterCache);
|
||||
moved = true;
|
||||
joints?.MoveTo(cutOff.Axis == CutOffAxis.Vertical ? cutOff.Position.X : cutOff.Position.Y);
|
||||
foreach (var line in joints?.Lines ?? new List<CutOff>())
|
||||
line.Regenerate(view.Plate, view.CutOffSettings, dragPerimeterCache);
|
||||
drag.MoveTo(currentPoint);
|
||||
view.Invalidate();
|
||||
}
|
||||
|
||||
@@ -71,17 +48,16 @@ namespace OpenNest.Controls
|
||||
return;
|
||||
|
||||
IsDragging = false;
|
||||
dragPerimeterCache = null;
|
||||
view.Plate.RegenerateCutOffs(view.CutOffSettings);
|
||||
if (moved && joints != null)
|
||||
PlateSequencing.PlaceCutOffs(view.Plate, joints.Lines);
|
||||
joints = null;
|
||||
view.Invalidate();
|
||||
|
||||
var scope = drag;
|
||||
var ending = drag;
|
||||
drag = null;
|
||||
scope?.Complete();
|
||||
scope?.Dispose();
|
||||
try
|
||||
{
|
||||
ending?.End();
|
||||
}
|
||||
finally
|
||||
{
|
||||
view.Invalidate();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -91,16 +67,9 @@ namespace OpenNest.Controls
|
||||
/// </summary>
|
||||
public bool Apply(CutOffEdit edit, string label)
|
||||
{
|
||||
if (edit == null || !edit.Succeeded)
|
||||
if (!CutOffEdits.Apply(view.Plate, edit, label, view.CutOffSettings, l => view.BeginChange(l)))
|
||||
return false;
|
||||
|
||||
using var change = view.BeginChange(label);
|
||||
change.MarkChanged();
|
||||
edit.Apply();
|
||||
view.Plate.RegenerateCutOffs(view.CutOffSettings);
|
||||
PlateSequencing.PlaceCutOffs(view.Plate, edit.Changes.Select(c => c.CutOff));
|
||||
view.Invalidate();
|
||||
change.Complete();
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ using System.Drawing;
|
||||
using System.Windows.Forms;
|
||||
using OpenNest.Actions;
|
||||
using OpenNest.CutOffs;
|
||||
using OpenNest.Desktop.Interaction;
|
||||
|
||||
namespace OpenNest.Controls
|
||||
{
|
||||
@@ -47,13 +48,13 @@ namespace OpenNest.Controls
|
||||
)
|
||||
return null;
|
||||
|
||||
if (CutOffTrim.JunctionAt(plate, view.PointControlToWorld(location), tolerance) is not var (through, stopper))
|
||||
if (CutOffEdits.JunctionAt(plate, view.PointControlToWorld(location), tolerance) is not var (through, stopper))
|
||||
return null;
|
||||
|
||||
menu ??= new ContextMenuStrip();
|
||||
while (menu.Items.Count > 0)
|
||||
menu.Items[0].Dispose();
|
||||
menu.Items.Add("Swap Through-Cut", null, (_, _) => Swap(plate, through, stopper));
|
||||
menu.Items.Add(CutOffEdits.SwapLabel, null, (_, _) => Swap(plate, through, stopper));
|
||||
return menu;
|
||||
}
|
||||
|
||||
@@ -63,11 +64,10 @@ namespace OpenNest.Controls
|
||||
if (!ReferenceEquals(plate, view.Plate) || view.IsFillInProgress)
|
||||
return;
|
||||
|
||||
var edit = CutOffTrim.Swap(plate, through, stopper, view.CutOffSettings);
|
||||
if (view.CutOffs.Apply(edit, "Swap Through-Cut"))
|
||||
view.Status = edit.Notice ?? "Swapped the through-cut";
|
||||
else
|
||||
view.Status = edit.Refusal;
|
||||
var (_, status) = CutOffEdits.Swap(plate, through, stopper, view.CutOffSettings,
|
||||
label => view.BeginChange(label));
|
||||
view.Status = status;
|
||||
view.Invalidate();
|
||||
}
|
||||
|
||||
public void Dispose() => menu?.Dispose();
|
||||
|
||||
@@ -16,9 +16,8 @@ namespace OpenNest
|
||||
Properties.Settings.Default.CutOffHeadLockOvercutInches)
|
||||
.ApplyTo(settings, units);
|
||||
|
||||
internal static void Save(bool lockHeadHeight, double overcut, Units units)
|
||||
internal static void Save(SavedCutOffHeadLock saved)
|
||||
{
|
||||
var saved = SavedCutOffHeadLock.From(lockHeadHeight, overcut, units);
|
||||
Properties.Settings.Default.CutOffLockHeadHeight = saved.LockHeadHeight;
|
||||
Properties.Settings.Default.CutOffHeadLockOvercutInches = saved.OvercutInches;
|
||||
Properties.Settings.Default.Save();
|
||||
|
||||
@@ -19,9 +19,7 @@ public partial class AutomaticCutOffForm : Form
|
||||
private readonly PlateView plateView;
|
||||
private readonly Plate plate;
|
||||
private readonly Nest nest;
|
||||
private readonly Func<bool> isOperationBusy;
|
||||
private readonly Units units;
|
||||
private readonly string unit;
|
||||
private readonly AutomaticCutOffSession session;
|
||||
private bool minimumStripEdited;
|
||||
private bool settingMinimumStrip;
|
||||
private bool settingsOnly;
|
||||
@@ -37,7 +35,7 @@ public partial class AutomaticCutOffForm : Form
|
||||
AutomaticCutOffOptions initial)
|
||||
{
|
||||
var form = new AutomaticCutOffForm(plateView, units, nest, null) { settingsOnly = true };
|
||||
form.Text = "Automatic Scrap Cut-offs — Settings for Plan Cutting";
|
||||
form.Text = AutomaticCutOffSession.SettingsTitle;
|
||||
form.applyButton.Text = "&Use These Settings";
|
||||
if (initial != null)
|
||||
{
|
||||
@@ -60,26 +58,25 @@ public partial class AutomaticCutOffForm : Form
|
||||
this.plateView = plateView ?? throw new ArgumentNullException(nameof(plateView));
|
||||
plate = plateView.Plate ?? throw new ArgumentException("An active plate is required.", nameof(plateView));
|
||||
this.nest = nest;
|
||||
this.isOperationBusy = isOperationBusy;
|
||||
this.units = units;
|
||||
unit = UnitsHelper.GetShortString(units);
|
||||
session = new AutomaticCutOffSession(plate, units, nest,
|
||||
() => plateView.IsFillInProgress || isOperationBusy?.Invoke() == true,
|
||||
() => plateView.IsDisposed ? null : plateView.Plate);
|
||||
InitializeComponent();
|
||||
spacingLabel.Text = $"Nominal spacing along sheet length ({unit}):";
|
||||
spacingBox.Text = units == Units.Millimeters ? "889" : "35";
|
||||
minimumStripLabel.Text = $"Minimum strip ({unit}):";
|
||||
minimumTailLabel.Text = $"Minimum tail to keep ({unit}):";
|
||||
minimumTailBox.Text = (units == Units.Millimeters ? 304.8 : 12).ToString(CultureInfo.CurrentCulture);
|
||||
headLockBox.Text = $"Lock head height and overcut the far edge by ({unit}):";
|
||||
spacingLabel.Text = session.SpacingLabel;
|
||||
spacingBox.Text = session.DefaultSpacingText;
|
||||
minimumStripLabel.Text = session.MinimumStripLabel;
|
||||
minimumTailLabel.Text = session.MinimumTailLabel;
|
||||
minimumTailBox.Text = session.DefaultMinimumTailText;
|
||||
headLockBox.Text = session.HeadLockLabel;
|
||||
headLockBox.Checked = plateView.CutOffSettings.LockHeadHeight;
|
||||
headLockOvercutBox.Text = plateView.CutOffSettings.HeadLockOvercut.ToString(CultureInfo.CurrentCulture);
|
||||
headLockOvercutBox.Enabled = headLockBox.Checked;
|
||||
sheetLabel.Text = $"Sheet: {Measure(plate.Size.Length)} length × {Measure(plate.Size.Width)} width";
|
||||
sheetLabel.Text = session.InitialSheetText;
|
||||
diagnosticsLabel.Text = session.DetailsLabel;
|
||||
if (nest != null)
|
||||
{
|
||||
Text = "Automatic Scrap Cutoffs — All Plates";
|
||||
applyButton.Text = "&Apply to All Plates";
|
||||
sheetLabel.Text = $"All {nest.Plates.Count} plates — active sheet shown below";
|
||||
diagnosticsLabel.Text = "Details — issues and notices (the table above lists every plate):";
|
||||
Text = session.DialogTitle;
|
||||
applyButton.Text = session.ApplyText;
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -106,73 +103,25 @@ public partial class AutomaticCutOffForm : Form
|
||||
plateView.ClearPreviewParts();
|
||||
}
|
||||
|
||||
private string Measure(double value) => $"{value:0.####} {unit}";
|
||||
|
||||
private string SignedPosition(double value) => $"{value:+0.####;-0.####;0} {unit}";
|
||||
|
||||
// Busy and plate checks come before the settings are read, so their message wins.
|
||||
private (Plate[] Plates, IReadOnlyList<AutomaticCutOffPlan> Plans) Calculate(bool apply)
|
||||
{
|
||||
if (plateView.IsFillInProgress || isOperationBusy?.Invoke() == true)
|
||||
throw new InvalidOperationException("Wait for the current nesting or plate action to finish before creating cut-offs.");
|
||||
|
||||
if (plateView.IsDisposed || !ReferenceEquals(plateView.Plate, plate))
|
||||
throw new InvalidOperationException("The active plate changed. Close this dialog and try again.");
|
||||
|
||||
var plates = nest?.Plates.ToArray() ?? new[] { plate };
|
||||
if (!plates.Contains(plate))
|
||||
throw new InvalidOperationException("The active plate is no longer in this nest. Close this dialog and try again.");
|
||||
|
||||
var options = ParseOptions();
|
||||
var settings = WithHeadLock(plateView.CutOffSettings);
|
||||
var plans = apply
|
||||
? AutomaticCutOffBatch.Apply(plates, options, settings)
|
||||
: AutomaticCutOffBatch.Create(plates, options, settings);
|
||||
return (plates, plans);
|
||||
session.EnsureReady();
|
||||
return session.Calculate(ParseOptions(), WithHeadLock(plateView.CutOffSettings), apply);
|
||||
}
|
||||
|
||||
private AutomaticCutOffOptions ParseOptions()
|
||||
{
|
||||
if (!double.TryParse(spacingBox.Text, NumberStyles.Float, CultureInfo.CurrentCulture, out var spacing))
|
||||
throw new ArgumentException($"Enter a numeric spacing in {unit}.");
|
||||
if (!double.TryParse(minimumStripBox.Text, NumberStyles.Float, CultureInfo.CurrentCulture, out var minimumStrip))
|
||||
throw new ArgumentException($"Enter a numeric minimum strip in {unit}.");
|
||||
if (!double.TryParse(minimumTailBox.Text, NumberStyles.Float, CultureInfo.CurrentCulture, out var minimumTail))
|
||||
throw new ArgumentException($"Enter a numeric minimum tail length in {unit}.");
|
||||
|
||||
return new AutomaticCutOffOptions
|
||||
{
|
||||
Spacing = spacing,
|
||||
MinimumStripLength = minimumStrip,
|
||||
MinimumTailLength = minimumTail,
|
||||
KeepHorizontalRemnant = true,
|
||||
};
|
||||
}
|
||||
private AutomaticCutOffOptions ParseOptions() =>
|
||||
session.ParseOptions(spacingBox.Text, minimumStripBox.Text, minimumTailBox.Text);
|
||||
|
||||
// The view's settings with this dialog's head-lock choice; the view keeps its own until OK.
|
||||
private CutOffSettings WithHeadLock(CutOffSettings current)
|
||||
{
|
||||
var overcut = current.HeadLockOvercut;
|
||||
if (headLockBox.Checked && (!double.TryParse(headLockOvercutBox.Text, NumberStyles.Float, CultureInfo.CurrentCulture,
|
||||
out overcut) || !double.IsFinite(overcut) || overcut <= 0))
|
||||
throw new ArgumentException($"Enter a positive head-locked overcut in {unit}.");
|
||||
return new CutOffSettings
|
||||
{
|
||||
PartClearance = current.PartClearance,
|
||||
Overtravel = current.Overtravel,
|
||||
MinSegmentLength = current.MinSegmentLength,
|
||||
CutDirection = current.CutDirection,
|
||||
LockHeadHeight = headLockBox.Checked,
|
||||
HeadLockOvercut = overcut,
|
||||
};
|
||||
}
|
||||
private CutOffSettings WithHeadLock(CutOffSettings current) =>
|
||||
session.WithHeadLock(current, headLockBox.Checked, headLockOvercutBox.Text);
|
||||
|
||||
// New cut-offs from here on, including Plan Cutting's and the manual tool's, use the choice.
|
||||
private void KeepHeadLock()
|
||||
{
|
||||
var chosen = WithHeadLock(plateView.CutOffSettings);
|
||||
plateView.CutOffSettings.LockHeadHeight = chosen.LockHeadHeight;
|
||||
plateView.CutOffSettings.HeadLockOvercut = chosen.HeadLockOvercut;
|
||||
CutOffHeadLockDefaults.Save(chosen.LockHeadHeight, chosen.HeadLockOvercut, units);
|
||||
var saved = session.KeepHeadLock(plateView.CutOffSettings, WithHeadLock(plateView.CutOffSettings));
|
||||
CutOffHeadLockDefaults.Save(saved);
|
||||
}
|
||||
|
||||
private void HeadLockBox_CheckedChanged(object sender, EventArgs e)
|
||||
@@ -181,98 +130,53 @@ public partial class AutomaticCutOffForm : Form
|
||||
SettingsBox_TextChanged(sender, e);
|
||||
}
|
||||
|
||||
private string DiagnosticLine(AutomaticCutOffPlan plan) => string.Join(Environment.NewLine,
|
||||
plan.Diagnostics.Select(d =>
|
||||
$"{(d.IsBlocking ? "BLOCKING" : "Notice")} [{d.Code}]"
|
||||
+ (d.X.HasValue ? $" X = {SignedPosition(d.X.Value)}" : string.Empty)
|
||||
+ $": {d.Message}"));
|
||||
|
||||
private void SetStatus(string message, Color color)
|
||||
{
|
||||
statusLabel.Text = message;
|
||||
statusLabel.ForeColor = color;
|
||||
}
|
||||
|
||||
private static Color ColorOf(AutomaticCutOffTone tone) => tone switch
|
||||
{
|
||||
AutomaticCutOffTone.Ready => ReadyColor,
|
||||
AutomaticCutOffTone.Blocked => BlockedColor,
|
||||
AutomaticCutOffTone.Unchanged => SystemColors.GrayText,
|
||||
_ => NeutralColor,
|
||||
};
|
||||
|
||||
private void DisplayPlans(Plate[] plates, IReadOnlyList<AutomaticCutOffPlan> plans)
|
||||
{
|
||||
var currentIndex = Array.IndexOf(plates, plate);
|
||||
var plan = plans[currentIndex];
|
||||
occupiedLabel.Text = Measure(plan.OccupiedSpan);
|
||||
usedLabel.Text = Measure(plan.UsedSpan);
|
||||
separatorLabel.Text = plan.HasSeparatedTail ? SignedPosition(plan.TailSeparatorX.Value) : "none";
|
||||
tailLabel.Text = plan.HasSeparatedTail ? Measure(plan.TailLength) : "none";
|
||||
var saving = plan.FixedGridCutLength - plan.StripCutLength;
|
||||
stripCutsLabel.Text = $"Strip cuts: {Measure(plan.StripCutLength)} ("
|
||||
+ (saving > 0 ? $"{Measure(saving)} less than the fixed grid" :
|
||||
saving < 0 ? $"{Measure(-saving)} more than the fixed grid" : "same as the fixed grid")
|
||||
+ ")";
|
||||
|
||||
var blocked = plans.Any(p => p.HasBlockingDiagnostics);
|
||||
var definitionCount = plans.Sum(p => p.Definitions.Count);
|
||||
// Settings may be chosen even when this layout needs no new lines or is blocked:
|
||||
// Plan Cutting reports the blocked plate itself.
|
||||
applyButton.Enabled = settingsOnly || !blocked && definitionCount > 0;
|
||||
|
||||
var issues = new List<string>();
|
||||
for (var index = 0; index < plans.Count; index++)
|
||||
{
|
||||
var lines = DiagnosticLine(plans[index]);
|
||||
if (lines.Length == 0)
|
||||
continue;
|
||||
issues.Add(nest == null ? lines : $"Plate {index + 1}: {lines}");
|
||||
}
|
||||
diagnosticsBox.Text = issues.Count == 0 ? "No issues detected." : string.Join(Environment.NewLine, issues);
|
||||
|
||||
if (blocked)
|
||||
{
|
||||
var issueCount = plans.Sum(p => p.Diagnostics.Count(d => d.IsBlocking));
|
||||
SetStatus($"Blocked — {issueCount} blocking issue{(issueCount == 1 ? "" : "s")}; nothing will be applied.", BlockedColor);
|
||||
}
|
||||
else if (definitionCount == 0)
|
||||
{
|
||||
SetStatus("No new cut-offs to apply.", NeutralColor);
|
||||
}
|
||||
else if (nest == null)
|
||||
{
|
||||
SetStatus($"Ready — {definitionCount} new cut-off{(definitionCount == 1 ? "" : "s")} will be added.", ReadyColor);
|
||||
}
|
||||
else
|
||||
{
|
||||
var touched = plans.Count(p => p.Definitions.Count > 0);
|
||||
SetStatus($"Ready — {definitionCount} cut-off{(definitionCount == 1 ? "" : "s")} across {touched} of {plans.Count} plates. Unchanged plates stay untouched.", ReadyColor);
|
||||
}
|
||||
var summary = session.Summarize(plates, plans, settingsOnly);
|
||||
occupiedLabel.Text = summary.Occupied;
|
||||
usedLabel.Text = summary.Used;
|
||||
separatorLabel.Text = summary.Separator;
|
||||
tailLabel.Text = summary.Tail;
|
||||
stripCutsLabel.Text = summary.StripCuts;
|
||||
applyButton.Enabled = summary.CanApply;
|
||||
diagnosticsBox.Text = summary.Details;
|
||||
SetStatus(summary.Status, ColorOf(summary.StatusTone));
|
||||
|
||||
if (nest == null)
|
||||
return;
|
||||
|
||||
sheetLabel.Text = $"All {plates.Length} plates — preview shows plate {currentIndex + 1} "
|
||||
+ $"({Measure(plate.Size.Length)} length × {Measure(plate.Size.Width)} width)";
|
||||
FillPlateGrid(plans, currentIndex);
|
||||
sheetLabel.Text = summary.SheetText;
|
||||
FillPlateGrid(summary.Rows);
|
||||
}
|
||||
|
||||
private void FillPlateGrid(IReadOnlyList<AutomaticCutOffPlan> plans, int activeIndex)
|
||||
private void FillPlateGrid(IReadOnlyList<AutomaticCutOffPlateRow> rows)
|
||||
{
|
||||
plateGrid.BeginUpdate();
|
||||
plateGrid.Items.Clear();
|
||||
for (var index = 0; index < plans.Count; index++)
|
||||
foreach (var row in rows)
|
||||
{
|
||||
var plan = plans[index];
|
||||
var label = (index + 1).ToString(CultureInfo.CurrentCulture);
|
||||
if (index == activeIndex)
|
||||
label += " (active)";
|
||||
var row = new ListViewItem(label);
|
||||
row.SubItems.Add(plan.Definitions.Count == 0 ? "—" : plan.Definitions.Count.ToString(CultureInfo.CurrentCulture));
|
||||
row.SubItems.Add(Measure(plan.OccupiedSpan));
|
||||
row.SubItems.Add(Measure(plan.UsedSpan));
|
||||
row.SubItems.Add(plan.HasSeparatedTail ? Measure(plan.TailLength) : "—");
|
||||
row.SubItems.Add(plan.HasBlockingDiagnostics ? "Blocked" : plan.Definitions.Count > 0 ? "Ready" : "No change");
|
||||
if (plan.HasBlockingDiagnostics)
|
||||
row.ForeColor = BlockedColor;
|
||||
else if (plan.Definitions.Count > 0)
|
||||
row.ForeColor = ReadyColor;
|
||||
else
|
||||
row.ForeColor = SystemColors.GrayText;
|
||||
plateGrid.Items.Add(row);
|
||||
var item = new ListViewItem(row.Plate);
|
||||
item.SubItems.Add(row.CutOffs);
|
||||
item.SubItems.Add(row.Occupied);
|
||||
item.SubItems.Add(row.Used);
|
||||
item.SubItems.Add(row.Tail);
|
||||
item.SubItems.Add(row.Status);
|
||||
item.ForeColor = ColorOf(row.Tone);
|
||||
plateGrid.Items.Add(item);
|
||||
}
|
||||
plateGrid.EndUpdate();
|
||||
}
|
||||
@@ -298,14 +202,12 @@ public partial class AutomaticCutOffForm : Form
|
||||
|
||||
private void SpacingBox_TextChanged(object sender, EventArgs e)
|
||||
{
|
||||
if (!minimumStripEdited &&
|
||||
double.TryParse(spacingBox.Text, NumberStyles.Float, CultureInfo.CurrentCulture, out var spacing) &&
|
||||
double.IsFinite(spacing))
|
||||
if (!minimumStripEdited && AutomaticCutOffSession.MinimumStripFor(spacingBox.Text) is { } minimumStrip)
|
||||
{
|
||||
settingMinimumStrip = true;
|
||||
try
|
||||
{
|
||||
minimumStripBox.Text = (spacing / 2).ToString(CultureInfo.CurrentCulture);
|
||||
minimumStripBox.Text = minimumStrip;
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -341,7 +243,7 @@ public partial class AutomaticCutOffForm : Form
|
||||
var (plates, plans) = Calculate(apply: false);
|
||||
DisplayPlans(plates, plans);
|
||||
if (!plans.Any(p => p.HasBlockingDiagnostics))
|
||||
plateView.SetActiveParts(plans[Array.IndexOf(plates, plate)].PreviewParts.ToList());
|
||||
plateView.SetActiveParts(session.PreviewParts(plates, plans).ToList());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -376,18 +278,12 @@ public partial class AutomaticCutOffForm : Form
|
||||
try
|
||||
{
|
||||
// The batch service replans every plate before mutating any; never accept previews.
|
||||
Plate[] plates;
|
||||
IReadOnlyList<AutomaticCutOffPlan> plans;
|
||||
using (var change = plateView.BeginChange("Automatic Scrap Cutoffs"))
|
||||
{
|
||||
(plates, plans) = Calculate(apply: true);
|
||||
// A blocked batch changes nothing.
|
||||
if (!plans.Any(p => p.HasBlockingDiagnostics) && plans.Any(p => p.Definitions.Count > 0))
|
||||
change.MarkChanged();
|
||||
change.Complete();
|
||||
}
|
||||
// A blocked batch changes nothing.
|
||||
session.EnsureReady();
|
||||
var (plates, plans) = session.Apply(ParseOptions(), WithHeadLock(plateView.CutOffSettings),
|
||||
label => plateView.BeginChange(label));
|
||||
DisplayPlans(plates, plans);
|
||||
if (plans.Any(p => p.HasBlockingDiagnostics) || plans.All(p => p.Definitions.Count == 0))
|
||||
if (!AutomaticCutOffSession.Applied(plans))
|
||||
return;
|
||||
|
||||
KeepHeadLock();
|
||||
|
||||
@@ -132,3 +132,5 @@ The status bar refuses, changing nothing: a cut-off nothing crosses (delete it i
|
||||
## Implementation boundary
|
||||
|
||||
`AutomaticCutOffPlanner` in Core builds detached definitions and diagnostics without changing the input plate. `AutomaticCutOffOptions.MinimumTailLength` is a finite, nonnegative distance in model units; its programmatic default of zero preserves the previous behavior, while the desktop explicitly supplies its unit-aware 12-in / 304.8-mm default. `KeepHorizontalRemnant` defaults to false; both desktop entry points set it. The plan reports `HorizontalSeparatorY` and `HorizontalRemnantWidth`. `AutomaticCutOffBatch.Create` plans an ordered plate list, and `Apply` replans the complete list before mutating any plate, refusing a blocked batch and recovering touched cutoff state on exceptions. Callers must prevent concurrent edits throughout planning/apply. The desktop dialog renders the active plate's detached preview through `PlateView.SetActiveParts`; both menu commands apply through the shared batch service, which adds definitions to `Plate.CutOffs` and uses `Plate.RegenerateCutOffs`. It must not accept preview parts directly, because doing so would bypass cutoff persistence and regeneration. `RegenerateCutOffs` materializes one part per trimmed segment of each definition (`CutOff.SegmentPrograms`), each with its own place in `Plate.Parts`; `CutOffSegments.Of` finds a definition's segment parts and the span of the nominal line each stands for. Posts emit each segment part like any other part. There are no new nesting rules; the `.nest` format records each segment's sequence place.
|
||||
|
||||
Both desktop apps share the dialog's logic (`AutomaticCutOffSession`) and the manual edits (`CutOffEdits`, `CutOffDrag`, `SheetCutOffTool`, `TrimExtendCutOffTool`) in `OpenNest.Desktop`. The Avalonia app draws the dialog's detached preview as dashed preview lines, never as plate parts.
|
||||
Reference in new issue
Block a user