feat(desktop): share the cut-off tools and automatic scrap cutoffs

CutOffEdits ports the WinForms manual cut-off edits, each one undo step
under its WinForms label: Add Cut-Off (a Sheet Cut-Off line, stopped at
the first crossing unless full length), Trim/Extend Cut-Off and Swap
Through-Cut, applied to the definitions in Plate.CutOffs, rebuilt with
RegenerateCutOffs and placed with PlateSequencing.PlaceCutOffs.
CutOffDrag is the Move Cut-Off drag, taking the joined lines along.

SheetCutOffTool (Space turns the axis, Tab toggles full length for the
view) and TrimExtendCutOffTool (Tab switches mode) are plate tools; the
Select tool now drags a pressed cut-off.

AutomaticCutOffSession holds the Automatic Scrap Cutoffs dialog's
logic: unit-aware defaults, parsing, planning and applying through
AutomaticCutOffBatch as one step, and the status, details and per-plate
table texts.

The WinForms actions, cut-off handler, junction menu and dialog now
delegate to it with unchanged behavior, except that releasing a
cut-off without moving it no longer rebuilds the cut-offs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Opus 5.5 committed 2026-11-30 18:44:49 -05:00
1 parent 416f8296a8
commit 2f375215fc
13 files changed
+1460 -253

No files matched your search

@@ -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 &gt; Automatic
/// Scrap Cutoffs for the active plate, Nest &gt; 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;
}
}
+234
View File
@@ -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();
}
}
}
+43 -4
View File
@@ -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 &gt; 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();
}
}
+5 -12
View File
@@ -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)
+5 -18
View File
@@ -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));
}
}
}
+14 -45
View File
@@ -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;
}
+7 -7
View File
@@ -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();
+1 -2
View File
@@ -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();
+61 -165
View File
@@ -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();