Files
OpenNest/OpenNest/Controls/EntityView.Breakoffs.cs
T
ajandClaude Opus 5.5 f28fb5adb6 refactor: share the breakoff and tabbed-cutout code paths
The duplicate scan showed the CAD Converter's breakoff and tabbed-cutout
features, and several IO readers, as copy-and-paste pairs, so a fix to
one feature could miss its twin. Each pair now shares one helper with no
change in behavior:

- CAD Converter pick modes go through one toggle, turning the other modes
  off in the same order as before (the view's cursor follows the last one
  set); index guards, nearest-pick and keep-tabs tests are shared helpers.
- EntityView pick clicks, entity and tab-handle hit tests, and tab-handle
  and entry-mark drawing are shared by both features.
- IO: both polyline converters build one line chain; NestFormat's lenient
  converters share one TryNumber; NestReader reads breakoffs and tabbed
  cutouts through one loop with the same warnings.

The edit and tab-drag handlers stay separate: their types share no
interface, and the tab-drag guard deliberately differs. The Server's own
TryNumber copy stays, since Server may not reference IO. The WinForms
suite (1062) and IO.Tests pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 17:50:53 -05:00

269 lines
11 KiB
C#

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using OpenNest.Breakoffs;
using OpenNest.Geometry;
namespace OpenNest.Controls
{
public sealed class TabDragEventArgs : EventArgs
{
public TabDragEventArgs(int breakoff, int tab, double center, bool finished)
{
Breakoff = breakoff;
Tab = tab;
Center = center;
Finished = finished;
}
public int Breakoff { get; }
public int Tab { get; }
/// <summary>The new tab center as a distance along the break line, already clamped.</summary>
public double Center { get; }
public bool Finished { get; }
}
public partial class EntityView
{
private const int TabHandleRadius = 7;
private bool isPickingBreakoff;
private (int Breakoff, int Tab)? draggedTab;
/// <summary>Resolved breakoffs to draw, in breakoff order; null entries are not drawn.</summary>
public IReadOnlyList<BreakoffLayout> BreakoffLayouts { get; set; } = Array.Empty<BreakoffLayout>();
public int SelectedBreakoffIndex { get; set; } = -1;
/// <summary>Where each break cut is entered and the direction into its scrap, in world coordinates.</summary>
public IReadOnlyList<(Vector Entry, Vector ScrapDirection)> BreakCutEntries { get; set; } =
Array.Empty<(Vector, Vector)>();
/// <summary>A line or arc was clicked while picking a joining line; the point is where.</summary>
public event EventHandler<(Entity Entity, Vector Point)> BreakoffEdgePicked;
public event EventHandler<TabDragEventArgs> TabDragged;
public bool IsPickingBreakoff
{
get => isPickingBreakoff;
set
{
isPickingBreakoff = value;
Cursor = value ? Cursors.Hand : Cursors.Cross;
}
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if (e.Button != MouseButtons.Left || IsPicking)
return;
draggedTab = HitTestTab(e.Location);
if (draggedTab == null)
draggedCutoutTab = HitTestCutoutTab(e.Location);
var dimension = draggedTab == null && draggedCutoutTab == null && BeginDimensionDrag(e.Location);
if (draggedTab == null && draggedCutoutTab == null && !dimension)
BeginWindowSelect(e);
else
suppressNextClick = true; // A tab press or drag does not change the selection.
}
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
if (e.Button != MouseButtons.Left)
return;
EndWindowSelect(e);
EndDimensionDrag();
if (draggedCutoutTab is { } cutoutTab)
{
draggedCutoutTab = null;
RaiseCutoutTabDragged(cutoutTab, e.Location, finished: true);
}
if (draggedTab is not { } tab)
return;
draggedTab = null;
RaiseTabDragged(tab, e.Location, finished: true);
}
private void HandleBreakoffMouseMove(MouseEventArgs e)
{
if (draggedTab is { } tab)
RaiseTabDragged(tab, e.Location, finished: false);
else if (draggedCutoutTab is { } cutoutTab)
RaiseCutoutTabDragged(cutoutTab, e.Location, finished: false);
else if (draggedDimension is { } dimension)
RaiseDimensionDragged(dimension, e.Location);
else if (e.Button == MouseButtons.None && !IsPicking)
{
if (HitTestTab(e.Location) != null || HitTestCutoutTab(e.Location) != null)
Cursor = Cursors.SizeAll;
else if (HitTestDimension(e.Location) is { } hover)
Cursor = DimensionCursor(hover);
else
Cursor = Cursors.Cross;
}
}
private bool HandleBreakoffClick(MouseEventArgs e) =>
HandlePickClick(e, IsPickingBreakoff, entity => entity is Line or Arc, BreakoffEdgePicked);
// Breakoff and tabbed-cutout picking differ only in the mode flag, the kinds of entity
// a click may take and the event raised; a pick-mode click never falls through.
private bool HandlePickClick(MouseEventArgs e, bool picking, Func<Entity, bool> accepts,
EventHandler<(Entity Entity, Vector Point)> picked)
{
if (!picking || e.Button != MouseButtons.Left)
return false;
var entity = HitTestNearest(e.Location, accepts);
if (entity != null)
picked?.Invoke(this, (entity, PointControlToWorld(e.Location)));
return true;
}
private void RaiseTabDragged((int Breakoff, int Tab) tab, Point location, bool finished)
{
var layout = BreakoffLayouts.ElementAtOrDefault(tab.Breakoff);
if (layout is not { IsValid: true } || tab.Tab >= layout.TabCenters.Count)
return;
var center = layout.ClampTabCenter(tab.Tab, layout.DistanceOf(PointControlToWorld(location)));
TabDragged?.Invoke(this, new TabDragEventArgs(tab.Breakoff, tab.Tab, center, finished));
}
private (int, int)? HitTestTab(Point location) =>
HitTestTabHandle(location, BreakoffLayouts.Count, b => BreakoffLayouts[b] is { IsValid: true } layout
? layout.TabCenters.Select(layout.PointAt)
: Enumerable.Empty<Vector>());
// Breakoff and tabbed-cutout tab handles hit-test alike; each layout supplies its handles'
// world points (none when it is invalid), and the first handle under the cursor wins.
private (int, int)? HitTestTabHandle(Point location, int count, Func<int, IEnumerable<Vector>> handles)
{
for (var i = 0; i < count; i++)
{
var t = 0;
foreach (var at in handles(i))
{
var handle = PointWorldToControl(at);
var dx = handle.X - location.X;
var dy = handle.Y - location.Y;
if (dx * dx + dy * dy <= TabHandleRadius * TabHandleRadius)
return (i, t);
t++;
}
}
return null;
}
// The nearest shown entity of an accepted kind within a few pixels of the point.
private Entity HitTestNearest(Point controlPoint, Func<Entity, bool> accepts)
{
var worldPoint = PointControlToWorld(controlPoint);
var tolerance = LengthGuiToWorld(6);
Entity best = null;
var bestDistance = double.MaxValue;
foreach (var entity in Entities)
{
if (!accepts(entity) || !entity.IsVisible || entity.Layer?.IsVisible == false)
continue;
var distance = worldPoint.DistanceTo(entity.ClosestPointTo(worldPoint));
if (distance < tolerance && distance < bestDistance)
{
best = entity;
bestDistance = distance;
}
}
return best;
}
private void DrawBreakoffs(Graphics g)
{
if (BreakoffLayouts.Count == 0)
return;
using var scrapFill = new SolidBrush(Color.FromArgb(55, 255, 170, 0));
using var selectedScrapFill = new SolidBrush(Color.FromArgb(95, 255, 170, 0));
using var cutPen = new Pen(Color.FromArgb(0, 200, 255), 2.5f);
using var leadPen = new Pen(Color.FromArgb(0, 200, 255), 1.5f);
using var tabPen = new Pen(Color.Red, 3f);
using var handleBrush = new SolidBrush(Color.Red);
using var handlePen = new Pen(Color.White, 1f);
for (var b = 0; b < BreakoffLayouts.Count; b++)
{
var layout = BreakoffLayouts[b];
if (layout is not { IsValid: true })
continue;
var selected = b == SelectedBreakoffIndex;
var scrap = Outline(layout.Scrap);
if (scrap.Length >= 3)
g.FillPolygon(selected ? selectedScrapFill : scrapFill, scrap);
foreach (var cut in layout.Cuts)
{
var points = Outline(cut);
if (points.Length >= 2)
g.DrawLines(cutPen, points);
}
foreach (var center in layout.TabCenters)
{
var from = PointWorldToGraph(layout.PointAt(center - layout.TabWidth / 2));
var to = PointWorldToGraph(layout.PointAt(center + layout.TabWidth / 2));
g.DrawLine(tabPen, from, to);
DrawTabHandle(g, handleBrush, handlePen, layout.PointAt(center), selected);
}
}
DrawEntryMarks(g, leadPen);
}
// A short stroke from the pierce side into each cut's entry, a fixed size on screen.
private void DrawEntryMarks(Graphics g, Pen pen)
{
foreach (var (entry, scrap) in BreakCutEntries)
DrawEntryMark(g, pen, entry, scrap);
}
private void DrawEntryMark(Graphics g, Pen pen, Vector entry, Vector pierceDirection)
{
var at = PointWorldToGraph(entry);
var pierce = PointWorldToGraph(entry + pierceDirection * LengthGuiToWorld(12));
g.DrawLine(pen, pierce, at);
g.DrawEllipse(pen, pierce.X - 2.5f, pierce.Y - 2.5f, 5f, 5f);
}
// A tab's drag handle; the selected feature's handles draw larger.
private void DrawTabHandle(Graphics g, Brush fill, Pen outline, Vector at, bool selected)
{
var handle = PointWorldToGraph(at);
var size = selected ? TabHandleRadius : TabHandleRadius - 2;
var rect = new RectangleF(handle.X - size, handle.Y - size, size * 2, size * 2);
g.FillEllipse(fill, rect);
g.DrawEllipse(outline, rect);
}
private PointF[] Outline(IReadOnlyList<Entity> path)
{
var points = new List<PointF>();
foreach (var entity in path)
{
if (entity is Arc arc)
points.AddRange(arc.ToPoints(System.Math.Max(2, arc.SegmentsForTolerance(LengthGuiToWorld(0.5f))))
.Select(PointWorldToGraph));
else if (entity is Line line)
{
points.Add(PointWorldToGraph(line.StartPoint));
points.Add(PointWorldToGraph(line.EndPoint));
}
}
return points.ToArray();
}
}
}