mirror of
https://github.com/ajisaacs/OpenNest.git
synced 2026-12-01 06:41:42 -05:00
PlateArrange ports the WinForms Arrange commands, each one undo step under its WinForms label: Align Left/Right/Top/Bottom, Horizontally and Vertically (lined up with the first selected part), Evenly Space Horizontally/Vertically, Center Parts, Join Common Line (facing edges up to four part spacings, at least an inch, apart), Remove Common Line and Cut Common Lines Twice/Once. It also decides which common-line commands the part right-click menu enables. Expand Spacing and Fix Spacing take a runner for the search, so a front end can run it off the UI thread behind a Cancel window; the step opens before the search (it moves the live parts when it finishes), and a canceled run moves nothing and records nothing. They return the parts to redraw and the status line WinForms shows. The WinForms plate view, selection manager and part menu now delegate to it with unchanged behavior; Center Parts keeps its own loop, which moves the view's layout parts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
370 lines
16 KiB
C#
370 lines
16 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using OpenNest.CommonLines;
|
|
using OpenNest.CutOffs;
|
|
using OpenNest.Engine.Fill;
|
|
using OpenNest.Undo;
|
|
|
|
namespace OpenNest.Desktop.Interaction;
|
|
|
|
/// <summary>
|
|
/// The Plate > Arrange commands, toolkit-neutral: align, evenly space and center parts, join
|
|
/// and remove common lines (see docs/common-line-cutting.md), cut them twice, Expand Spacing and
|
|
/// Fix Spacing. Each is one undo step under the WinForms label, opened through
|
|
/// <c>beginChange</c>; the caller redraws the parts it reports moved.
|
|
/// </summary>
|
|
public static class PlateArrange
|
|
{
|
|
/// <summary>
|
|
/// Aligns or evenly spaces <paramref name="selected"/>: an alignment lines them up with
|
|
/// <paramref name="fixedPart"/>. False, opening no step, without a selection; an unknown
|
|
/// <paramref name="type"/> records nothing.
|
|
/// </summary>
|
|
public static bool Align(IReadOnlyList<Part> selected, Part fixedPart, AlignType type,
|
|
Func<string, ChangeScope> beginChange)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(beginChange);
|
|
if (selected == null || selected.Count == 0)
|
|
return false;
|
|
|
|
using var change = beginChange("Align");
|
|
var parts = selected.ToList();
|
|
switch (type)
|
|
{
|
|
case AlignType.Bottom:
|
|
change.MarkChanged();
|
|
OpenNest.Align.Bottom(fixedPart, parts);
|
|
break;
|
|
case AlignType.Horizontally:
|
|
change.MarkChanged();
|
|
OpenNest.Align.Horizontally(fixedPart, parts);
|
|
break;
|
|
case AlignType.Left:
|
|
change.MarkChanged();
|
|
OpenNest.Align.Left(fixedPart, parts);
|
|
break;
|
|
case AlignType.Right:
|
|
change.MarkChanged();
|
|
OpenNest.Align.Right(fixedPart, parts);
|
|
break;
|
|
case AlignType.Top:
|
|
change.MarkChanged();
|
|
OpenNest.Align.Top(fixedPart, parts);
|
|
break;
|
|
case AlignType.Vertically:
|
|
change.MarkChanged();
|
|
OpenNest.Align.Vertically(fixedPart, parts);
|
|
break;
|
|
case AlignType.EvenlySpaceHorizontally:
|
|
change.MarkChanged();
|
|
OpenNest.Align.EvenlyDistributeHorizontally(parts);
|
|
break;
|
|
case AlignType.EvenlySpaceVertically:
|
|
change.MarkChanged();
|
|
OpenNest.Align.EvenlyDistributeVertically(parts);
|
|
break;
|
|
default:
|
|
// An unknown alignment moves nothing; completing records nothing either.
|
|
change.Complete();
|
|
return false;
|
|
}
|
|
|
|
change.Complete();
|
|
return true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Center Parts: moves every part on the plate so their bounds center in its work area. False,
|
|
/// opening no step, without a plate or parts; a layout already centered records nothing.
|
|
/// </summary>
|
|
public static bool CenterParts(Plate plate, Func<string, ChangeScope> beginChange)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(beginChange);
|
|
if (plate == null || plate.Parts.Count == 0)
|
|
return false;
|
|
|
|
var offset = plate.OffsetToCenterPartsInWorkArea();
|
|
using var change = beginChange("Center Parts");
|
|
if (offset.X != 0 || offset.Y != 0)
|
|
change.MarkChanged();
|
|
foreach (var part in plate.Parts)
|
|
part.Offset(offset);
|
|
change.Complete();
|
|
return true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// How far apart facing edges may start and still be joined: a few part spacings, at least
|
|
/// an inch.
|
|
/// </summary>
|
|
public static double JoinGap(Plate plate) => System.Math.Max(1.0, 4 * plate.PartSpacing);
|
|
|
|
/// <summary>
|
|
/// Join Common Line: slides <paramref name="selected"/> one <paramref name="kerf"/> apart
|
|
/// along their facing straight edges and groups them; parts already in a group move with it.
|
|
/// Nothing changes, and no step is recorded, when the join fails.
|
|
/// </summary>
|
|
public static CommonLineJoinResult JoinCommonLine(Plate plate, IReadOnlyList<Part> selected, double kerf,
|
|
Func<string, ChangeScope> beginChange)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(plate);
|
|
ArgumentNullException.ThrowIfNull(beginChange);
|
|
using var change = beginChange("Join Common Line");
|
|
var result = CommonLineJoiner.Join(plate, selected ?? Array.Empty<Part>(), kerf, JoinGap(plate));
|
|
if (!result.Succeeded)
|
|
return result;
|
|
change.MarkChanged();
|
|
change.Complete();
|
|
return result;
|
|
}
|
|
|
|
/// <summary>The notice shown when none of the selected parts is in a common-line group.</summary>
|
|
public const string NoCommonLineNotice = "None of the selected parts share a common line.";
|
|
|
|
/// <summary>
|
|
/// Remove Common Line: removes the common-line groups of <paramref name="selected"/>; the
|
|
/// parts stay where they are. False, recording nothing, when none is in a group.
|
|
/// </summary>
|
|
public static bool RemoveCommonLines(Plate plate, IReadOnlyList<Part> selected,
|
|
Func<string, ChangeScope> beginChange)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(beginChange);
|
|
if (plate == null || selected == null)
|
|
return false;
|
|
var groups = selected.Select(plate.CommonLineGroupOf).Where(group => group != null).Distinct().ToList();
|
|
if (groups.Count == 0)
|
|
return false;
|
|
using var change = beginChange("Remove Common Line");
|
|
change.MarkChanged();
|
|
foreach (var group in groups)
|
|
plate.CommonLines.Remove(group);
|
|
change.Complete();
|
|
return true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Cut Common Lines Twice: sets <see cref="Plate.CutCommonLinesTwice"/> as an undoable edit.
|
|
/// False when nothing changed.
|
|
/// </summary>
|
|
public static bool SetCutCommonLinesTwice(Plate plate, bool twice, Func<string, ChangeScope> beginChange)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(beginChange);
|
|
if (plate == null || plate.CutCommonLinesTwice == twice)
|
|
return false;
|
|
using var change = beginChange(twice ? "Cut Common Lines Twice" : "Cut Common Lines Once");
|
|
change.MarkChanged();
|
|
plate.CutCommonLinesTwice = twice;
|
|
change.Complete();
|
|
return true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Which common-line commands the part right-click menu enables for <paramref name="selected"/>:
|
|
/// Join needs two units to bring together (two loose parts, or a group and anything outside
|
|
/// it), Remove a part in a group.
|
|
/// </summary>
|
|
public static (bool CanJoin, bool CanRemove) CommonLineCommands(Plate plate, IReadOnlyList<Part> selected)
|
|
{
|
|
if (plate == null || selected == null)
|
|
return (false, false);
|
|
var groups = selected.Select(plate.CommonLineGroupOf).ToList();
|
|
var units = groups.Where(g => g != null).Distinct().Count() + groups.Count(g => g == null);
|
|
return (units >= 2, groups.Any(g => g != null));
|
|
}
|
|
|
|
/// <summary>The notice shown when Expand Spacing has fewer than two parts to move.</summary>
|
|
public const string ExpandNeedsTwoPartsNotice = "Select at least two parts on the plate to expand.";
|
|
|
|
/// <summary>The notice shown when a nest or fill could still add parts to the plate.</summary>
|
|
public static string BusyNotice(string command) =>
|
|
$"Finish or cancel the current nesting or fill before {command}.";
|
|
|
|
/// <summary>
|
|
/// What a spacing command did: whether it ran, the parts it moved (redraw them) and the status
|
|
/// line to show.
|
|
/// </summary>
|
|
public sealed record SpacingOutcome<TResult>(TResult Result, IReadOnlyList<Part> MovedParts, string Status);
|
|
|
|
/// <summary>
|
|
/// Expand Spacing: pushes <paramref name="selected"/> apart as far as the plate allows
|
|
/// (<see cref="Expander"/>). <paramref name="run"/> executes the search, off the UI thread
|
|
/// behind a Cancel window, and may cancel it; a canceled run moves no part and records
|
|
/// nothing. Null, opening no step, with fewer than two parts.
|
|
/// </summary>
|
|
public static async Task<SpacingOutcome<Expander.Result>> ExpandSpacingAsync(Plate plate,
|
|
IReadOnlyList<Part> selected, CutOffSettings cutOffSettings, Func<string, ChangeScope> beginChange,
|
|
Func<Func<CancellationToken, Expander.Result>, Task<Expander.Result>> run)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(beginChange);
|
|
ArgumentNullException.ThrowIfNull(run);
|
|
var movingParts = selected?.ToList() ?? new List<Part>();
|
|
if (plate == null || movingParts.Count < 2)
|
|
return null;
|
|
|
|
Expander.Result Work(CancellationToken token) => Expander.Expand(movingParts, plate, null, token);
|
|
|
|
// Opened before the search: it moves the live parts once it finishes.
|
|
using var change = beginChange("Expand Spacing");
|
|
var result = await run(Work);
|
|
|
|
if (result.Canceled)
|
|
{
|
|
change.Complete();
|
|
return new(result, Array.Empty<Part>(), "Expand Spacing canceled - no parts were moved");
|
|
}
|
|
|
|
change.MarkChanged();
|
|
if (plate.CutOffs.Count > 0)
|
|
plate.RegenerateCutOffs(cutOffSettings);
|
|
|
|
var status = result.KeptPattern
|
|
? (result.PatternMoved
|
|
? $"Spread the repeating pattern - smallest gap {result.AchievedSpacing:0.###}"
|
|
: $"The repeating pattern has no room to spread - smallest gap {result.AchievedSpacing:0.###}")
|
|
: $"Expanded spacing to {result.AchievedSpacing:0.###}"
|
|
+ (result.Violations.Count > 0 ? $" - {result.Violations.Count} blocked pairs" : "");
|
|
|
|
change.Complete();
|
|
return new(result, movingParts, status);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Fix Spacing: pushes apart only the parts the overlap check flags, by just enough to reach
|
|
/// the part spacing (<see cref="SpacingFixer"/>). With parts selected, only flagged pairs
|
|
/// touching the selection are fixed. <paramref name="run"/> executes the search as for
|
|
/// <see cref="ExpandSpacingAsync"/>; a canceled run moves no part. Null without a plate.
|
|
/// </summary>
|
|
public static async Task<SpacingOutcome<SpacingFixer.Result>> FixSpacingAsync(Plate plate,
|
|
IReadOnlyList<Part> selected, CutOffSettings cutOffSettings, Func<string, ChangeScope> beginChange,
|
|
Func<Func<CancellationToken, SpacingFixer.Result>, Task<SpacingFixer.Result>> run)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(beginChange);
|
|
ArgumentNullException.ThrowIfNull(run);
|
|
if (plate == null)
|
|
return null;
|
|
var scope = selected?.ToList() ?? new List<Part>();
|
|
SpacingFixer.Result Work(CancellationToken token) => SpacingFixer.Fix(plate, scope, token);
|
|
|
|
using var change = beginChange("Fix Spacing");
|
|
var result = await run(Work);
|
|
var where = scope.Count > 0 ? " among the selected parts" : "";
|
|
IReadOnlyList<Part> moved = Array.Empty<Part>();
|
|
string status;
|
|
|
|
if (result.Canceled)
|
|
status = "Fix Spacing canceled - no parts were moved";
|
|
else if (result.FlaggedPairs == 0)
|
|
status = $"No overlapping or too-close parts{where} to fix";
|
|
else if (result.MovedParts.Count == 0)
|
|
status = $"Fix Spacing found no room to clear the {Pairs(result.FlaggedPairs)}{where}";
|
|
else
|
|
{
|
|
change.MarkChanged();
|
|
moved = result.MovedParts;
|
|
if (plate.CutOffs.Count > 0)
|
|
plate.RegenerateCutOffs(cutOffSettings);
|
|
var fixedPairs = result.FlaggedPairs - result.RemainingPairs;
|
|
status = $"Fixed {fixedPairs} of {Pairs(result.FlaggedPairs)} - moved {result.MovedParts.Count} "
|
|
+ $"part{(result.MovedParts.Count == 1 ? "" : "s")}, largest move {result.LargestMove:0.####}"
|
|
+ (result.TurnedParts.Count > 0
|
|
? $", {result.TurnedParts.Count} tilted up to {OpenNest.Math.Angle.ToDegrees(result.LargestTurn):0.##} deg"
|
|
: "")
|
|
+ (result.RemainingPairs > 0 ? $" - {Pairs(result.RemainingPairs)} left" : "");
|
|
}
|
|
|
|
change.Complete();
|
|
return new(result, moved, status);
|
|
|
|
static string Pairs(int count) => $"{count} flagged pair{(count == 1 ? "" : "s")}";
|
|
}
|
|
|
|
/// <summary>
|
|
/// The selected parts still on <paramref name="host"/>'s plate, in selection order; null
|
|
/// without a plate or while its edits are locked (<see cref="IPlateToolHost.EditsLocked"/>).
|
|
/// </summary>
|
|
public static IReadOnlyList<Part> EditableSelection(IPlateToolHost host)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(host);
|
|
if (host.Plate == null || host.EditsLocked)
|
|
return null;
|
|
host.Selection.Prune();
|
|
return host.Selection.Parts.ToList();
|
|
}
|
|
|
|
/// <summary>
|
|
/// <see cref="Align(IReadOnlyList{Part}, Part, AlignType, Func{string, ChangeScope})"/> on the
|
|
/// host's selection, lined up with its first selected part.
|
|
/// </summary>
|
|
public static bool Align(IPlateToolHost host, AlignType type)
|
|
{
|
|
if (EditableSelection(host) is not { Count: > 0 } parts)
|
|
return false;
|
|
var aligned = Align(parts, parts[0], type, label => host.BeginChange(label));
|
|
if (aligned)
|
|
host.Invalidate();
|
|
return aligned;
|
|
}
|
|
|
|
/// <summary><see cref="CenterParts(Plate, Func{string, ChangeScope})"/> on the host's plate.</summary>
|
|
public static bool CenterParts(IPlateToolHost host)
|
|
{
|
|
if (EditableSelection(host) == null)
|
|
return false;
|
|
var centered = CenterParts(host.Plate, label => host.BeginChange(label));
|
|
if (centered)
|
|
host.Invalidate();
|
|
return centered;
|
|
}
|
|
|
|
/// <summary>
|
|
/// <see cref="JoinCommonLine(Plate, IReadOnlyList{Part}, double, Func{string, ChangeScope})"/>
|
|
/// on the host's selection; null while edits are locked.
|
|
/// </summary>
|
|
public static CommonLineJoinResult JoinCommonLine(IPlateToolHost host, double kerf)
|
|
{
|
|
if (EditableSelection(host) is not { } parts)
|
|
return null;
|
|
var result = JoinCommonLine(host.Plate, parts, kerf, label => host.BeginChange(label));
|
|
if (result.Succeeded)
|
|
host.Invalidate();
|
|
return result;
|
|
}
|
|
|
|
/// <summary>
|
|
/// <see cref="RemoveCommonLines(Plate, IReadOnlyList{Part}, Func{string, ChangeScope})"/> on
|
|
/// the host's selection; null while edits are locked.
|
|
/// </summary>
|
|
public static bool? RemoveCommonLines(IPlateToolHost host)
|
|
{
|
|
if (EditableSelection(host) is not { } parts)
|
|
return null;
|
|
var removed = RemoveCommonLines(host.Plate, parts, label => host.BeginChange(label));
|
|
if (removed)
|
|
host.Invalidate();
|
|
return removed;
|
|
}
|
|
|
|
/// <summary>Toggles the host plate's <see cref="Plate.CutCommonLinesTwice"/>.</summary>
|
|
public static bool ToggleCutCommonLinesTwice(IPlateToolHost host)
|
|
{
|
|
if (EditableSelection(host) == null)
|
|
return false;
|
|
var plate = host.Plate;
|
|
var changed = SetCutCommonLinesTwice(plate, !plate.CutCommonLinesTwice, label => host.BeginChange(label));
|
|
if (changed)
|
|
host.Invalidate();
|
|
return changed;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Runs a spacing command synchronously, as the WinForms Cancel window does: the task the
|
|
/// command returns has completed once <paramref name="run"/> returns.
|
|
/// </summary>
|
|
public static Func<Func<CancellationToken, T>, Task<T>> Synchronous<T>(
|
|
Func<Func<CancellationToken, T>, T> run) =>
|
|
work => Task.FromResult(run != null ? run(work) : work(CancellationToken.None));
|
|
}
|