mirror of
https://github.com/ajisaacs/OpenNest.git
synced 2026-11-15 19:15:37 -05:00
feat(drawing-library): export drawings as DXF, SVG or .nest
Export... saves the selected drawing's listed revision; Export Listed Drawings writes every drawing on the page to a folder, numbering names the batch already used and asking once before replacing files. Files are written beside the target and moved into place. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
08318620c9
commit
3e2e9c842a
7 files changed
+647
-5
No files matched your search
@@ -0,0 +1,159 @@
|
||||
using System.Xml.Linq;
|
||||
using OpenNest.Data;
|
||||
using OpenNest.Geometry;
|
||||
using OpenNest.IO;
|
||||
|
||||
namespace OpenNest.Desktop.Tests;
|
||||
|
||||
public sealed class LibraryDrawingExportTests : IDisposable
|
||||
{
|
||||
private readonly string folder = Path.Combine(Path.GetTempPath(), $"opennest-library-export-{Guid.NewGuid():N}");
|
||||
|
||||
public LibraryDrawingExportTests() => Directory.CreateDirectory(folder);
|
||||
|
||||
public void Dispose() => Directory.Delete(folder, true);
|
||||
|
||||
[Theory]
|
||||
[InlineData(1, LibraryExportFormat.Dxf)]
|
||||
[InlineData(2, LibraryExportFormat.Svg)]
|
||||
[InlineData(3, LibraryExportFormat.Nest)]
|
||||
public void FromFilterIndex_FollowsTheDialogFilter(int index, LibraryExportFormat expected)
|
||||
{
|
||||
Assert.Equal(expected, LibraryDrawingExport.FromFilterIndex(index));
|
||||
var patterns = LibraryDrawingExport.DialogFilter.Split('|').Where((_, i) => i % 2 == 1).ToArray();
|
||||
Assert.Equal("*" + LibraryDrawingExport.Extension(expected), patterns[index - 1]);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0)]
|
||||
[InlineData(4)]
|
||||
public void FromFilterIndex_RefusesOtherIndexes(int index) =>
|
||||
Assert.Throws<ArgumentException>(() => LibraryDrawingExport.FromFilterIndex(index));
|
||||
|
||||
[Theory]
|
||||
[InlineData("BRKT-1", LibraryExportFormat.Dxf, "BRKT-1.dxf")]
|
||||
[InlineData(" A/B:C ", LibraryExportFormat.Svg, "A_B_C.svg")]
|
||||
[InlineData("", LibraryExportFormat.Nest, "Drawing.nest")]
|
||||
public void SuggestedFileName_IsTheSafeDrawingName(string name, LibraryExportFormat format, string expected) =>
|
||||
Assert.Equal(expected, LibraryDrawingExport.SuggestedFileName(new DrawingLibraryRecord { Name = name }, format));
|
||||
|
||||
[Fact]
|
||||
public void PlanFolder_NumbersNamesTheBatchAlreadyTook()
|
||||
{
|
||||
var records = new[] { "Plate", "plate", "Other", "Plate" }
|
||||
.Select(name => new DrawingLibraryRecord { Id = Guid.NewGuid(), Name = name });
|
||||
|
||||
var targets = LibraryDrawingExport.PlanFolder(records, folder, LibraryExportFormat.Dxf);
|
||||
|
||||
Assert.Equal(new[] { "Plate.dxf", "plate (2).dxf", "Other.dxf", "Plate (3).dxf" },
|
||||
targets.Select(target => Path.GetFileName(target.Path)));
|
||||
Assert.All(targets, target => Assert.Equal(folder, Path.GetDirectoryName(target.Path)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Write_Dxf_ReadsBackAsTheDrawingsGeometry()
|
||||
{
|
||||
var path = Path.Combine(folder, "part.dxf");
|
||||
|
||||
LibraryDrawingExport.Write(Package(Units.Inches), path, LibraryExportFormat.Dxf);
|
||||
|
||||
var box = Dxf.GetGeometry(path).Cast<IBoundable>().GetBoundingBox();
|
||||
Assert.Equal(4, box.Width, 6);
|
||||
Assert.Equal(4, box.Length, 6);
|
||||
Assert.Empty(Directory.GetFiles(folder, "*.tmp"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Write_Svg_UsesThePackagesUnits()
|
||||
{
|
||||
var path = Path.Combine(folder, "part.svg");
|
||||
|
||||
LibraryDrawingExport.Write(Package(Units.Millimeters), path, LibraryExportFormat.Svg);
|
||||
|
||||
Assert.EndsWith("mm", XDocument.Load(path).Root!.Attribute("width")!.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Write_Nest_IsThePackageAsStored()
|
||||
{
|
||||
var path = Path.Combine(folder, "part.nest");
|
||||
var package = Package(Units.Inches);
|
||||
|
||||
LibraryDrawingExport.Write(package, path, LibraryExportFormat.Nest);
|
||||
|
||||
Assert.Equal(package, File.ReadAllBytes(path));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Write_ADamagedPackage_LeavesTheExistingFileAlone()
|
||||
{
|
||||
var path = Path.Combine(folder, "part.nest");
|
||||
File.WriteAllText(path, "keep me");
|
||||
|
||||
Assert.Throws<InvalidDataException>(() =>
|
||||
LibraryDrawingExport.Write(new byte[] { 1, 2, 3 }, path, LibraryExportFormat.Nest));
|
||||
|
||||
Assert.Equal("keep me", File.ReadAllText(path));
|
||||
Assert.Single(Directory.GetFiles(folder));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExportAsync_WritesWhatItCan_AndReportsTheRest()
|
||||
{
|
||||
var library = new FakeLibrary();
|
||||
var good = library.Add("Good", Package(Units.Inches));
|
||||
var gone = new DrawingLibraryRecord { Id = Guid.NewGuid(), Revision = 1, Name = "Gone" };
|
||||
var damaged = library.Add("Damaged", new byte[] { 9 });
|
||||
var targets = LibraryDrawingExport.PlanFolder(new[] { good, gone, damaged }, folder, LibraryExportFormat.Dxf);
|
||||
var reported = new List<int>();
|
||||
|
||||
var result = await LibraryDrawingExport.ExportAsync(library, targets, LibraryExportFormat.Dxf,
|
||||
new SynchronousProgress(reported.Add));
|
||||
|
||||
Assert.Equal(new[] { targets[0].Path }, result.Written);
|
||||
Assert.Same(gone, Assert.Single(result.Missing));
|
||||
Assert.Same(damaged, Assert.Single(result.Failed).Record);
|
||||
Assert.Equal(new[] { 1, 2, 3 }, reported);
|
||||
Assert.Equal(new[] { "Good.dxf" }, Directory.GetFiles(folder).Select(Path.GetFileName));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExportAsync_StopsWhenCanceled()
|
||||
{
|
||||
var library = new FakeLibrary();
|
||||
var targets = LibraryDrawingExport.PlanFolder(new[] { library.Add("A", Package(Units.Inches)) },
|
||||
folder, LibraryExportFormat.Dxf);
|
||||
using var cancel = new CancellationTokenSource();
|
||||
cancel.Cancel();
|
||||
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() =>
|
||||
LibraryDrawingExport.ExportAsync(library, targets, LibraryExportFormat.Dxf, null, cancel.Token));
|
||||
Assert.Empty(Directory.GetFiles(folder));
|
||||
}
|
||||
|
||||
private static byte[] Package(Units units) =>
|
||||
DrawingPackage.Write(new Drawing("square", PlateExportTests.Square(4)), units);
|
||||
|
||||
private sealed class SynchronousProgress(Action<int> report) : IProgress<int>
|
||||
{
|
||||
public void Report(int value) => report(value);
|
||||
}
|
||||
|
||||
private sealed class FakeLibrary : IDrawingLibrary
|
||||
{
|
||||
private readonly Dictionary<(Guid, int), byte[]> packages = new();
|
||||
|
||||
public DrawingLibraryRecord Add(string name, byte[] package)
|
||||
{
|
||||
var record = new DrawingLibraryRecord { Id = Guid.NewGuid(), Revision = 1, Name = name };
|
||||
packages[(record.Id, record.Revision)] = package;
|
||||
return record;
|
||||
}
|
||||
|
||||
public Task<DrawingLibraryPage> QueryAsync(DrawingLibraryQuery query, CancellationToken cancellationToken = default) =>
|
||||
throw new NotSupportedException();
|
||||
|
||||
public Task<byte[]?> GetRevisionPackageAsync(Guid id, int revision, CancellationToken cancellationToken = default) =>
|
||||
Task.FromResult(packages.TryGetValue((id, revision), out var package) ? package : null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using OpenNest.Data;
|
||||
using OpenNest.IO;
|
||||
|
||||
namespace OpenNest.Desktop;
|
||||
|
||||
/// <summary>What exporting a drawing from the drawing library writes.</summary>
|
||||
public enum LibraryExportFormat
|
||||
{
|
||||
/// <summary>The drawing's program as DXF geometry.</summary>
|
||||
Dxf,
|
||||
|
||||
/// <summary>The drawing's program as SVG in the units it was saved in.</summary>
|
||||
Svg,
|
||||
|
||||
/// <summary>The revision's package as stored: a .nest holding the one drawing.</summary>
|
||||
Nest,
|
||||
}
|
||||
|
||||
/// <summary>One drawing to export and the file it goes to.</summary>
|
||||
public sealed record LibraryExportTarget(DrawingLibraryRecord Record, string Path);
|
||||
|
||||
/// <summary>What a library export wrote, and what it could not.</summary>
|
||||
public sealed class LibraryExportResult
|
||||
{
|
||||
/// <summary>The files written, in order.</summary>
|
||||
public List<string> Written { get; } = new();
|
||||
|
||||
/// <summary>The drawings whose listed revision is no longer on the server.</summary>
|
||||
public List<DrawingLibraryRecord> Missing { get; } = new();
|
||||
|
||||
/// <summary>The drawings that could not be read or written, with the reason.</summary>
|
||||
public List<(DrawingLibraryRecord Record, string Reason)> Failed { get; } = new();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Export from the drawing library for both desktop apps: downloads each listed revision's
|
||||
/// exact package and writes it as DXF, SVG or the package itself. Nothing on the server or in
|
||||
/// an open nest changes. The package leaves customer, color and nesting settings to the
|
||||
/// library record, so a .nest export carries the geometry, units, bends and cut settings only.
|
||||
/// </summary>
|
||||
public static class LibraryDrawingExport
|
||||
{
|
||||
/// <summary>The save dialog's file types in order: its 1-based filter index picks the format.</summary>
|
||||
public static IReadOnlyList<LibraryExportFormat> DialogFormats { get; } = new[]
|
||||
{
|
||||
LibraryExportFormat.Dxf,
|
||||
LibraryExportFormat.Svg,
|
||||
LibraryExportFormat.Nest,
|
||||
};
|
||||
|
||||
/// <summary>The WinForms save dialog filter, in <see cref="DialogFormats"/> order.</summary>
|
||||
public const string DialogFilter = "DXF (*.dxf)|*.dxf|SVG (*.svg)|*.svg|OpenNest nest (*.nest)|*.nest";
|
||||
|
||||
/// <summary>The format for the save dialog's 1-based <paramref name="filterIndex"/>.</summary>
|
||||
public static LibraryExportFormat FromFilterIndex(int filterIndex) =>
|
||||
filterIndex >= 1 && filterIndex <= DialogFormats.Count
|
||||
? DialogFormats[filterIndex - 1]
|
||||
: throw new ArgumentException("Unsupported drawing export format.", nameof(filterIndex));
|
||||
|
||||
/// <summary>The file extension a format is written with, including the dot.</summary>
|
||||
public static string Extension(LibraryExportFormat format) => format switch
|
||||
{
|
||||
LibraryExportFormat.Dxf => ".dxf",
|
||||
LibraryExportFormat.Svg => ".svg",
|
||||
LibraryExportFormat.Nest => ".nest",
|
||||
_ => throw new ArgumentException("Unsupported drawing export format.", nameof(format)),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The file a drawing is suggested to be saved as: its name, made safe for a file name on
|
||||
/// every platform ("Drawing" when blank), with the format's extension.
|
||||
/// </summary>
|
||||
public static string SuggestedFileName(DrawingLibraryRecord record, LibraryExportFormat format)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(record);
|
||||
return PlateExport.SafeFileName(record.Name, "Drawing") + Extension(format);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The file in <paramref name="folder"/> each drawing is exported to: its suggested name, with
|
||||
/// " (2)", " (3)"... added when another drawing in the batch already took it (names compared
|
||||
/// ignoring case, as Windows does). Files already in the folder are not considered; callers
|
||||
/// ask before overwriting them.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<LibraryExportTarget> PlanFolder(
|
||||
IEnumerable<DrawingLibraryRecord> records, string folder, LibraryExportFormat format)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(records);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(folder);
|
||||
var taken = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var targets = new List<LibraryExportTarget>();
|
||||
foreach (var record in records)
|
||||
{
|
||||
var name = SuggestedFileName(record, format);
|
||||
var stem = System.IO.Path.GetFileNameWithoutExtension(name);
|
||||
var extension = Extension(format);
|
||||
for (var copy = 2; !taken.Add(name); copy++)
|
||||
name = $"{stem} ({copy}){extension}";
|
||||
targets.Add(new LibraryExportTarget(record, System.IO.Path.Combine(folder, name)));
|
||||
}
|
||||
return targets;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes one revision's <paramref name="package"/> to <paramref name="destination"/>. The file
|
||||
/// is written beside it under a temporary name and then moved over it, so a failure never
|
||||
/// leaves a partial file or damages one already there. Throws
|
||||
/// <see cref="InvalidDataException"/> for an unreadable package.
|
||||
/// </summary>
|
||||
public static void Write(byte[] package, string destination, LibraryExportFormat format)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(package);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(destination);
|
||||
Extension(format);
|
||||
|
||||
// Reading first refuses a damaged package, even when it would be copied as is.
|
||||
var contents = DrawingPackage.Read(package);
|
||||
var folder = System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(destination))!;
|
||||
var temporary = System.IO.Path.Combine(folder, $".{System.IO.Path.GetFileName(destination)}.{Guid.NewGuid():N}.tmp");
|
||||
try
|
||||
{
|
||||
switch (format)
|
||||
{
|
||||
case LibraryExportFormat.Dxf:
|
||||
Dxf.ExportProgram(contents.Drawing.Program, temporary);
|
||||
break;
|
||||
case LibraryExportFormat.Svg:
|
||||
Svg.ExportProgram(contents.Drawing.Program, temporary, contents.Units);
|
||||
break;
|
||||
case LibraryExportFormat.Nest:
|
||||
File.WriteAllBytes(temporary, package);
|
||||
break;
|
||||
}
|
||||
File.Move(temporary, destination, overwrite: true);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (File.Exists(temporary))
|
||||
File.Delete(temporary);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Downloads each target's listed revision and writes it in <paramref name="format"/>, in
|
||||
/// order. A revision no longer on the server, an unreadable package or a file that cannot be
|
||||
/// written is recorded and the rest still export; cancellation stops the batch.
|
||||
/// <paramref name="progress"/> receives the number of drawings finished so far.
|
||||
/// </summary>
|
||||
public static async Task<LibraryExportResult> ExportAsync(
|
||||
IDrawingLibrary library,
|
||||
IReadOnlyList<LibraryExportTarget> targets,
|
||||
LibraryExportFormat format,
|
||||
IProgress<int> progress = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(library);
|
||||
ArgumentNullException.ThrowIfNull(targets);
|
||||
Extension(format);
|
||||
|
||||
var result = new LibraryExportResult();
|
||||
for (var i = 0; i < targets.Count; i++)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var (record, path) = targets[i];
|
||||
try
|
||||
{
|
||||
var package = await library.GetRevisionPackageAsync(record.Id, record.Revision, cancellationToken);
|
||||
if (package == null)
|
||||
result.Missing.Add(record);
|
||||
else
|
||||
{
|
||||
await Task.Run(() => Write(package, path, format), cancellationToken);
|
||||
result.Written.Add(path);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (!cancellationToken.IsCancellationRequested
|
||||
&& (ex is IOException || ex is InvalidDataException || ex is UnauthorizedAccessException
|
||||
|| ex is HttpRequestException || ex is TaskCanceledException))
|
||||
{
|
||||
// ServerTooOldException is an IOException; InvalidDataException (an unreadable package) is not.
|
||||
result.Failed.Add((record, ex.Message));
|
||||
}
|
||||
progress?.Report(i + 1);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -76,11 +76,17 @@ public static class PlateExport
|
||||
/// "-P" with the 1-based plate number ("job-P2"). Characters a file name cannot hold on any
|
||||
/// platform become underscores; a blank nest name is "Nest".
|
||||
/// </summary>
|
||||
public static string SuggestedFileName(string nestName, int plateNumber)
|
||||
public static string SuggestedFileName(string nestName, int plateNumber) =>
|
||||
$"{SafeFileName(nestName, "Nest")}-P{plateNumber}";
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="name"/> trimmed, with characters a file name cannot hold on any platform
|
||||
/// turned into underscores; <paramref name="fallback"/> when it is blank.
|
||||
/// </summary>
|
||||
internal static string SafeFileName(string name, string fallback)
|
||||
{
|
||||
var baseName = string.IsNullOrWhiteSpace(nestName) ? "Nest" : nestName.Trim();
|
||||
var chars = baseName.Select(c => Array.IndexOf(InvalidFileNameChars, c) >= 0 ? '_' : c).ToArray();
|
||||
return $"{new string(chars)}-P{plateNumber}";
|
||||
var baseName = string.IsNullOrWhiteSpace(name) ? fallback : name.Trim();
|
||||
return new string(baseName.Select(c => Array.IndexOf(InvalidFileNameChars, c) >= 0 ? '_' : c).ToArray());
|
||||
}
|
||||
|
||||
/// <summary>The DXF that View in CAD writes for the plate and opens: <see cref="SuggestedFileName"/>.dxf.</summary>
|
||||
|
||||
@@ -578,6 +578,56 @@ public class DrawingLibraryFormTests
|
||||
"The drawing library filter test did not complete.");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Export_SavesTheSelectedDrawing_AndTheListedPageToAFolder()
|
||||
{
|
||||
var folder = Path.Combine(Path.GetTempPath(), $"opennest-library-export-{Guid.NewGuid():N}");
|
||||
Directory.CreateDirectory(folder);
|
||||
try
|
||||
{
|
||||
StaTestThread.Run(
|
||||
() =>
|
||||
{
|
||||
var library = new FakeLibrary();
|
||||
var record = library.Add("SYN-EXPORT", "", "", 0, Units.Millimeters, "");
|
||||
var messages = new List<string>();
|
||||
|
||||
using var form = new DrawingLibraryForm(library, Server, nest: null);
|
||||
form.View.ShowMessage = (text, _, _) => { messages.Add(text); return DialogResult.OK; };
|
||||
form.View.LoadPreview = (_, _) => Task.FromResult<Drawing>(null!);
|
||||
var single = Path.Combine(folder, "one.svg");
|
||||
form.View.ChooseExportFile = chosen =>
|
||||
{
|
||||
Assert.Same(record, chosen);
|
||||
return (single, OpenNest.Desktop.LibraryExportFormat.Svg);
|
||||
};
|
||||
form.View.ChooseExportFolder = () => folder;
|
||||
form.Show();
|
||||
var grid = Field<DataGridView>(form, "drawingGrid");
|
||||
PumpUntilListed(grid, "the library page");
|
||||
Assert.True(Field<Button>(form, "exportButton").Enabled);
|
||||
|
||||
Run(form.View.ExportSelectedAsync());
|
||||
Assert.Contains("mm", File.ReadAllText(single));
|
||||
Assert.StartsWith("Exported 'SYN-EXPORT' revision 2", Field<Label>(form, "statusLabel").Text);
|
||||
|
||||
Run(form.View.ExportListedAsync(OpenNest.Desktop.LibraryExportFormat.Dxf));
|
||||
Assert.NotEmpty(Dxf.GetGeometry(Path.Combine(folder, "SYN-EXPORT.dxf")));
|
||||
|
||||
// A second run asks once before replacing the file it wrote.
|
||||
Run(form.View.ExportListedAsync(OpenNest.Desktop.LibraryExportFormat.Dxf));
|
||||
Assert.Contains("1 of the 1 files already exist", Assert.Single(messages));
|
||||
Assert.Equal(3, library.Downloads.Count);
|
||||
},
|
||||
TestTimeout,
|
||||
"The drawing library export test did not complete.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(folder, true);
|
||||
}
|
||||
}
|
||||
|
||||
private static Nest MatchingNest() => new("Synthetic job")
|
||||
{
|
||||
Units = Units.Inches,
|
||||
|
||||
+65
-1
@@ -84,6 +84,7 @@ namespace OpenNest.Controls
|
||||
quantityBox = new System.Windows.Forms.NumericUpDown();
|
||||
addButton = new System.Windows.Forms.Button();
|
||||
editButton = new System.Windows.Forms.Button();
|
||||
exportButton = new System.Windows.Forms.Button();
|
||||
statusLabel = new System.Windows.Forms.Label();
|
||||
searchTimer = new System.Windows.Forms.Timer(components);
|
||||
previewTimer = new System.Windows.Forms.Timer(components);
|
||||
@@ -95,6 +96,12 @@ namespace OpenNest.Controls
|
||||
releaseSeparator = new System.Windows.Forms.ToolStripSeparator();
|
||||
releaseMenuItem = new System.Windows.Forms.ToolStripMenuItem();
|
||||
releasesMenuItem = new System.Windows.Forms.ToolStripMenuItem();
|
||||
exportSeparator = new System.Windows.Forms.ToolStripSeparator();
|
||||
exportMenuItem = new System.Windows.Forms.ToolStripMenuItem();
|
||||
exportListedMenuItem = new System.Windows.Forms.ToolStripMenuItem();
|
||||
exportListedDxfMenuItem = new System.Windows.Forms.ToolStripMenuItem();
|
||||
exportListedSvgMenuItem = new System.Windows.Forms.ToolStripMenuItem();
|
||||
exportListedNestMenuItem = new System.Windows.Forms.ToolStripMenuItem();
|
||||
rootTable.SuspendLayout();
|
||||
tabControl.SuspendLayout();
|
||||
drawingsTab.SuspendLayout();
|
||||
@@ -704,6 +711,8 @@ namespace OpenNest.Controls
|
||||
actionTable.Controls.Add(quantityLabel, 0, 0);
|
||||
actionTable.Controls.Add(quantityBox, 1, 0);
|
||||
actionTable.Controls.Add(addButton, 2, 0);
|
||||
actionTable.Controls.Add(exportButton, 0, 1);
|
||||
actionTable.SetColumnSpan(exportButton, 2);
|
||||
actionTable.Controls.Add(editButton, 2, 1);
|
||||
actionTable.Dock = System.Windows.Forms.DockStyle.Fill;
|
||||
actionTable.Margin = new System.Windows.Forms.Padding(0);
|
||||
@@ -758,6 +767,18 @@ namespace OpenNest.Controls
|
||||
editButton.UseVisualStyleBackColor = true;
|
||||
editButton.Click += EditButton_Click;
|
||||
//
|
||||
// exportButton
|
||||
//
|
||||
exportButton.AutoSize = true;
|
||||
exportButton.Anchor = System.Windows.Forms.AnchorStyles.Left;
|
||||
exportButton.Enabled = false;
|
||||
exportButton.Margin = new System.Windows.Forms.Padding(0, 3, 0, 0);
|
||||
exportButton.Name = "exportButton";
|
||||
exportButton.TabIndex = 4;
|
||||
exportButton.Text = "Export...";
|
||||
exportButton.UseVisualStyleBackColor = true;
|
||||
exportButton.Click += ExportButton_Click;
|
||||
//
|
||||
// statusLabel
|
||||
//
|
||||
statusLabel.AutoEllipsis = true;
|
||||
@@ -779,7 +800,7 @@ namespace OpenNest.Controls
|
||||
//
|
||||
// drawingMenu
|
||||
//
|
||||
drawingMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { editMenuItem, editSeparator, usedInSetsMenuItem, addToSetMenuItem, releaseSeparator, releaseMenuItem, releasesMenuItem });
|
||||
drawingMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { editMenuItem, editSeparator, usedInSetsMenuItem, addToSetMenuItem, releaseSeparator, releaseMenuItem, releasesMenuItem, exportSeparator, exportMenuItem, exportListedMenuItem });
|
||||
drawingMenu.Name = "drawingMenu";
|
||||
drawingMenu.Opening += DrawingMenu_Opening;
|
||||
//
|
||||
@@ -825,6 +846,42 @@ namespace OpenNest.Controls
|
||||
releasesMenuItem.ToolTipText = "The releases that had this drawing on its own";
|
||||
releasesMenuItem.Click += ReleasesMenuItem_Click;
|
||||
//
|
||||
// exportSeparator
|
||||
//
|
||||
exportSeparator.Name = "exportSeparator";
|
||||
//
|
||||
// exportMenuItem
|
||||
//
|
||||
exportMenuItem.Name = "exportMenuItem";
|
||||
exportMenuItem.Text = "Export...";
|
||||
exportMenuItem.ToolTipText = "Save this drawing's listed revision as DXF, SVG or an OpenNest nest";
|
||||
exportMenuItem.Click += ExportButton_Click;
|
||||
//
|
||||
// exportListedMenuItem
|
||||
//
|
||||
exportListedMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { exportListedDxfMenuItem, exportListedSvgMenuItem, exportListedNestMenuItem });
|
||||
exportListedMenuItem.Name = "exportListedMenuItem";
|
||||
exportListedMenuItem.Text = "Export Listed Drawings";
|
||||
exportListedMenuItem.ToolTipText = "Save every drawing on this page to a folder";
|
||||
//
|
||||
// exportListedDxfMenuItem
|
||||
//
|
||||
exportListedDxfMenuItem.Name = "exportListedDxfMenuItem";
|
||||
exportListedDxfMenuItem.Text = "As DXF...";
|
||||
exportListedDxfMenuItem.Click += ExportListedDxfMenuItem_Click;
|
||||
//
|
||||
// exportListedSvgMenuItem
|
||||
//
|
||||
exportListedSvgMenuItem.Name = "exportListedSvgMenuItem";
|
||||
exportListedSvgMenuItem.Text = "As SVG...";
|
||||
exportListedSvgMenuItem.Click += ExportListedSvgMenuItem_Click;
|
||||
//
|
||||
// exportListedNestMenuItem
|
||||
//
|
||||
exportListedNestMenuItem.Name = "exportListedNestMenuItem";
|
||||
exportListedNestMenuItem.Text = "As OpenNest Nests...";
|
||||
exportListedNestMenuItem.Click += ExportListedNestMenuItem_Click;
|
||||
//
|
||||
// DrawingLibraryView
|
||||
//
|
||||
AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
|
||||
@@ -941,5 +998,12 @@ namespace OpenNest.Controls
|
||||
private System.Windows.Forms.ToolStripSeparator releaseSeparator;
|
||||
private System.Windows.Forms.ToolStripMenuItem releaseMenuItem;
|
||||
private System.Windows.Forms.ToolStripMenuItem releasesMenuItem;
|
||||
private System.Windows.Forms.Button exportButton;
|
||||
private System.Windows.Forms.ToolStripSeparator exportSeparator;
|
||||
private System.Windows.Forms.ToolStripMenuItem exportMenuItem;
|
||||
private System.Windows.Forms.ToolStripMenuItem exportListedMenuItem;
|
||||
private System.Windows.Forms.ToolStripMenuItem exportListedDxfMenuItem;
|
||||
private System.Windows.Forms.ToolStripMenuItem exportListedSvgMenuItem;
|
||||
private System.Windows.Forms.ToolStripMenuItem exportListedNestMenuItem;
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using OpenNest.Data;
|
||||
using OpenNest.Desktop;
|
||||
using OpenNest.Forms;
|
||||
using OpenNest.IO;
|
||||
|
||||
@@ -81,6 +82,15 @@ namespace OpenNest.Controls
|
||||
/// <summary>Shows the set editor and returns the saved record, or null; replaced by tests.</summary>
|
||||
internal Func<DrawingSetEditSession, DrawingSetRecord> EditSet { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Asks where to save one drawing: the chosen file and format, or null when canceled;
|
||||
/// replaced by tests.
|
||||
/// </summary>
|
||||
internal Func<DrawingLibraryRecord, (string Path, LibraryExportFormat Format)?> ChooseExportFile { get; set; }
|
||||
|
||||
/// <summary>Asks for the folder Export Listed Drawings writes to, or null when canceled; replaced by tests.</summary>
|
||||
internal Func<string> ChooseExportFolder { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Adds a drawing read from the library, at a quantity, to the release: the host's
|
||||
/// release panel, or with a nest the release dialog; set by <see cref="EnableRelease(Action{DrawingLibraryRecord, int})"/>
|
||||
@@ -162,6 +172,28 @@ namespace OpenNest.Controls
|
||||
using var form = new DrawingLibraryFilterForm(filter, customers);
|
||||
return form.ShowDialog(DialogOwner) == DialogResult.OK ? form.Filter : null;
|
||||
};
|
||||
ChooseExportFile = record =>
|
||||
{
|
||||
using var dialog = new SaveFileDialog
|
||||
{
|
||||
Title = $"Export '{record.Name}'",
|
||||
Filter = LibraryDrawingExport.DialogFilter,
|
||||
FileName = LibraryDrawingExport.SuggestedFileName(record, LibraryExportFormat.Dxf),
|
||||
};
|
||||
if (dialog.ShowDialog(DialogOwner) != DialogResult.OK)
|
||||
return null;
|
||||
var format = LibraryDrawingExport.FromFilterIndex(dialog.FilterIndex);
|
||||
return (Path.ChangeExtension(dialog.FileName, LibraryDrawingExport.Extension(format)), format);
|
||||
};
|
||||
ChooseExportFolder = () =>
|
||||
{
|
||||
using var dialog = new FolderBrowserDialog
|
||||
{
|
||||
Description = "Export the listed drawings to",
|
||||
UseDescriptionForTitle = true,
|
||||
};
|
||||
return dialog.ShowDialog(DialogOwner) == DialogResult.OK ? dialog.SelectedPath : null;
|
||||
};
|
||||
LoadPreview = async (record, token) =>
|
||||
{
|
||||
var bytes = await library.GetRevisionPackageAsync(record.Id, record.Revision, token);
|
||||
@@ -498,6 +530,119 @@ namespace OpenNest.Controls
|
||||
addToSetMenuItem.Enabled = record != null && !adding;
|
||||
releaseMenuItem.Enabled = record is { Archived: false } && !adding && AddToRelease != null;
|
||||
releasesMenuItem.Enabled = record != null && !adding;
|
||||
exportMenuItem.Enabled = record != null && !adding;
|
||||
exportListedMenuItem.Enabled = session.Page?.Items.Count > 0 && !adding;
|
||||
}
|
||||
|
||||
private async void ExportButton_Click(object sender, EventArgs e) => await ExportSelectedAsync();
|
||||
|
||||
private async void ExportListedDxfMenuItem_Click(object sender, EventArgs e) =>
|
||||
await ExportListedAsync(LibraryExportFormat.Dxf);
|
||||
|
||||
private async void ExportListedSvgMenuItem_Click(object sender, EventArgs e) =>
|
||||
await ExportListedAsync(LibraryExportFormat.Svg);
|
||||
|
||||
private async void ExportListedNestMenuItem_Click(object sender, EventArgs e) =>
|
||||
await ExportListedAsync(LibraryExportFormat.Nest);
|
||||
|
||||
/// <summary>
|
||||
/// Saves the selected drawing's listed revision as DXF, SVG or its .nest package; the
|
||||
/// save dialog asks before replacing a file.
|
||||
/// </summary>
|
||||
internal async Task ExportSelectedAsync()
|
||||
{
|
||||
var record = SelectedRecord();
|
||||
if (record == null || adding)
|
||||
return;
|
||||
|
||||
var choice = ChooseExportFile(record);
|
||||
if (choice is not { } chosen || IsDisposed)
|
||||
return;
|
||||
|
||||
var result = await RunExportAsync(new[] { new LibraryExportTarget(record, chosen.Path) }, chosen.Format);
|
||||
if (result == null || IsDisposed)
|
||||
return;
|
||||
if (result.Written.Count == 1)
|
||||
{
|
||||
statusLabel.Text = $"Exported '{record.Name}' revision {record.Revision} to {chosen.Path}.";
|
||||
return;
|
||||
}
|
||||
|
||||
statusLabel.Text = "";
|
||||
if (result.Missing.Count > 0)
|
||||
{
|
||||
ShowMessage($"Revision {record.Revision} of '{record.Name}' is no longer on the server.",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Warning);
|
||||
await RunAsync(session.RefreshAsync);
|
||||
}
|
||||
else
|
||||
{
|
||||
ShowMessage($"Could not export '{record.Name}': {result.Failed[0].Reason}",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Saves every drawing on the current page to a chosen folder in <paramref name="format"/>,
|
||||
/// one file per drawing named after it. Asks once before replacing files already there.
|
||||
/// </summary>
|
||||
internal async Task ExportListedAsync(LibraryExportFormat format)
|
||||
{
|
||||
var records = session.Page?.Items ?? Array.Empty<DrawingLibraryRecord>();
|
||||
if (records.Count == 0 || adding)
|
||||
return;
|
||||
|
||||
var folder = ChooseExportFolder();
|
||||
if (string.IsNullOrWhiteSpace(folder) || IsDisposed)
|
||||
return;
|
||||
|
||||
var targets = LibraryDrawingExport.PlanFolder(records, folder, format);
|
||||
var existing = targets.Count(target => File.Exists(target.Path));
|
||||
if (existing > 0 && ShowMessage(
|
||||
$"{existing:N0} of the {targets.Count:N0} files already exist in {folder}. Replace them?",
|
||||
MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.OK)
|
||||
return;
|
||||
|
||||
var result = await RunExportAsync(targets, format);
|
||||
if (result == null || IsDisposed)
|
||||
return;
|
||||
|
||||
statusLabel.Text = $"Exported {result.Written.Count:N0} of {targets.Count:N0} drawings to {folder}.";
|
||||
var problems = result.Missing.Select(record => $"- {record.Name}: revision {record.Revision} is no longer on the server")
|
||||
.Concat(result.Failed.Select(failure => $"- {failure.Record.Name}: {failure.Reason}"))
|
||||
.ToList();
|
||||
if (problems.Count > 0)
|
||||
{
|
||||
const int shown = 15;
|
||||
var more = problems.Count > shown ? $"{Environment.NewLine}...and {problems.Count - shown:N0} more." : "";
|
||||
ShowMessage($"{problems.Count:N0} drawing{(problems.Count == 1 ? "" : "s")} could not be exported:"
|
||||
+ Environment.NewLine + string.Join(Environment.NewLine, problems.Take(shown)) + more,
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Warning);
|
||||
}
|
||||
}
|
||||
|
||||
// Runs an export with the commands disabled and progress in the status line; null if the view closed.
|
||||
private async Task<LibraryExportResult> RunExportAsync(IReadOnlyList<LibraryExportTarget> targets, LibraryExportFormat format)
|
||||
{
|
||||
adding = true;
|
||||
UpdateCommands();
|
||||
statusLabel.Text = targets.Count == 1 ? $"Exporting '{targets[0].Record.Name}'..." : $"Exporting 0 of {targets.Count:N0} drawings...";
|
||||
var progress = new Progress<int>(done =>
|
||||
{
|
||||
if (!IsDisposed && targets.Count > 1)
|
||||
statusLabel.Text = $"Exporting {done:N0} of {targets.Count:N0} drawings...";
|
||||
});
|
||||
try
|
||||
{
|
||||
var result = await LibraryDrawingExport.ExportAsync(library, targets, format, progress);
|
||||
return IsDisposed ? null : result;
|
||||
}
|
||||
finally
|
||||
{
|
||||
adding = false;
|
||||
if (!IsDisposed)
|
||||
UpdateCommands();
|
||||
}
|
||||
}
|
||||
|
||||
private async void ReleaseMenuItem_Click(object sender, EventArgs e) => await AddSelectedToReleaseAsync();
|
||||
@@ -813,6 +958,7 @@ namespace OpenNest.Controls
|
||||
addButton.Enabled = !adding && (nest != null ? SelectedRecord() != null
|
||||
: AddToRelease != null && SelectedRecord() is { Archived: false });
|
||||
editButton.Enabled = !adding && SelectedRecord() is { Archived: false };
|
||||
exportButton.Enabled = !adding && SelectedRecord() != null;
|
||||
}
|
||||
|
||||
private void UpdateFilterLabel(bool showAll = false)
|
||||
|
||||
@@ -480,6 +480,29 @@ release panel ([below](#make-nests-the-release-panel)); **Edit Drawing...** (the
|
||||
button or the right-click menu) edits it. Its right-click menu also has the set
|
||||
and release items below.
|
||||
|
||||
### Export from the Drawing Library (desktop)
|
||||
|
||||
Both forms of the browser can export without changing the library or any nest
|
||||
(`OpenNest.Desktop.LibraryDrawingExport`). Each export downloads the listed
|
||||
revision's exact package:
|
||||
|
||||
- **Export...** (the button under the details pane, or the drawing's right-click
|
||||
menu) saves the selected drawing, archived ones included, as **DXF** (the
|
||||
drawing's program), **SVG** (in the units the drawing was saved in, so it needs
|
||||
no scale on import) or **OpenNest nest** (the package as stored: a `.nest`
|
||||
holding the one drawing). The package leaves customer, color and nesting
|
||||
settings to the library record, so a `.nest` export carries geometry, units,
|
||||
bends and cut settings only.
|
||||
- **Export Listed Drawings > As DXF / As SVG / As OpenNest Nests...** (right-click
|
||||
menu) writes every drawing on the current page to a chosen folder, one file
|
||||
per drawing named after it; names the batch already used get " (2)", " (3)"...
|
||||
If files of those names are already there it asks once before replacing them.
|
||||
A revision no longer on the server or a file that cannot be written is listed
|
||||
at the end, and the rest still export.
|
||||
|
||||
Each file is written under a temporary name beside it and then moved into
|
||||
place, so a failure never leaves a partial file or damages one already there.
|
||||
|
||||
### Edit Drawing (desktop)
|
||||
|
||||
**Edit Drawing...** (`OpenNest.Data.DrawingLibraryEditSession`) edits one active
|
||||
|
||||
Reference in new issue
Block a user