using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using OpenNest.CutOffs;
using OpenNest.Desktop;
using OpenNest.Undo;
namespace OpenNest.Forms;
/// How a status line or plate row of the automatic cut-off dialog is colored.
public enum AutomaticCutOffTone
{
/// Ordinary text.
Neutral,
/// Dark green: the plan is ready to apply.
Ready,
/// Dark red: blocked, or an error.
Blocked,
/// Gray: a plate the plan leaves unchanged.
Unchanged,
}
/// One plate's row in the All Plates table.
public sealed record AutomaticCutOffPlateRow(string Plate, string CutOffs, string Occupied, string Used,
string Tail, string Status, AutomaticCutOffTone Tone);
/// 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.
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 Rows);
///
/// 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
/// , 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).
///
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 isBusy;
private readonly Func shownPlate;
/// The active plate: the one previewed on the sheet.
/// The nest's units, for defaults and labels.
/// For All Plates, the nest whose every plate is planned; null for the active plate alone.
/// True while a nesting job or plate action forbids planning; null for never.
/// The plate the view shows now (null once it is gone); null to skip the check.
public AutomaticCutOffSession(Plate plate, Units units, Nest nest = null, Func isBusy = null,
Func 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; }
/// The nest for All Plates, or null.
public Nest Nest { get; }
public bool AllPlates => Nest != null;
/// The short unit name, "in" or "mm".
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:";
/// The sheet line before the first preview.
public string InitialSheetText => AllPlates
? $"All {Nest.Plates.Count} plates — active sheet shown below"
: $"Sheet: {Measure(Plate.Size.Length)} length × {Measure(Plate.Size.Width)} width";
/// 35 in, or 889 mm.
public string DefaultSpacingText => Units == Units.Millimeters ? "889" : "35";
/// 12 in, or 304.8 mm.
public string DefaultMinimumTailText =>
(Units == Units.Millimeters ? 304.8 : 12).ToString(CultureInfo.CurrentCulture);
///
/// The minimum strip that follows a spacing typed as until the
/// user edits the minimum strip: half the spacing; null when it is not a finite number.
///
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}";
/// The settings typed in the dialog; throws with the dialog's message.
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,
};
}
///
/// A copy of (the view's settings, which it keeps until Apply) with
/// the dialog's head-lock choice; a checked lock needs a positive overcut.
///
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,
};
}
///
/// 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 and returns what to
/// save between sessions.
///
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);
}
///
/// Plans every plate in scope (with , adds the definitions through
/// ). Throws
/// while busy or once the view shows another plate.
///
public (Plate[] Plates, IReadOnlyList 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);
}
///
/// The plates in scope, after checking planning may run: throws
/// 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.
///
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;
}
///
/// 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.
///
public (Plate[] Plates, IReadOnlyList Plans) Apply(AutomaticCutOffOptions options,
CutOffSettings settings, Func 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;
}
/// Whether Apply changed the plates: nothing blocked and something was added.
public static bool Applied(IReadOnlyList plans) =>
!plans.Any(p => p.HasBlockingDiagnostics) && plans.Any(p => p.Definitions.Count > 0);
/// The active plate's detached preview parts, for display only; none when anything is blocked.
public IReadOnlyList PreviewParts(Plate[] plates, IReadOnlyList plans) =>
plans.Any(p => p.HasBlockingDiagnostics)
? Array.Empty()
: plans[Array.IndexOf(plates, Plate)].PreviewParts.ToList();
/// One plan's issues and notices, one per line.
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}"));
///
/// What the dialog shows for planned ; with
/// (Plan Cutting's settings), the options may be chosen even when blocked or empty.
///
public AutomaticCutOffSummary Summarize(Plate[] plates, IReadOnlyList 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();
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());
}
private IReadOnlyList Rows(IReadOnlyList plans, int activeIndex)
{
var rows = new List();
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;
}
}