diff --git a/OpenNest.Reporting/NestPdfWriter.cs b/OpenNest.Reporting/NestPdfWriter.cs index f275f53e..e66c5eae 100644 --- a/OpenNest.Reporting/NestPdfWriter.cs +++ b/OpenNest.Reporting/NestPdfWriter.cs @@ -34,7 +34,8 @@ public static class NestPdfWriter // PDFsharp/MigraDoc layout and font state is process-wide and not safe for concurrent // documents: parallel exports laid out text differently. Reports are rare, so serialize them. - private static readonly object RenderLock = new(); + // Shared with PartPrintoutWriter for the same reason. + internal static readonly object RenderLock = new(); /// Thread-safe; concurrent calls are serialized. public static void Write(NestReportSnapshot snapshot, string destination) => @@ -584,7 +585,7 @@ public static class NestPdfWriter } } - private static void AddContour(XGraphicsPath path, ReportContour contour, Fit fit) + internal static void AddContour(XGraphicsPath path, ReportContour contour, Fit fit) { foreach (var segment in contour.Segments) { diff --git a/OpenNest.Reporting/PartPrintoutBuilder.cs b/OpenNest.Reporting/PartPrintoutBuilder.cs new file mode 100644 index 00000000..3258c1b0 --- /dev/null +++ b/OpenNest.Reporting/PartPrintoutBuilder.cs @@ -0,0 +1,111 @@ +using System.Collections.Immutable; +using OpenNest.CNC; +using OpenNest.Converters; +using OpenNest.Geometry; + +namespace OpenNest.Reporting; + +/// One part page of a printout. Values are detached from the nest. +/// Bounding-box extent along Y. +/// Bounding-box extent along X. +/// Net part area (outside minus cutouts). +/// Length of every move the head cuts: cut, break, common-line and lead moves. +/// Cut runs: each starts with a pierce after a rapid, mark or tab. +/// Required quantity; zero when the nest does not track one. +/// Net weight of one part in ; null when unknown. +public sealed record PrintoutPart(string Name, string Customer, double Width, double Length, double Area, + double CutLength, int PierceCount, long Quantity, double? Weight, ReportGeometry Geometry); + +/// A detached value snapshot of the parts to print, one page each. +public sealed record PartPrintoutSnapshot(string Title, string Material, double Thickness, string Units, + DateTimeOffset GeneratedAt, ImmutableArray Parts) +{ + /// "lb" for inch jobs, "kg" for millimeter jobs. + public string WeightUnits => Units == "mm" ? "kg" : "lb"; +} + +public static class PartPrintoutBuilder +{ + /// + /// Captures (every non-cutoff drawing of the nest when null) in the + /// given order. Material and thickness come from the nest, the drawing's own material being the + /// fallback. is the machine catalog density (lb/in^3) used + /// when the nest material carries none. Capture synchronously while the drawings are stable. + /// + public static PartPrintoutSnapshot Capture(Nest nest, IEnumerable? drawings, DateTimeOffset generatedAt, + double catalogDensity = 0) + { + ArgumentNullException.ThrowIfNull(nest); + if (!double.IsFinite(nest.Thickness) || nest.Thickness < 0) + throw new InvalidOperationException("Nest: thickness must be finite and nonnegative."); + + var selected = (drawings ?? nest.Drawings.Where(drawing => !drawing.IsCutOff)).ToList(); + if (selected.Count == 0) + throw new InvalidOperationException("There are no drawings to print."); + + var parts = ImmutableArray.CreateBuilder(selected.Count); + foreach (var drawing in selected) + parts.Add(CapturePart(drawing, nest, catalogDensity)); + + var title = selected.Count == 1 ? $"{selected[0].Name} printout" : $"{nest.Name} part printouts"; + return new PartPrintoutSnapshot(title.Trim(), MaterialName(nest, selected), nest.Thickness, + nest.Units == Units.Millimeters ? "mm" : "in", generatedAt, parts.MoveToImmutable()); + } + + private static PrintoutPart CapturePart(Drawing drawing, Nest nest, double catalogDensity) + { + ArgumentNullException.ThrowIfNull(drawing); + var context = $"Drawing '{drawing.Name}'"; + var geometry = NestReportGeometry.Capture(drawing.Program, new Vector(), context); + var (cutLength, pierces) = CutMetrics(drawing.Program); + var area = drawing.Area; + if (!double.IsFinite(area) || area < 0) + throw new InvalidOperationException($"{context}: net part area is invalid."); + var customer = string.IsNullOrWhiteSpace(drawing.Customer) ? nest.Customer : drawing.Customer; + return new PrintoutPart(drawing.Name ?? "", customer?.Trim() ?? "", geometry.Bounds.Width, + geometry.Bounds.Length, area, cutLength, pierces, + System.Math.Max(drawing.Quantity.Required, 0), NestReportBuilder.PartWeight(drawing, nest, catalogDensity), + geometry); + } + + /// + /// Walks the program as cut. Scribe/etch marks, tab spans and display-only moves are not cut, + /// so they end a run, and the next cut move starts a new run with its own pierce. A display + /// perimeter's tail is never cut. + /// + internal static (double Length, int Pierces) CutMetrics(Program program) + { + var length = 0.0; + var pierces = 0; + var cutting = false; + foreach (var entity in ConvertProgram.ToGeometry(DisplayPerimeterTail.WithoutTail(program))) + { + if (!IsCut(entity.Layer)) + { + cutting = false; + continue; + } + length += entity.Length; + if (!cutting) + pierces++; + cutting = true; + } + return (length, pierces); + } + + private static bool IsCut(Layer layer) => + layer == SpecialLayers.Cut || layer == SpecialLayers.Break + || layer == SpecialLayers.Leadin || layer == SpecialLayers.Leadout || layer == SpecialLayers.CommonLine; + + /// The nest material, else the drawings' material when they all share one. + private static string MaterialName(Nest nest, IReadOnlyList drawings) + { + static string Name(Material? material) => $"{material?.Name} {material?.Grade}".Trim(); + + var name = Name(nest.Material); + if (name.Length > 0) + return name; + var names = drawings.Select(drawing => Name(drawing.Material)).Distinct().ToList(); + return names.Count == 1 ? names[0] : ""; + } +} diff --git a/OpenNest.Reporting/PartPrintoutWriter.cs b/OpenNest.Reporting/PartPrintoutWriter.cs new file mode 100644 index 00000000..b28bc794 --- /dev/null +++ b/OpenNest.Reporting/PartPrintoutWriter.cs @@ -0,0 +1,183 @@ +using System.Globalization; +using PdfSharp.Drawing; +using PdfSharp.Pdf; + +namespace OpenNest.Reporting; + +/// +/// Renders part printouts: one Letter portrait page per part, bookmarked by part name, with a +/// part name header, customer subtitle, the part drawn to fit, a details table and the generated date. +/// +public static class PartPrintoutWriter +{ + private const double PageWidth = 612; // Letter, points + private const double PageHeight = 792; + private const double Margin = 36; + private const double ContentWidth = PageWidth - 2 * Margin; + private const double RowHeight = 22; + private const double LabelWidth = 100; + private const double ValueWidth = ContentWidth / 2 - LabelWidth; + private const double DrawingPadding = 14; + private const double FooterTop = PageHeight - Margin - 10; + + private static readonly XColor Ink = XColor.FromArgb(0x1a, 0x1a, 0x1a); + private static readonly XColor Muted = XColor.FromArgb(0x64, 0x74, 0x8b); + private static readonly XColor Line = XColor.FromArgb(0xcb, 0xd5, 0xe1); + private static readonly XColor LabelFill = XColor.FromArgb(0xf8, 0xfa, 0xfc); + private static readonly CultureInfo Invariant = CultureInfo.InvariantCulture; + + /// Thread-safe; renders are serialized with nest reports. + public static void Write(PartPrintoutSnapshot snapshot, string destination) + { + ArgumentNullException.ThrowIfNull(snapshot); + ArgumentException.ThrowIfNullOrWhiteSpace(destination); + if (snapshot.Parts.IsDefaultOrEmpty) + throw new InvalidOperationException("A printout needs at least one part."); + ValidateText(snapshot); + + lock (NestPdfWriter.RenderLock) + { + ReportFonts.Initialize(); + using var pdf = new PdfDocument(); + pdf.Info.Title = snapshot.Title; + pdf.Info.Creator = "OpenNest"; + pdf.Info.CreationDate = snapshot.GeneratedAt.UtcDateTime; + var stamp = snapshot.GeneratedAt.ToString("M/d/yyyy h:mm tt", Invariant); + + foreach (var part in snapshot.Parts) + { + var page = pdf.AddPage(); + page.Width = XUnit.FromPoint(PageWidth); + page.Height = XUnit.FromPoint(PageHeight); + using (var gfx = XGraphics.FromPdfPage(page)) + DrawPage(gfx, snapshot, part, stamp); + pdf.Outlines.Add(part.Name.Length == 0 ? "(unnamed)" : part.Name, page, true); + } + + AtomicReportFile.Write(destination, stream => pdf.Save(stream, false)); + } + } + + private static void ValidateText(PartPrintoutSnapshot snapshot) + { + ReportFonts.ValidateText(snapshot.Title, "Printout title"); + ReportFonts.ValidateText(snapshot.Material, "Material"); + foreach (var part in snapshot.Parts) + { + ReportFonts.ValidateText(part.Name, $"Drawing '{part.Name}' name"); + ReportFonts.ValidateText(part.Customer, $"Drawing '{part.Name}' customer"); + } + } + + private static void DrawPage(XGraphics gfx, PartPrintoutSnapshot snapshot, PrintoutPart part, string stamp) + { + var title = Font(24, true); + var subtitle = Font(12, false); + var label = Font(8, true); + var value = Font(10, true); + var small = Font(8, false); + var ink = new XSolidBrush(Ink); + var muted = new XSolidBrush(Muted); + var linePen = new XPen(Line, 0.75); + + // Header: part name, then the customer. + var y = Margin; + gfx.DrawString(Elide(gfx, Dash(part.Name), title, ContentWidth), title, ink, + new XRect(Margin, y, ContentWidth, 30), XStringFormats.TopLeft); + y += 32; + if (part.Customer.Length > 0) + { + gfx.DrawString(Elide(gfx, part.Customer, subtitle, ContentWidth), subtitle, muted, + new XRect(Margin, y, ContentWidth, 16), XStringFormats.TopLeft); + y += 18; + } + y += 6; + gfx.DrawLine(linePen, Margin, y, PageWidth - Margin, y); + y += 12; + + var units = snapshot.Units; + var rows = new (string, string, string, string)[] + { + ("DIMENSIONS", $"{Length(part.Width, units)} x {Length(part.Length, units)}", "MATERIAL", Dash(snapshot.Material)), + ("THICKNESS", snapshot.Thickness > 0 ? Length(snapshot.Thickness, units, "0.####") : "-", + "CUT LENGTH", Length(part.CutLength, units)), + ("PIERCE COUNT", part.PierceCount.ToString(Invariant), "WEIGHT", + part.Weight is { } weight ? $"{Number(weight)} {snapshot.WeightUnits}" : "-"), + ("AREA", $"{Number(part.Area)} sq {units}", "QUANTITY", + part.Quantity > 0 ? part.Quantity.ToString(Invariant) : "-"), + }; + var tableTop = FooterTop - 12 - rows.Length * RowHeight; + var drawing = new XRect(Margin, y, ContentWidth, tableTop - 14 - y); + + gfx.DrawRoundedRectangle(new XPen(Line, 1.5), drawing, new XSize(10, 10)); + DrawGeometry(gfx, part.Geometry, Inset(drawing, DrawingPadding)); + + var rowTop = tableTop; + foreach (var (l1, v1, l2, v2) in rows) + { + DrawCell(gfx, Margin, rowTop, LabelWidth, l1, label, muted, linePen, labelCell: true); + DrawCell(gfx, Margin + LabelWidth, rowTop, ValueWidth, v1, value, ink, linePen, labelCell: false); + DrawCell(gfx, Margin + LabelWidth + ValueWidth, rowTop, LabelWidth, l2, label, muted, linePen, labelCell: true); + DrawCell(gfx, Margin + 2 * LabelWidth + ValueWidth, rowTop, ValueWidth, v2, value, ink, linePen, labelCell: false); + rowTop += RowHeight; + } + + gfx.DrawString($"Generated {stamp}", small, muted, + new XRect(Margin, FooterTop, ContentWidth, 10), XStringFormats.TopRight); + } + + private static void DrawCell(XGraphics gfx, double x, double y, double width, string text, + XFont font, XBrush brush, XPen pen, bool labelCell) + { + var rect = new XRect(x, y, width, RowHeight); + if (labelCell) + gfx.DrawRectangle(pen, new XSolidBrush(LabelFill), rect); + else + gfx.DrawRectangle(pen, rect); + var inner = new XRect(x + 8, y, width - 16, RowHeight); + gfx.DrawString(Elide(gfx, text, font, inner.Width), font, brush, inner, XStringFormats.CenterLeft); + } + + /// + /// Strokes every contour, scaled uniformly and centered in the area. Each contour is its own + /// path so a tab gap never gets a false joining segment. + /// + private static void DrawGeometry(XGraphics gfx, ReportGeometry geometry, XRect area) + { + var fit = Fit.Create(geometry.Bounds, area); + var pen = new XPen(Ink, 0.75) { LineCap = XLineCap.Round, LineJoin = XLineJoin.Round }; + foreach (var contour in geometry.Contours) + { + var path = new XGraphicsPath(); + NestPdfWriter.AddContour(path, contour, fit); + if (contour.Closed) + path.CloseFigure(); + gfx.DrawPath(pen, path); + } + } + + private static XFont Font(double size, bool bold) => + new(ReportFonts.Family, size, bold ? XFontStyleEx.Bold : XFontStyleEx.Regular); + + /// Overlong text is elided visibly rather than overflowing its box. + private static string Elide(XGraphics gfx, string text, XFont font, double width) + { + if (gfx.MeasureString(text, font).Width <= width) + return text; + var shortened = text; + while (shortened.Length > 1 && gfx.MeasureString(shortened + "...", font).Width > width) + shortened = shortened[..^1]; + return shortened + "..."; + } + + private static XRect Inset(XRect rect, double by) => + new(rect.X + by, rect.Y + by, rect.Width - 2 * by, rect.Height - 2 * by); + + /// Inches get an inch mark, as on CutSend's printout; millimeters spell the unit. + private static string Length(double value, string units, string format = "0.00") => + units == "mm" ? $"{value.ToString(format, Invariant)} mm" : $"{value.ToString(format, Invariant)}\""; + + private static string Number(double value) => value.ToString("0.00", Invariant); + + private static string Dash(string text) => string.IsNullOrWhiteSpace(text) ? "-" : text.Trim(); +} diff --git a/OpenNest.Tests/Reporting/PartPrintoutTests.cs b/OpenNest.Tests/Reporting/PartPrintoutTests.cs new file mode 100644 index 00000000..32147512 --- /dev/null +++ b/OpenNest.Tests/Reporting/PartPrintoutTests.cs @@ -0,0 +1,147 @@ +using OpenNest.CNC; +using OpenNest.Reporting; +using PdfSharp.Pdf.IO; + +namespace OpenNest.Tests.Reporting; + +public sealed class PartPrintoutTests : IDisposable +{ + private readonly string directory = Path.Combine(Path.GetTempPath(), "opennest-printout-" + Guid.NewGuid().ToString("N")); + + public PartPrintoutTests() => Directory.CreateDirectory(directory); + + public void Dispose() + { + try { Directory.Delete(directory, true); } catch (IOException) { } + } + + [Fact] + public void Capture_DefaultsToEveryPartDrawingInNestOrder() + { + var snapshot = PartPrintoutBuilder.Capture(NestReportTestData.CreateNest(), null, NestReportTestData.GeneratedAt); + + // The cutoff drawing is never a part page. + Assert.Equal(["Unplaced", "Rotated", "Bracket"], snapshot.Parts.Select(part => part.Name).ToArray()); + Assert.Equal("Steel A36", snapshot.Material); + Assert.Equal(0.125, snapshot.Thickness); + Assert.Equal("in", snapshot.Units); + } + + [Fact] + public void Capture_MeasuresTheDrawing() + { + var nest = NestReportTestData.CreateNest(); + var bracket = nest.Drawings.Single(drawing => drawing.Name == "Bracket"); + + var part = Assert.Single(PartPrintoutBuilder.Capture(nest, [bracket], NestReportTestData.GeneratedAt).Parts); + + Assert.Equal(10, part.Width, 6); + Assert.Equal(10, part.Length, 6); + Assert.Equal(100 - System.Math.PI, part.Area, 6); + Assert.Equal(40 + 2 * System.Math.PI, part.CutLength, 6); + Assert.Equal(2, part.PierceCount); + Assert.Equal(5, part.Quantity); + Assert.Equal((100 - System.Math.PI) * 0.125 * 0.2836, part.Weight!.Value, 6); + Assert.Equal("Test customer", part.Customer); + } + + [Fact] + public void Capture_ReportsYExtentAsWidthAndXExtentAsLength() + { + var nest = NestReportTestData.CreateNest(); + var rotated = nest.Drawings.Single(drawing => drawing.Name == "Rotated"); // 4 along X, 2 along Y + + var part = Assert.Single(PartPrintoutBuilder.Capture(nest, [rotated], NestReportTestData.GeneratedAt).Parts); + + Assert.Equal(2, part.Width, 6); + Assert.Equal(4, part.Length, 6); + } + + [Fact] + public void CutMetrics_CountOnlyWhatTheHeadCuts() + { + var program = new Program(); + // 10 x 10 outside: one pierce, 40 cut. + program.Codes.Add(new RapidMove(0, 0)); + program.Codes.Add(new LinearMove(0, 10)); + program.Codes.Add(new LinearMove(10, 10)); + program.Codes.Add(new LinearMove(10, 0)); + program.Codes.Add(new LinearMove(0, 0)); + // An etch mark is neither cut length nor a pierce. + program.Codes.Add(new RapidMove(1, 1)); + program.Codes.Add(new LinearMove(3, 1) { Layer = LayerType.Scribe }); + // A tabbed 4 x 2 cutout: two cut pieces either side of 1-long tabs, so two pierces, 10 cut. + program.Codes.Add(new RapidMove(3, 4)); + program.Codes.Add(new LinearMove(7, 4)); + program.Codes.Add(new LinearMove(7, 5)); + program.Codes.Add(new LinearMove(7, 6) { Layer = LayerType.Tab }); + program.Codes.Add(new LinearMove(3, 6)); + program.Codes.Add(new LinearMove(3, 5)); + program.Codes.Add(new LinearMove(3, 4) { Layer = LayerType.Tab }); + // A breakoff's break line is cut: one pierce, 2 cut. + program.Codes.Add(new RapidMove(8, 2)); + program.Codes.Add(new LinearMove(8, 4) { Layer = LayerType.Break }); + + var (length, pierces) = PartPrintoutBuilder.CutMetrics(program); + + Assert.Equal(40 + 10 + 2, length, 6); + Assert.Equal(4, pierces); + } + + [Fact] + public void Write_MakesOneLetterPortraitPageAndBookmarkPerPart() + { + var nest = NestReportTestData.CreateNest(); + var path = Path.Combine(directory, "parts.pdf"); + + PartPrintoutWriter.Write(PartPrintoutBuilder.Capture(nest, null, NestReportTestData.GeneratedAt), path); + + using var pdf = PdfReader.Open(path, PdfDocumentOpenMode.Modify); + Assert.Equal(3, pdf.PageCount); + foreach (var page in pdf.Pages) + Assert.Equal((612, 792), ReportPdf.EffectiveSize(page)); + Assert.Equal(["Unplaced", "Rotated", "Bracket"], pdf.Outlines.Select(outline => outline.Title).ToArray()); + } + + [SkippableFact] + public void Write_PageCarriesTheDetailsTable() + { + var nest = NestReportTestData.CreateNest(); + var bracket = nest.Drawings.Single(drawing => drawing.Name == "Bracket"); + var path = Path.Combine(directory, "bracket.pdf"); + + PartPrintoutWriter.Write(PartPrintoutBuilder.Capture(nest, [bracket], NestReportTestData.GeneratedAt), path); + + var text = ReportPdf.Text(path, 1); + Assert.Contains("Bracket", text); + Assert.Contains("Test customer", text); + Assert.Matches(@"DIMENSIONS\s+10\.00"" x 10\.00""\s+MATERIAL\s+Steel A36", text); + Assert.Matches(@"THICKNESS\s+0\.125""\s+CUT LENGTH\s+46\.28""", text); + Assert.Matches(@"PIERCE COUNT\s+2\s+WEIGHT\s+3\.43 lb", text); + Assert.Matches(@"AREA\s+96\.86 sq in\s+QUANTITY\s+5", text); + Assert.Contains("Generated 9/29/2026 12:00 PM", text); + } + + [Fact] + public void Write_RejectsTextTheBundledFontCannotShow() + { + var nest = NestReportTestData.CreateNest(); + var drawing = nest.Drawings.Single(item => item.Name == "Rotated"); + drawing.Customer = "em—dash"; + var path = Path.Combine(directory, "bad.pdf"); + + var error = Assert.Throws(() => + PartPrintoutWriter.Write(PartPrintoutBuilder.Capture(nest, [drawing], NestReportTestData.GeneratedAt), path)); + + Assert.Contains("U+2014", error.Message); + Assert.False(File.Exists(path)); + } + + [Fact] + public void Capture_RejectsAnEmptySelection() + { + var error = Assert.Throws(() => + PartPrintoutBuilder.Capture(new Nest("empty"), null, NestReportTestData.GeneratedAt)); + Assert.Contains("no drawings", error.Message); + } +} diff --git a/OpenNest.WinForms.Tests/Forms/NestReportExportTests.cs b/OpenNest.WinForms.Tests/Forms/NestReportExportTests.cs index 6634e3d2..708cd253 100644 --- a/OpenNest.WinForms.Tests/Forms/NestReportExportTests.cs +++ b/OpenNest.WinForms.Tests/Forms/NestReportExportTests.cs @@ -285,6 +285,68 @@ public class NestReportExportTests Assert.Equal(before, Directory.Exists(reports) ? Directory.GetDirectories(reports).Length : 0); }); + [Fact] + public void PartPrintoutsRenderEveryPartDrawingWithoutTouchingTheJob() => RunSta(() => + { + using var host = new TestMainForm(); + host.Show(); + var nest = CreateJob("printout job"); + using var form = new EditNestForm(nest) { MdiParent = host }; + form.PlateView.SetOverlapAutoCheck(null); // Background overlap workers are irrelevant here. + form.Show(); + var plateCount = nest.Plates.Count; + var menu = Menu(host, "mnuFileViewPartPrintouts"); + Assert.True(menu.Enabled); + + menu.PerformClick(); + + Assert.Empty(host.Failures); + var path = Assert.Single(host.Viewed); + try + { + Assert.Equal("printout job.printout.pdf", Path.GetFileName(path)); + using var pdf = PdfSharp.Pdf.IO.PdfReader.Open(path, PdfSharp.Pdf.IO.PdfDocumentOpenMode.Import); + Assert.Equal(nest.Drawings.Count, pdf.PageCount); + Assert.Equal(plateCount, nest.Plates.Count); + Assert.Equal(2, nest.Drawings.Count); + } + finally + { + NestReportViewerForm.DeleteReportFolder(path); + } + }); + + [Fact] + public void DrawingListPrintoutRendersOnlyThatDrawing() => RunSta(() => + { + using var host = new TestMainForm(); + host.Show(); + var nest = CreateJob("list job"); + var drawing = nest.Drawings.First(); + // Opened as BOM import does, without MainForm.LoadNest's wiring. + using var form = new EditNestForm(nest) { MdiParent = host }; + form.PlateView.SetOverlapAutoCheck(null); // Background overlap workers are irrelevant here. + form.Show(); + var list = (DrawingListBox)typeof(EditNestForm) + .GetField("drawingListBox1", BindingFlags.Instance | BindingFlags.NonPublic)! + .GetValue(form)!; + list.SelectedItem = drawing; + + list.ContextMenuStrip!.Items["mnuPartPrintout"]!.PerformClick(); + + var path = Assert.Single(host.Viewed); + try + { + Assert.Equal($"{drawing.Name}.printout.pdf", Path.GetFileName(path)); + using var pdf = PdfSharp.Pdf.IO.PdfReader.Open(path, PdfSharp.Pdf.IO.PdfDocumentOpenMode.Import); + Assert.Equal(1, pdf.PageCount); + } + finally + { + NestReportViewerForm.DeleteReportFolder(path); + } + }); + [Fact] public void ViewerCentersOnItsOwnerInsideTheScreen() { @@ -383,6 +445,11 @@ public class NestReportExportTests internal override void ShowReportViewer(string pdfPath, EditNestForm.NestReportTargets targets) => Viewed.Add(pdfPath); + + internal override void ShowPrintoutViewer(string pdfPath, string nestName, string suggestedFileName) => + Viewed.Add(pdfPath); + + internal override void PrintoutFailure(Exception error) => Failures.Add(error.Message); } private static void RunSta(System.Action action) => diff --git a/OpenNest/Controls/DrawingListBox.cs b/OpenNest/Controls/DrawingListBox.cs index 60225e40..abd7de4e 100644 --- a/OpenNest/Controls/DrawingListBox.cs +++ b/OpenNest/Controls/DrawingListBox.cs @@ -48,6 +48,13 @@ namespace OpenNest.Controls 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) => { @@ -65,12 +72,15 @@ namespace OpenNest.Controls 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; } @@ -95,6 +105,9 @@ namespace OpenNest.Controls /// Raised when Open in CAD Converter is chosen for the selected drawing. public event EventHandler OpenInConverterRequested; + /// Raised when View Part Printout is chosen for the selected drawing. + public event EventHandler PartPrintoutRequested; + /// /// Raised when the left button is pressed on a drawing's row. /// diff --git a/OpenNest/Forms/EditNestForm.cs b/OpenNest/Forms/EditNestForm.cs index e28130c8..db08a6f3 100644 --- a/OpenNest/Forms/EditNestForm.cs +++ b/OpenNest/Forms/EditNestForm.cs @@ -491,6 +491,9 @@ namespace OpenNest.Forms drawingListBox1.SaveToLibraryRequested += drawingListBox1_SaveToLibraryRequested; drawingListBox1.AddToSetRequested += drawingListBox1_AddToSetRequested; drawingListBox1.OpenInConverterRequested += drawingListBox1_OpenInConverterRequested; + // Every nest window (opened, new or from BOM import) lives in the main window. + drawingListBox1.PartPrintoutRequested += (_, drawing) => + (MdiParent as MainForm)?.ViewPartPrintouts(this, new[] { drawing }); drawingListBox1.DrawingPickedUp += drawingListBox1_DrawingPickedUp; drawingListBox1.DrawingDropped += drawingListBox1_DrawingDropped; drawingListBox1.EmptyTextClicked += (_, _) => hideNestedButton.Checked = false; @@ -860,6 +863,25 @@ namespace OpenNest.Forms NestPdfWriter.Write(snapshot, destination); } + /// + /// Writes one printout page per drawing, in order. Capture is synchronous on the UI thread + /// and reads only drawings, so it has no accounting or dirty-state side effects. + /// + internal void WritePartPrintouts(IReadOnlyList drawings, string destination) + { + ArgumentNullException.ThrowIfNull(drawings); + ArgumentException.ThrowIfNullOrWhiteSpace(destination); + var material = Nest.Material; + var catalogDensity = Data.MaterialDensityLookup.Resolve( + material?.Name, + material?.Grade, + MachineSettings.FindMachine(Nest.Machine), + MachineSettings.LoadMaterials() + ); + var snapshot = PartPrintoutBuilder.Capture(Nest, drawings, DateTimeOffset.Now, catalogDensity); + PartPrintoutWriter.Write(snapshot, destination); + } + private bool IsReportTargetBusy(Nest nest) => Application .OpenForms.OfType() diff --git a/OpenNest/Forms/MainForm.Designer.cs b/OpenNest/Forms/MainForm.Designer.cs index 225ab6cd..80cf6547 100644 --- a/OpenNest/Forms/MainForm.Designer.cs +++ b/OpenNest/Forms/MainForm.Designer.cs @@ -52,6 +52,7 @@ namespace OpenNest.Forms mnuFileExportAll = new System.Windows.Forms.ToolStripMenuItem(); mnuFileViewNestReport = new System.Windows.Forms.ToolStripMenuItem(); mnuFileExportNestReport = new System.Windows.Forms.ToolStripMenuItem(); + mnuFileViewPartPrintouts = new System.Windows.Forms.ToolStripMenuItem(); toolStripMenuItem3 = new System.Windows.Forms.ToolStripSeparator(); mnuFileExit = new System.Windows.Forms.ToolStripMenuItem(); mnuEdit = new System.Windows.Forms.ToolStripMenuItem(); @@ -221,7 +222,7 @@ namespace OpenNest.Forms // // mnuFile // - mnuFile.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { mnuFileNew, mnuFileOpen, mnuFileImportBom, mnuFileDrawingLibrary, mnuFileDrawingSets, mnuFileReleases, toolStripMenuItem1, mnuFileSave, mnuFileSaveAs, toolStripMenuItem2, mnuFileExport, mnuFileExportAll, mnuFileViewNestReport, mnuFileExportNestReport, toolStripMenuItem3, mnuFileExit }); + mnuFile.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { mnuFileNew, mnuFileOpen, mnuFileImportBom, mnuFileDrawingLibrary, mnuFileDrawingSets, mnuFileReleases, toolStripMenuItem1, mnuFileSave, mnuFileSaveAs, toolStripMenuItem2, mnuFileExport, mnuFileExportAll, mnuFileViewNestReport, mnuFileExportNestReport, mnuFileViewPartPrintouts, toolStripMenuItem3, mnuFileExit }); mnuFile.Name = "mnuFile"; mnuFile.DropDownOpening += FileMenu_Opening; mnuFile.Size = new System.Drawing.Size(37, 20); @@ -332,6 +333,14 @@ namespace OpenNest.Forms mnuFileExportNestReport.Text = "Export Nest Report..."; mnuFileExportNestReport.Click += ExportNestReport_Click; // + // mnuFileViewPartPrintouts + // + mnuFileViewPartPrintouts.Enabled = false; + mnuFileViewPartPrintouts.Name = "mnuFileViewPartPrintouts"; + mnuFileViewPartPrintouts.Size = new System.Drawing.Size(146, 22); + mnuFileViewPartPrintouts.Text = "View Part Printouts..."; + mnuFileViewPartPrintouts.Click += ViewPartPrintouts_Click; + // // toolStripMenuItem3 // toolStripMenuItem3.Name = "toolStripMenuItem3"; @@ -1530,6 +1539,7 @@ namespace OpenNest.Forms private System.Windows.Forms.ToolStripMenuItem mnuFileExportAll; private System.Windows.Forms.ToolStripMenuItem mnuFileViewNestReport; private System.Windows.Forms.ToolStripMenuItem mnuFileExportNestReport; + private System.Windows.Forms.ToolStripMenuItem mnuFileViewPartPrintouts; private System.Windows.Forms.ToolStripMenuItem openNestToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem pEPToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem mnuViewZoomTo; diff --git a/OpenNest/Forms/MainForm.File.cs b/OpenNest/Forms/MainForm.File.cs index aaf9e889..6367dee4 100644 --- a/OpenNest/Forms/MainForm.File.cs +++ b/OpenNest/Forms/MainForm.File.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; @@ -358,6 +359,69 @@ namespace OpenNest.Forms ShowReportViewer(path, targets); } + /// Every part drawing of the active nest, one printout page each. + private void ViewPartPrintouts_Click(object sender, EventArgs e) + { + var form = activeForm; + if (form == null) + return; + ViewPartPrintouts(form, form.Nest.Drawings.Where(drawing => !drawing.IsCutOff).ToList()); + } + + /// + /// Renders printouts to a private temporary file and opens them in the report viewer to + /// save or print. Printouts read drawings only, so a running fill does not block them. + /// + internal void ViewPartPrintouts(EditNestForm form, IReadOnlyList drawings) + { + if (drawings.Count == 0) + { + PrintoutFailure(new InvalidOperationException("The nest has no part drawings to print.")); + return; + } + + var name = drawings.Count == 1 ? drawings[0].Name : form.Nest.Name; + var suggested = $"{SafeFileName(name, "parts")}.printout.pdf"; + var path = Path.Combine(Path.GetTempPath(), "OpenNest", "Reports", Guid.NewGuid().ToString("N"), suggested); + try + { + Directory.CreateDirectory(Path.GetDirectoryName(path)); + form.WritePartPrintouts(drawings, path); + } + catch (Exception ex) + when (ex is InvalidOperationException + or NotSupportedException + or IOException + or UnauthorizedAccessException + or ArgumentException) + { + NestReportViewerForm.DeleteReportFolder(path); + PrintoutFailure(ex); + return; + } + ShowPrintoutViewer(path, form.Nest.Name, suggested); + } + + private static string SafeFileName(string name, string fallback) + { + if (string.IsNullOrWhiteSpace(name)) + return fallback; + var invalid = Path.GetInvalidFileNameChars(); + return new string(name.Trim().Select(c => Array.IndexOf(invalid, c) >= 0 ? '_' : c).ToArray()); + } + + /// Opens rendered printouts; internal so tests observe it without a WebView2 window. + internal virtual void ShowPrintoutViewer(string pdfPath, string nestName, string suggestedFileName) + { + var viewer = new NestReportViewerForm(pdfPath, nestName, suggestedFileName, "Part Printouts"); + viewer.Show(this); + } + + /// Failure notice; internal so tests observe it without dialogs. + internal virtual void PrintoutFailure(Exception error) => + MessageBox.Show(this, $"Could not create the part printout: {error.Message}", + "Part Printouts", MessageBoxButtons.OK, MessageBoxIcon.Warning); + // The report never depends on a selected post or NC output; it only needs a // quiescent nest so the snapshot is coherent. private bool TryCaptureReportTargets(EditNestForm form, out EditNestForm.NestReportTargets targets) diff --git a/OpenNest/Forms/MainForm.Status.cs b/OpenNest/Forms/MainForm.Status.cs index 70c951cf..6813c941 100644 --- a/OpenNest/Forms/MainForm.Status.cs +++ b/OpenNest/Forms/MainForm.Status.cs @@ -24,6 +24,7 @@ namespace OpenNest.Forms mnuFileExportAll.Enabled = hasValue; mnuFileExportNestReport.Enabled = hasValue && !storage.IsSaving; mnuFileViewNestReport.Enabled = mnuFileExportNestReport.Enabled; + mnuFileViewPartPrintouts.Enabled = hasValue; mnuEdit.Visible = hasValue; mnuView.Visible = hasValue; mnuNest.Visible = hasValue; diff --git a/OpenNest/Forms/NestReportViewerForm.cs b/OpenNest/Forms/NestReportViewerForm.cs index 7c162780..8af5659e 100644 --- a/OpenNest/Forms/NestReportViewerForm.cs +++ b/OpenNest/Forms/NestReportViewerForm.cs @@ -9,21 +9,25 @@ using Microsoft.Web.WebView2.WinForms; namespace OpenNest.Forms { /// - /// Shows a rendered nest report PDF in WebView2 with Save As and Print. The PDF is a private + /// Shows a rendered nest report or part printout PDF in WebView2 with Save As and Print. The PDF is a private /// temporary copy owned by this window: saving copies it, and closing deletes it. /// public sealed class NestReportViewerForm : Form { private readonly string pdfPath; private readonly string suggestedFileName; + private readonly string documentName; private readonly WebView2 browser = new() { Dock = DockStyle.Fill }; private readonly ToolStripButton printButton; - public NestReportViewerForm(string pdfPath, string nestName, string suggestedFileName) + /// What the PDF is, for the title and messages, e.g. "Part Printouts". + public NestReportViewerForm(string pdfPath, string nestName, string suggestedFileName, + string documentName = "Nest Report") { this.pdfPath = pdfPath ?? throw new ArgumentNullException(nameof(pdfPath)); this.suggestedFileName = suggestedFileName; - Text = $"Nest Report - {nestName}"; + this.documentName = documentName; + Text = $"{documentName} - {nestName}"; Icon = Properties.Resources.app_icon; // CenterParent is ignored for modeless windows; OnLoad centers on the owner instead. StartPosition = FormStartPosition.Manual; @@ -60,8 +64,8 @@ namespace OpenNest.Forms { // Saving needs no viewer; only the preview and Print are unavailable. MessageBox.Show(this, - "The report preview needs the Microsoft Edge WebView2 Runtime, which could not be started. " - + "Use Save As to keep the report.\n\n" + ex.Message, + $"The {documentName.ToLowerInvariant()} preview needs the Microsoft Edge WebView2 Runtime, " + + "which could not be started. Use Save As to keep the PDF.\n\n" + ex.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } @@ -71,7 +75,7 @@ namespace OpenNest.Forms var core = browser.CoreWebView2; core.Settings.AreDevToolsEnabled = false; core.Settings.IsStatusBarEnabled = false; - // The report is the only page this window shows. + // The PDF is the only page this window shows. core.NewWindowRequested += (_, args) => args.Handled = true; core.Navigate(new Uri(pdfPath).AbsoluteUri); printButton.Enabled = true; @@ -96,7 +100,7 @@ namespace OpenNest.Forms { using var dlg = new SaveFileDialog { - Filter = "PDF report (*.pdf)|*.pdf", + Filter = "PDF (*.pdf)|*.pdf", FileName = suggestedFileName, AddExtension = true, DefaultExt = ".pdf", @@ -111,7 +115,7 @@ namespace OpenNest.Forms } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or NotSupportedException) { - MessageBox.Show(this, $"Could not save the nest report: {ex.Message}", Text, + MessageBox.Show(this, $"Could not save the {documentName.ToLowerInvariant()}: {ex.Message}", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } @@ -124,7 +128,7 @@ namespace OpenNest.Forms } catch (Exception ex) when (ex is COMException or InvalidOperationException) { - MessageBox.Show(this, $"Could not print the nest report: {ex.Message}", Text, + MessageBox.Show(this, $"Could not print the {documentName.ToLowerInvariant()}: {ex.Message}", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } diff --git a/docs/nest-reports.md b/docs/nest-reports.md index 185cec18..a829de3b 100644 --- a/docs/nest-reports.md +++ b/docs/nest-reports.md @@ -29,6 +29,28 @@ NestPdfWriter.Write(snapshot, destinationPath); Reporting does not select a post, generate CNC, refresh drawing quantities, change the selected plate, or certify that a layout passed geometry/pre-post checks. +## Part printouts + +**File -> View Part Printouts...** prints every non-cutoff drawing of the active +nest; **View Part Printout...** on the drawing list's right-click menu prints the +selected one. Both render to `%TEMP%\OpenNest\Reports\` and open the report viewer, +suggesting `.printout.pdf` or `.printout.pdf`. Each part +gets one Letter portrait page, bookmarked by name, with the name and customer (the drawing's, else the +nest's) as the header, the part's material contours stroked to fit (leads, rapids +and marks omitted), a details table and the generated time. The table shows the +bounding box (Y extent x X extent), nest material and thickness, cut length and +pierce count, net area, weight +(the nest report's density rules) and required quantity. Cut length sums the moves the head cuts (cut, break, common-line and lead layers); each run of +them is one pierce, so scribe marks, tab spans, display moves and a display +perimeter's tail add neither length nor pierces, and a tabbed cutout counts one +pierce per piece. Printouts read drawings only, so running fills do not block them, and they share the nest report's +Latin-1 text limit and render lock. + +```csharp +var snapshot = PartPrintoutBuilder.Capture(nest, drawingsOrNull, DateTimeOffset.Now, catalogDensity); +PartPrintoutWriter.Write(snapshot, destinationPath); +``` + ## Snapshot contract - IDs (`1`, `2`, ...) are local to the report. Visit non-cutoff placements in plate