refactor: share duplicated fill, cache, settings and toggle code

- fill_plate and fill_area share one MCP fill helper
- FillLinear uses FillHelpers.HasOverlappingParts
- BestFitCache and FillResultCache entries derive from DrawingCacheEntry
- NestDefaults and ClampSettings read through SettingsFile.TryReadText
- MainForm view toggles share one ToggleView handler

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Opus 5.5 committed 2026-11-29 09:47:29 -05:00
1 parent 4b61d249c0
commit d77693aaff
10 files changed
+178 -217

No files matched your search

+2 -13
View File
@@ -206,20 +206,9 @@ public sealed class ClampSettings
/// </summary>
public static ClampSettings Load(string path, out ClampSettingsStatus status)
{
if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
if (!SettingsFile.TryReadText(path, out var json, out var missing))
{
status = ClampSettingsStatus.Missing;
return Fallback;
}
string json;
try
{
json = File.ReadAllText(path);
}
catch (Exception ex) when (SettingsFile.IsUnreadableFile(ex))
{
status = ClampSettingsStatus.Invalid;
status = missing ? ClampSettingsStatus.Missing : ClampSettingsStatus.Invalid;
return Fallback;
}
return Parse(json, out status);
+4 -15
View File
@@ -102,22 +102,11 @@ public sealed class NestDefaults
out NestDefaultsStatus status
)
{
if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
// A file that exists but cannot be read (locked, access-denied)
// must never block creating a nest.
if (!SettingsFile.TryReadText(path, out var json, out var missing))
{
status = NestDefaultsStatus.Missing;
return WithUnits(Fallback, fallbackUnits);
}
string json;
try
{
json = File.ReadAllText(path);
}
catch (Exception ex) when (SettingsFile.IsUnreadableFile(ex))
{
// A file that exists but cannot be read (locked, access-denied)
// must never block creating a nest.
status = NestDefaultsStatus.Invalid;
status = missing ? NestDefaultsStatus.Missing : NestDefaultsStatus.Invalid;
return WithUnits(Fallback, fallbackUnits);
}
return Parse(json, fallbackUnits, out status);
+27
View File
@@ -1,3 +1,4 @@
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
namespace OpenNest.Data;
@@ -51,6 +52,32 @@ internal static class SettingsFile
}
}
/// <summary>
/// Reads the file's text. Returns false when the file is missing (<paramref name="missing"/>
/// true) or exists but cannot be read, for example locked or access-denied.
/// </summary>
public static bool TryReadText(
string path,
[NotNullWhen(true)] out string? text,
out bool missing
)
{
text = null;
missing = string.IsNullOrWhiteSpace(path) || !File.Exists(path);
if (missing)
return false;
try
{
text = File.ReadAllText(path);
return true;
}
catch (Exception ex) when (IsUnreadableFile(ex))
{
return false;
}
}
public static bool IsUnreadableFile(Exception ex) =>
ex
is JsonException
+9 -29
View File
@@ -227,23 +227,13 @@ namespace OpenNest.Engine.BestFit
}
}
private static Entry GetEntry(Drawing drawing)
{
var source = CanonicalFrame.SourceOf(drawing);
if (_entries.TryGetValue(source, out var entry) && entry.IsCurrentFor(source))
return entry;
lock (_entriesLock)
{
if (_entries.TryGetValue(source, out entry) && entry.IsCurrentFor(source))
return entry;
entry = new Entry(source);
_entries.AddOrUpdate(source, entry);
return entry;
}
}
private static Entry GetEntry(Drawing drawing) =>
DrawingCacheEntry.GetOrCreate(
_entries,
_entriesLock,
CanonicalFrame.SourceOf(drawing),
static source => new Entry(source)
);
private static List<BestFitResult> GetCandidates(Entry entry, Drawing drawing, double spacing)
{
@@ -407,11 +397,8 @@ namespace OpenNest.Engine.BestFit
return copy;
}
private sealed class Entry
private sealed class Entry : DrawingCacheEntry
{
private readonly CNC.Program _program;
private readonly double _sourceAngle;
public readonly ConcurrentDictionary<double, Lazy<List<BestFitResult>>> Unfiltered = new();
public readonly ConcurrentDictionary<
@@ -420,14 +407,7 @@ namespace OpenNest.Engine.BestFit
> Filtered = new();
public Entry(Drawing source)
{
_program = source.Program;
_sourceAngle = source.Source?.Angle ?? 0.0;
}
public bool IsCurrentFor(Drawing source) =>
ReferenceEquals(_program, source.Program)
&& _sourceAngle == (source.Source?.Angle ?? 0.0);
: base(source) { }
}
/// <summary>The geometry a drawing was reconstructed from, and the program built then.</summary>
+51
View File
@@ -0,0 +1,51 @@
using System;
using System.Runtime.CompilerServices;
namespace OpenNest.Engine
{
/// <summary>
/// A per-drawing cache entry that is current while the drawing keeps the program
/// reference and source angle it was built from.
/// </summary>
internal abstract class DrawingCacheEntry
{
private readonly CNC.Program program;
private readonly double sourceAngle;
protected DrawingCacheEntry(Drawing source)
{
program = source.Program;
sourceAngle = source.Source?.Angle ?? 0.0;
}
public bool IsCurrentFor(Drawing source) =>
ReferenceEquals(program, source.Program)
&& sourceAngle == (source.Source?.Angle ?? 0.0);
/// <summary>
/// Returns the current entry for <paramref name="source"/>, replacing a missing or
/// stale one under <paramref name="gate"/>.
/// </summary>
public static TEntry GetOrCreate<TEntry>(
ConditionalWeakTable<Drawing, TEntry> entries,
object gate,
Drawing source,
Func<Drawing, TEntry> create
)
where TEntry : DrawingCacheEntry
{
if (entries.TryGetValue(source, out var entry) && entry.IsCurrentFor(source))
return entry;
lock (gate)
{
if (entries.TryGetValue(source, out entry) && entry.IsCurrentFor(source))
return entry;
entry = create(source);
entries.AddOrUpdate(source, entry);
return entry;
}
}
}
}
+1 -33
View File
@@ -504,39 +504,7 @@ namespace OpenNest.Engine.Fill
List<Part> parts,
out int overlapA,
out int overlapB
)
{
var checker = new PartOverlapChecker();
for (var i = 0; i < parts.Count; i++)
{
var b1 = parts[i].BoundingBox;
for (var j = i + 1; j < parts.Count; j++)
{
var b2 = parts[j].BoundingBox;
var overlapX =
System.Math.Min(b1.Right, b2.Right) - System.Math.Max(b1.Left, b2.Left);
var overlapY =
System.Math.Min(b1.Top, b2.Top) - System.Math.Max(b1.Bottom, b2.Bottom);
if (overlapX <= Tolerance.Epsilon || overlapY <= Tolerance.Epsilon)
continue;
if (checker.Overlaps(parts[i], parts[j]))
{
overlapA = i;
overlapB = j;
return true;
}
}
}
overlapA = -1;
overlapB = -1;
return false;
}
) => Strategies.FillHelpers.HasOverlappingParts(parts, out overlapA, out overlapB);
/// <summary>
/// Creates a seed pattern containing a single part positioned at the work area origin.
+12 -29
View File
@@ -85,38 +85,20 @@ public static class FillResultCache
}
}
private static Entry GetEntry(Drawing source)
private static Entry GetEntry(Drawing source) =>
DrawingCacheEntry.GetOrCreate(
_entries,
_entriesLock,
source,
static drawing => new Entry(drawing)
);
private sealed class Entry : DrawingCacheEntry
{
if (_entries.TryGetValue(source, out var entry) && entry.IsCurrentFor(source))
return entry;
lock (_entriesLock)
{
if (_entries.TryGetValue(source, out entry) && entry.IsCurrentFor(source))
return entry;
entry = new Entry(source);
_entries.AddOrUpdate(source, entry);
return entry;
}
}
private sealed class Entry
{
private readonly CNC.Program program;
private readonly double sourceAngle;
public readonly ConcurrentDictionary<CacheKey, List<Part>> Results = new();
public Entry(Drawing source)
{
program = source.Program;
sourceAngle = source.Source?.Angle ?? 0.0;
}
public bool IsCurrentFor(Drawing source) =>
ReferenceEquals(program, source.Program)
&& sourceAngle == (source.Source?.Angle ?? 0.0);
: base(source) { }
}
private readonly record struct CacheKey(bool IsCanonical, double Width, double Height, double Spacing)
@@ -127,6 +109,7 @@ public static class FillResultCache
System.Math.Round(width, 2),
System.Math.Round(height, 2),
spacing
) { }
)
{ }
}
}
+18 -1
View File
@@ -222,7 +222,18 @@ namespace OpenNest.Engine.Strategies
/// Checks if any pair of parts geometrically overlap. Uses bounding box
/// pre-filtering for performance, then falls back to shape intersection.
/// </summary>
internal static bool HasOverlappingParts(List<Part> parts)
internal static bool HasOverlappingParts(List<Part> parts) =>
HasOverlappingParts(parts, out _, out _);
/// <summary>
/// Finds the first pair of overlapping parts, reporting their indices
/// (or -1 when none overlap).
/// </summary>
internal static bool HasOverlappingParts(
List<Part> parts,
out int overlapA,
out int overlapB
)
{
var checker = new PartOverlapChecker();
@@ -243,10 +254,16 @@ namespace OpenNest.Engine.Strategies
continue;
if (checker.Overlaps(parts[i], parts[j]))
{
overlapA = i;
overlapB = j;
return true;
}
}
}
overlapA = -1;
overlapB = -1;
return false;
}
}
+29 -52
View File
@@ -54,50 +54,15 @@ namespace OpenNest.Mcp.Tools
[Description("Maximum quantity to place (0 = unlimited)")] int quantity = 0,
[Description(FillStrategies)]
string engine = null
)
{
var plate = _session.GetPlate(plateIndex);
if (plate == null)
return $"Error: plate {plateIndex} not found";
if (_session.IsConsumedStockPlate(plate))
return "Error: this empty entry was consumed by a repeated layout; select or create an unused stock plate. Nothing committed.";
var drawing = _session.GetDrawing(drawingName);
if (drawing == null)
return $"Error: drawing '{drawingName}' not found";
var strategy = ResolveStrategy(engine);
if (strategy == null)
return EngineError(engine);
if (OutlinedSheetRefusal(plate) is { } refusal)
return refusal;
var countBefore = plate.Parts.Count;
var item = new NestItem { Drawing = drawing, Quantity = quantity };
var parts = PlateFillService.FillItem(
strategy,
plate,
item,
plate.WorkArea(),
null,
CancellationToken.None
) =>
FillWithDrawing(
plateIndex,
drawingName,
quantity,
engine,
plate => plate.WorkArea(),
$"plate {plateIndex}"
);
plate.Parts.AddRange(parts);
var success = parts.Count > 0;
var countAfter = plate.Parts.Count;
var added = countAfter - countBefore;
var sb = new StringBuilder();
sb.AppendLine(
$"Fill plate {plateIndex} with '{drawingName}' ({strategy}): {(success ? "success" : "failed")}"
);
sb.AppendLine($" Parts added: {added}");
sb.AppendLine($" Total parts: {countAfter}");
sb.AppendLine($" Utilization: {plate.Utilization():P1}");
return sb.ToString();
}
[McpServerTool(Name = "fill_area")]
[Description("Fill a specific rectangular area on a plate with a single drawing.")]
@@ -111,6 +76,23 @@ namespace OpenNest.Mcp.Tools
[Description("Maximum quantity to place (0 = unlimited)")] int quantity = 0,
[Description(FillStrategies)]
string engine = null
) =>
FillWithDrawing(
plateIndex,
drawingName,
quantity,
engine,
_ => new Box(x, y, width, length),
$"area ({x:F1},{y:F1} {width:F1}x{length:F1}) on plate {plateIndex}"
);
private string FillWithDrawing(
int plateIndex,
string drawingName,
int quantity,
string engine,
Func<Plate, Box> area,
string target
)
{
var plate = _session.GetPlate(plateIndex);
@@ -131,27 +113,22 @@ namespace OpenNest.Mcp.Tools
var countBefore = plate.Parts.Count;
var item = new NestItem { Drawing = drawing, Quantity = quantity };
var area = new Box(x, y, width, length);
var parts = PlateFillService.FillItem(
strategy,
plate,
item,
area,
area(plate),
null,
CancellationToken.None
);
plate.Parts.AddRange(parts);
var success = parts.Count > 0;
var countAfter = plate.Parts.Count;
var added = countAfter - countBefore;
var sb = new StringBuilder();
sb.AppendLine(
$"Fill area ({x:F1},{y:F1} {width:F1}x{length:F1}) on plate {plateIndex} with '{drawingName}' ({strategy}): {(success ? "success" : "failed")}"
$"Fill {target} with '{drawingName}' ({strategy}): {(parts.Count > 0 ? "success" : "failed")}"
);
sb.AppendLine($" Parts added: {added}");
sb.AppendLine($" Total parts: {countAfter}");
sb.AppendLine($" Parts added: {plate.Parts.Count - countBefore}");
sb.AppendLine($" Total parts: {plate.Parts.Count}");
sb.AppendLine($" Utilization: {plate.Utilization():P1}");
return sb.ToString();
+25 -45
View File
@@ -91,60 +91,40 @@ namespace OpenNest.Forms
activeForm.OverlapDisplay = OverlapDisplayMode.Both;
}
private void ToggleDrawRapids_Click(object sender, EventArgs e)
{
if (activeForm == null)
return;
activeForm.ToggleRapid();
mnuViewDrawRapids.Checked = activeForm.PlateView.DrawRapid;
}
private void ToggleDrawRapids_Click(object sender, EventArgs e) =>
ToggleView(mnuViewDrawRapids, f => f.ToggleRapid(), v => v.DrawRapid);
private void ToggleDrawPiercePoints_Click(object sender, EventArgs e)
{
if (activeForm == null)
return;
activeForm.TogglePiercePoints();
mnuViewDrawPiercePoints.Checked = activeForm.PlateView.DrawPiercePoints;
}
private void ToggleDrawPiercePoints_Click(object sender, EventArgs e) =>
ToggleView(mnuViewDrawPiercePoints, f => f.TogglePiercePoints(), v => v.DrawPiercePoints);
private void ToggleDrawBounds_Click(object sender, EventArgs e)
{
if (activeForm == null)
return;
activeForm.ToggleDrawBounds();
mnuViewDrawBounds.Checked = activeForm.PlateView.DrawBounds;
}
private void ToggleDrawBounds_Click(object sender, EventArgs e) =>
ToggleView(mnuViewDrawBounds, f => f.ToggleDrawBounds(), v => v.DrawBounds);
private void ToggleDrawOffset_Click(object sender, EventArgs e)
{
if (activeForm == null)
return;
activeForm.ToggleDrawOffset();
mnuViewDrawOffset.Checked = activeForm.PlateView.DrawOffset;
}
private void ToggleDrawOffset_Click(object sender, EventArgs e) =>
ToggleView(mnuViewDrawOffset, f => f.ToggleDrawOffset(), v => v.DrawOffset);
private void ToggleDrawCutDirection_Click(object sender, EventArgs e)
{
if (activeForm == null)
return;
activeForm.ToggleCutDirection();
mnuViewDrawCutDirection.Checked = activeForm.PlateView.DrawCutDirection;
}
private void ToggleDrawCutDirection_Click(object sender, EventArgs e) =>
ToggleView(mnuViewDrawCutDirection, f => f.ToggleCutDirection(), v => v.DrawCutDirection);
private void ToggleDrawSupport_Click(object sender, EventArgs e)
{
if (activeForm == null)
return;
activeForm.ToggleSupport();
mnuViewDrawSupport.Checked = activeForm.PlateView.DrawSupport;
}
private void ToggleDrawSupport_Click(object sender, EventArgs e) =>
ToggleView(mnuViewDrawSupport, f => f.ToggleSupport(), v => v.DrawSupport);
private void ToggleShowBendLines_Click(object sender, EventArgs e)
private void ToggleShowBendLines_Click(object sender, EventArgs e) =>
ToggleView(mnuViewShowBendLines, f => f.ToggleBendLines(), v => v.ShowBendLines);
/// <summary>
/// Flips a plate-view display option on the active nest and checks its menu item to match.
/// </summary>
private void ToggleView(
System.Windows.Forms.ToolStripMenuItem item,
Action<EditNestForm> toggle,
Func<Controls.PlateView, bool> isOn
)
{
if (activeForm == null)
return;
activeForm.ToggleBendLines();
mnuViewShowBendLines.Checked = activeForm.PlateView.ShowBendLines;
toggle(activeForm);
item.Checked = isOn(activeForm.PlateView);
}
private void ZoomToArea_Click(object sender, EventArgs e) => WithActive(f => f.PlateView.SetAction(typeof(ActionZoomWindow)));