Files
OpenNest/OpenNest/Controls/DrawingListBox.cs
T
ajandClaude Opus 5.5 696e0bdac6 feat(reporting): print one-page part printouts from the nest
Shops used CutSend to get a part printout (the part drawn to fit a Letter
page over a details table) because OpenNest had no way to make one. File >
View Part Printouts prints every part drawing of the nest, and the drawing
list's View Part Printout prints one; both open the report viewer to save
or print.

Cut length and pierce count walk the program as it is cut, so etch marks,
tab spans and display-only moves add neither, a tabbed cutout counts one
pierce per piece, and breakoff and common-line cuts count. The drawing list
item reaches the main window directly so nests made by BOM import get it
too. Rendering shares the nest report's lock, fonts and Latin-1 limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 07:10:56 -05:00

421 lines
15 KiB
C#

using System;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Size = System.Drawing.Size;
namespace OpenNest.Controls
{
public class DrawingListBox : ListBox
{
private const int WM_PAINT = 0x000F;
private const int WM_ERASEBKGND = 0x0014;
private readonly Size imageSize;
private readonly Font nameFont;
private Point lastClickLocation;
private Drawing pressedDrawing;
public DrawingListBox()
{
DrawMode = DrawMode.OwnerDrawFixed;
ItemHeight = 85;
imageSize = new Size(ItemHeight, ItemHeight - 10);
nameFont = new Font(Font.FontFamily, 10, FontStyle.Bold);
var menu = new ContextMenuStrip();
var deleteItem = new ToolStripMenuItem("Delete");
deleteItem.Click += (s, e) =>
{
if (SelectedItem is Drawing drawing)
DeleteRequested?.Invoke(this, drawing);
};
var saveToLibraryItem = new ToolStripMenuItem("Save to Drawing Library...");
saveToLibraryItem.Click += (s, e) =>
{
if (SelectedItem is Drawing drawing)
SaveToLibraryRequested?.Invoke(this, drawing);
};
var addToSetItem = new ToolStripMenuItem("Add Library Drawings to Set...");
addToSetItem.Click += (s, e) => AddToSetRequested?.Invoke(this, EventArgs.Empty);
var saveToLibrarySeparator = new ToolStripSeparator();
var openInConverterItem = new ToolStripMenuItem("Open in CAD Converter...");
openInConverterItem.Click += (s, e) =>
{
if (SelectedItem is Drawing drawing)
OpenInConverterRequested?.Invoke(this, drawing);
};
var openInConverterSeparator = new ToolStripSeparator();
var printoutItem = new ToolStripMenuItem("View Part Printout...") { Name = "mnuPartPrintout" };
printoutItem.Click += (s, e) =>
{
if (SelectedItem is Drawing drawing)
PartPrintoutRequested?.Invoke(this, drawing);
};
var printoutSeparator = new ToolStripSeparator();
menu.ShowItemToolTips = true;
menu.Opening += (s, e) =>
{
if (SelectedItem == null)
{
e.Cancel = true;
return;
}
// Only hosts that handle the request offer it.
saveToLibraryItem.Visible = saveToLibrarySeparator.Visible = SaveToLibraryRequested != null;
saveToLibraryItem.Enabled = SaveToLibraryUnavailableReason == null;
saveToLibraryItem.ToolTipText = SaveToLibraryUnavailableReason ?? "";
addToSetItem.Visible = AddToSetRequested != null;
addToSetItem.Enabled = SaveToLibraryUnavailableReason == null;
addToSetItem.ToolTipText = SaveToLibraryUnavailableReason ?? "";
openInConverterItem.Visible = openInConverterSeparator.Visible = OpenInConverterRequested != null;
printoutItem.Visible = printoutSeparator.Visible = PartPrintoutRequested != null;
};
menu.Items.Add(saveToLibraryItem);
menu.Items.Add(addToSetItem);
menu.Items.Add(saveToLibrarySeparator);
menu.Items.Add(openInConverterItem);
menu.Items.Add(openInConverterSeparator);
menu.Items.Add(printoutItem);
menu.Items.Add(printoutSeparator);
menu.Items.Add(deleteItem);
ContextMenuStrip = menu;
}
public event EventHandler<Drawing> DeleteRequested;
/// <summary>Raised when Save to Drawing Library is chosen for the selected drawing.</summary>
public event EventHandler<Drawing> SaveToLibraryRequested;
/// <summary>
/// Raised when Add Library Drawings to Set is chosen; it acts on the whole nest, not the
/// selected drawing.
/// </summary>
public event EventHandler AddToSetRequested;
/// <summary>
/// Why Save to Drawing Library and Add Library Drawings to Set are disabled, shown as their
/// tooltip; null enables them.
/// </summary>
public string SaveToLibraryUnavailableReason { get; set; }
/// <summary>Raised when Open in CAD Converter is chosen for the selected drawing.</summary>
public event EventHandler<Drawing> OpenInConverterRequested;
/// <summary>Raised when View Part Printout is chosen for the selected drawing.</summary>
public event EventHandler<Drawing> PartPrintoutRequested;
/// <summary>
/// Raised when the left button is pressed on a drawing's row.
/// </summary>
public event EventHandler<Drawing> DrawingPickedUp;
/// <summary>
/// Raised when a drawing dragged out of the list was accepted by a drop target.
/// </summary>
public event EventHandler<Drawing> DrawingDropped;
public Units Units { get; set; }
public bool HideDepletedParts { get; set; }
public bool HideQuantity { get; set; }
/// <summary>
/// The plate shown beside the list; each drawing's count on it prefixes the nested
/// quantity. Null omits the count.
/// </summary>
public Plate Plate { get; set; }
private string emptyText;
/// <summary>
/// A note drawn in the middle of the list while it has no rows; null draws nothing.
/// Clicking the empty list while the note shows raises <see cref="EmptyTextClicked"/>.
/// </summary>
public string EmptyText
{
get => emptyText;
set
{
if (emptyText == value)
return;
emptyText = value;
Invalidate();
}
}
/// <summary>Raised when the empty list is clicked while <see cref="EmptyText"/> shows.</summary>
public event EventHandler EmptyTextClicked;
private bool IsShowingEmptyText => Items.Count == 0 && !string.IsNullOrEmpty(emptyText);
protected override void OnDrawItem(DrawItemEventArgs e)
{
if (e.Index >= Items.Count || e.Index <= -1)
return;
var dwg = Items[e.Index] as Drawing;
if (dwg == null)
return;
var isSelected = (e.State & DrawItemState.Selected) != 0;
Brush bgBrush;
if (!HideQuantity && dwg.Quantity.Nested > 0 && dwg.Quantity.Remaining == 0)
bgBrush = SystemBrushes.Info;
else
bgBrush = Brushes.White;
e.Graphics.FillRectangle(bgBrush, e.Bounds);
if (isSelected)
{
var borderRect = new Rectangle(
e.Bounds.X,
e.Bounds.Y,
e.Bounds.Width - 1,
e.Bounds.Height - 1
);
using var borderPen = new Pen(SystemColors.Highlight, 2);
e.Graphics.DrawRectangle(borderPen, borderRect);
}
if (!HideQuantity && dwg.Quantity.Required > 0)
{
var barWidth = 4;
var barColor =
dwg.Quantity.Nested >= dwg.Quantity.Required
? Color.FromArgb(76, 175, 80)
: Color.FromArgb(255, 152, 0);
using var barBrush = new SolidBrush(barColor);
e.Graphics.FillRectangle(
barBrush,
e.Bounds.X,
e.Bounds.Y,
barWidth,
e.Bounds.Height
);
}
var pt = new PointF(5, e.Bounds.Y + 5);
var brush = new SolidBrush(dwg.Color);
var pen = new Pen(ColorScheme.Default.GetPartOutlineColor(dwg.Color));
using var img = dwg.Program.GetImage(imageSize, pen, brush);
pen.Dispose();
brush.Dispose();
e.Graphics.DrawImage(img, pt);
pt.X += imageSize.Width + 10;
var textBrush = Brushes.Black;
var detailBrush = Brushes.Gray;
e.Graphics.DrawString(dwg.Name, nameFont, textBrush, pt);
var bounds = dwg.Program.BoundingBox();
var text2 = bounds.Size.ToString(4);
var text3 = string.Format(
"{0} sq/{1}",
System.Math.Round(dwg.Area, 4),
UnitsHelper.GetShortString(Units)
);
if (HideQuantity)
{
pt.Y += 22;
e.Graphics.DrawString(text2, Font, detailBrush, pt);
pt.Y += 18;
e.Graphics.DrawString(text3, Font, detailBrush, pt);
}
else
{
var text1 = string.Format(
"{0} of {1} nested",
dwg.Quantity.Nested,
dwg.Quantity.Required
);
var onPlate = Plate?.Parts.Count(part => part.BaseDrawing == dwg) ?? 0;
if (onPlate > 0)
text1 = $"[{onPlate}] {text1}";
pt.Y += 22;
e.Graphics.DrawString(text1, Font, detailBrush, pt);
pt.Y += 18;
e.Graphics.DrawString(text2, Font, detailBrush, pt);
pt.Y += 18;
e.Graphics.DrawString(text3, Font, detailBrush, pt);
}
using var separatorPen = new Pen(Color.LightGray);
var separatorY = e.Bounds.Bottom - 1;
e.Graphics.DrawLine(separatorPen, e.Bounds.X, separatorY, e.Bounds.Right, separatorY);
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
Cursor = IsShowingEmptyText && EmptyTextClicked != null ? Cursors.Hand : Cursors.Default;
var drawing = pressedDrawing;
if (drawing == null || e.Button != MouseButtons.Left)
return;
if (e.Location.DistanceTo(lastClickLocation) <= 3)
return;
pressedDrawing = null;
if (DoDragDrop(drawing, DragDropEffects.Copy) != DragDropEffects.None)
DrawingDropped?.Invoke(this, drawing);
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
lastClickLocation = e.Location;
// Pick the part up on the press. Waiting for Click loses the pickup
// whenever the mouse moves a few pixels first: the drag that starts
// takes mouse capture and the list never raises Click.
pressedDrawing =
e.Button == MouseButtons.Left && e.Clicks == 1 ? DrawingAt(e.Location) : null;
if (pressedDrawing != null)
DrawingPickedUp?.Invoke(this, pressedDrawing);
}
/// <summary>Forgets a drawing pressed but not yet dragged, e.g. when the nest is swapped.</summary>
internal void CancelPickup() => pressedDrawing = null;
protected override void OnMouseUp(MouseEventArgs e)
{
pressedDrawing = null;
base.OnMouseUp(e);
if (e.Button == MouseButtons.Left && IsShowingEmptyText)
EmptyTextClicked?.Invoke(this, EventArgs.Empty);
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
// The note wraps to the width, so a resize must repaint all of it.
if (IsShowingEmptyText)
Invalidate();
}
private void DrawEmptyText()
{
using var g = CreateGraphics();
var bounds = Rectangle.Inflate(ClientRectangle, -12, -12);
TextRenderer.DrawText(
g,
emptyText,
Font,
bounds,
SystemColors.GrayText,
TextFormatFlags.HorizontalCenter
| TextFormatFlags.Top
| TextFormatFlags.WordBreak
| TextFormatFlags.TextBoxControl
);
}
/// <summary>
/// The drawing whose row contains <paramref name="location"/>, or null
/// when the point is in the empty area below the last row.
/// </summary>
internal Drawing DrawingAt(Point location)
{
var index = IndexFromPoint(location);
if (index < 0 || index >= Items.Count)
return null;
return GetItemRectangle(index).Contains(location) ? Items[index] as Drawing : null;
}
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_ERASEBKGND)
{
// Windows erases a resized window before WinForms hears the new size, so the
// cached ClientSize still holds the old one; filling to it left the newly
// exposed strip unpainted (and validated, so nothing repainted it later).
GetClientRect(Handle, out var client);
var clientWidth = client.Right - client.Left;
var clientHeight = client.Bottom - client.Top;
var itemBottom = 0;
if (Items.Count > 0)
{
var lastVisible = System.Math.Min(
TopIndex + (clientHeight / ItemHeight),
Items.Count - 1
);
itemBottom = GetItemRectangle(lastVisible).Bottom;
}
if (itemBottom < clientHeight)
{
using var g = Graphics.FromHdc(m.WParam);
g.FillRectangle(
Brushes.White,
0,
itemBottom,
clientWidth,
clientHeight - itemBottom
);
}
m.Result = (IntPtr)1;
return;
}
base.WndProc(ref m);
// An owner-drawn list paints nothing when empty, so the note goes on top afterward.
if (m.Msg == WM_PAINT && IsShowingEmptyText)
DrawEmptyText();
}
[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetClientRect(IntPtr hWnd, out RECT rect);
}
public static class PointExtensions
{
public static double DistanceTo(this Point pt1, Point pt2)
{
var x = pt2.X - pt1.X;
var y = pt2.Y - pt1.Y;
return System.Math.Sqrt(x * x + y * y);
}
}
}