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;
///
/// 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 and rebuilds the
/// segments through ; preview parts are
/// never accepted. See docs/automatic-scrap-cutoffs.md, "Trim and extend".
///
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";
/// What the status bar says after a swap that has no notice of its own.
public const string SwappedStatus = "Swapped the through-cut";
///
/// The line Sheet Cut-Off adds at : along ,
/// with the new cut-off head-lock overcut of , and unless
/// , stopped at the first crossing cut-off from its start edge
/// (). The line is not added to the plate;
/// Notice says when stopping it turned its overcut off.
///
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);
}
/// Adds to the plate and rebuilds its cut-offs, as one "Add Cut-Off" step.
public static void Add(Plate plate, CutOff cutOff, CutOffSettings settings, Func 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();
}
///
/// 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
/// (). False, changing nothing, when the edit was
/// refused. If applying throws, the step is left incomplete, so it rolls back.
///
public static bool Apply(Plate plate, CutOffEdit edit, string label, CutOffSettings settings,
Func 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;
}
///
/// The junction of two cut-offs at , one running through and the
/// other stopping at it, for the Swap Through-Cut menu; null when there is none.
///
public static (CutOff Through, CutOff Stopper)? JunctionAt(Plate plate, Vector world, double tolerance) =>
plate?.CutOffs == null ? null : CutOffTrim.JunctionAt(plate, world, tolerance);
///
/// Swap Through-Cut: the stopped line runs through the junction and the through line stops
/// at it (), as one step. Returns whether it was applied and
/// the status line WinForms shows: the edit's notice or , or why
/// it was refused.
///
public static (bool Applied, string Status) Swap(Plate plate, CutOff through, CutOff stopper,
CutOffSettings settings, Func 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);
}
///
/// The stretches a trim or extend preview dashes: each changed cut-off's pieces it removes
/// (Added false) and adds (Added true), as lines in plate coordinates.
///
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));
}
}
///
/// 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 () 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 (); a plain click changes nothing.
///
public sealed class CutOffDrag
{
private readonly Plate plate;
private readonly CutOffSettings settings;
private readonly CutOffJoints joints;
private Dictionary 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);
}
/// Starts dragging , opening its undo step.
public static CutOffDrag Start(Plate plate, CutOff cutOff, CutOffSettings settings,
Func 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;
}
}
/// The cut-off being dragged.
public CutOff CutOff { get; }
/// Whether the drag has ended.
public bool IsEnded => scope == null;
/// Moves the cut-off's line through , taking its joined lines along.
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())
line.Regenerate(plate, settings, perimeterCache);
}
///
/// 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.
///
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();
}
}
}