Files
OpenNest/OpenNest.Desktop/Forms/AutomaticCutOffSession.cs
T
ajandClaude Opus 5.5 2f375215fc 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>
2026-11-30 18:44:49 -05:00

357 lines
16 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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;
}
}