mirror of
https://github.com/ajisaacs/OpenNest.git
synced 2026-12-01 06:41:42 -05:00
Merge M12 plates panel and plate commands into the Avalonia port work
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> # Conflicts: # OpenNest.Avalonia/MainWindow.axaml # OpenNest.Avalonia/MainWindow.axaml.cs
This commit is contained in:
commit
6f32d04cff
26 files changed
+2049
-141
No files matched your search
@@ -0,0 +1,97 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.Media;
|
||||
using OpenNest.Desktop;
|
||||
|
||||
namespace OpenNest.Avalonia.Controls
|
||||
{
|
||||
/// <summary>
|
||||
/// Edit Plate's quadrant picker, as the WinForms one: a square split in four with the plate
|
||||
/// origin's quadrant filled and numbered; a click picks the quadrant under the pointer. The
|
||||
/// arrow keys move it too.
|
||||
/// </summary>
|
||||
public sealed class QuadrantPicker : Control
|
||||
{
|
||||
private static readonly IBrush CellFill = Brush.Parse("#87CEFA");
|
||||
private static readonly IPen CellPen = new Pen(Brushes.Blue, 1);
|
||||
private static readonly IPen AxisPen = new Pen(Brushes.Gray, 1);
|
||||
|
||||
private int quadrant = 1;
|
||||
|
||||
public QuadrantPicker()
|
||||
{
|
||||
Focusable = true;
|
||||
MinWidth = 120;
|
||||
MinHeight = 90;
|
||||
}
|
||||
|
||||
/// <summary>The picked quadrant, 1 to 4; anything else is taken as 1.</summary>
|
||||
public int Quadrant
|
||||
{
|
||||
get => quadrant;
|
||||
set
|
||||
{
|
||||
var normalized = QuadrantPick.Normalize(value);
|
||||
if (normalized == quadrant)
|
||||
return;
|
||||
quadrant = normalized;
|
||||
InvalidateVisual();
|
||||
QuadrantChanged?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
}
|
||||
|
||||
public event EventHandler QuadrantChanged;
|
||||
|
||||
public override void Render(DrawingContext context)
|
||||
{
|
||||
var width = Bounds.Width;
|
||||
var height = Bounds.Height;
|
||||
context.FillRectangle(Brushes.White, new Rect(0, 0, width, height));
|
||||
context.DrawLine(AxisPen, new Point(width / 2, 0), new Point(width / 2, height));
|
||||
context.DrawLine(AxisPen, new Point(0, height / 2), new Point(width, height / 2));
|
||||
|
||||
var (x, y, w, h) = QuadrantPick.Cell(quadrant, width, height);
|
||||
var cell = new Rect(x, y, w, h).Deflate(0.5);
|
||||
context.FillRectangle(CellFill, cell);
|
||||
context.DrawRectangle(CellPen, cell);
|
||||
|
||||
var text = new FormattedText(
|
||||
quadrant.ToString(CultureInfo.InvariantCulture), CultureInfo.CurrentCulture,
|
||||
FlowDirection.LeftToRight, Typeface.Default, 35, Brushes.White);
|
||||
context.DrawText(text, new Point(
|
||||
x + (w - text.Width) / 2, y + (h - text.Height) / 2));
|
||||
}
|
||||
|
||||
protected override void OnPointerPressed(PointerPressedEventArgs e)
|
||||
{
|
||||
base.OnPointerPressed(e);
|
||||
if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)
|
||||
return;
|
||||
var at = e.GetPosition(this);
|
||||
Quadrant = QuadrantPick.At(at.X, at.Y, Bounds.Width, Bounds.Height);
|
||||
Focus();
|
||||
e.Handled = true;
|
||||
}
|
||||
|
||||
// Left and right cross the vertical axis, up and down the horizontal one.
|
||||
protected override void OnKeyDown(KeyEventArgs e)
|
||||
{
|
||||
base.OnKeyDown(e);
|
||||
var left = quadrant is 2 or 3;
|
||||
var top = quadrant is 1 or 2;
|
||||
switch (e.Key)
|
||||
{
|
||||
case Key.Left: left = true; break;
|
||||
case Key.Right: left = false; break;
|
||||
case Key.Up: top = true; break;
|
||||
case Key.Down: top = false; break;
|
||||
default: return;
|
||||
}
|
||||
Quadrant = left ? (top ? 2 : 3) : (top ? 1 : 4);
|
||||
e.Handled = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.Interactivity;
|
||||
using Avalonia.Layout;
|
||||
using Avalonia.Platform.Storage;
|
||||
using OpenNest.Avalonia.Controls;
|
||||
using OpenNest.Desktop;
|
||||
|
||||
namespace OpenNest.Avalonia
|
||||
{
|
||||
/// <summary>
|
||||
/// Plate > Edit, as the WinForms Edit Plate dialog: the plate's size, quantity, part and
|
||||
/// edge spacing, quadrant, and a rectangular sheet or an outline imported from a DXF, DWG or
|
||||
/// SVG file. While there is an outline the size is its bounds and cannot be typed. Done is
|
||||
/// enabled when the size parses and the edge spacing leaves room on the sheet; it returns
|
||||
/// the values (the caller writes the plate as one undo step), Cancel or Esc returns null.
|
||||
/// </summary>
|
||||
internal sealed class EditPlateDialog : Window
|
||||
{
|
||||
private static readonly FilePickerFileType CadFiles =
|
||||
new("CAD Files") { Patterns = new[] { "*.dxf", "*.dwg", "*.svg" } };
|
||||
|
||||
private readonly Units units;
|
||||
private readonly TextBox size = new() { Name = "Size", MinWidth = 160 };
|
||||
private readonly NumericUpDown quantity;
|
||||
private readonly NumericUpDown partSpacing;
|
||||
private readonly NumericUpDown left;
|
||||
private readonly NumericUpDown top;
|
||||
private readonly NumericUpDown right;
|
||||
private readonly NumericUpDown bottom;
|
||||
private readonly QuadrantPicker quadrant = new() { Name = "Quadrant", Width = 240, Height = 180 };
|
||||
private readonly TextBlock outlineText = new() { Name = "OutlineText", VerticalAlignment = VerticalAlignment.Center };
|
||||
private readonly Button clearOutline = new() { Name = "ClearOutline", Content = "Clear" };
|
||||
private readonly Button done = new() { Name = "Done", Content = "Done", IsDefault = true, MinWidth = 90 };
|
||||
private SheetOutline outline;
|
||||
|
||||
private EditPlateDialog(Plate plate, Units units)
|
||||
{
|
||||
this.units = units;
|
||||
Title = "Edit Plate";
|
||||
SizeToContent = SizeToContent.WidthAndHeight;
|
||||
CanResize = false;
|
||||
ShowInTaskbar = false;
|
||||
WindowStartupLocation = WindowStartupLocation.CenterOwner;
|
||||
|
||||
var values = PlateEditValues.FromPlate(plate);
|
||||
quantity = Box("Quantity", values.Quantity, decimals: 0, increment: 1);
|
||||
var increment = PlateEditValues.SpacingIncrement(units);
|
||||
partSpacing = Box("PartSpacing", values.PartSpacing, PlateEditValues.SpacingDecimals, increment);
|
||||
left = Box("Left", values.LeftSpacing, PlateEditValues.SpacingDecimals, increment);
|
||||
top = Box("Top", values.TopSpacing, PlateEditValues.SpacingDecimals, increment);
|
||||
right = Box("Right", values.RightSpacing, PlateEditValues.SpacingDecimals, increment);
|
||||
bottom = Box("Bottom", values.BottomSpacing, PlateEditValues.SpacingDecimals, increment);
|
||||
size.Text = values.Size.ToString();
|
||||
quadrant.Quadrant = values.Quadrant;
|
||||
SetOutline(values.Outline);
|
||||
|
||||
size.TextChanged += (_, _) => EnableCheck();
|
||||
foreach (var box in new[] { quantity, partSpacing, left, top, right, bottom })
|
||||
box.ValueChanged += (_, _) => EnableCheck();
|
||||
|
||||
var importOutline = new Button { Name = "ImportOutline", Content = "Outline..." };
|
||||
importOutline.Click += async (_, _) => await ImportOutlineAsync();
|
||||
clearOutline.Click += (_, _) => SetOutline(null);
|
||||
done.Click += (_, _) => Close(Values());
|
||||
var cancel = new Button { Content = "Cancel", IsCancel = true, MinWidth = 90 };
|
||||
cancel.Click += (_, _) => Close(null);
|
||||
|
||||
var unit = UnitsHelper.GetShortString(units);
|
||||
var sheet = new Grid
|
||||
{
|
||||
ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"),
|
||||
RowDefinitions = new RowDefinitions("Auto,Auto,Auto,Auto"),
|
||||
ColumnSpacing = 8,
|
||||
RowSpacing = 8,
|
||||
};
|
||||
AddRow(sheet, 0, "Size :", size, null);
|
||||
AddRow(sheet, 1, "Quantity :", quantity, null);
|
||||
var outlineRow = new StackPanel
|
||||
{
|
||||
Orientation = Orientation.Horizontal,
|
||||
Spacing = 6,
|
||||
Children = { outlineText, importOutline, clearOutline },
|
||||
};
|
||||
Grid.SetRow(outlineRow, 2);
|
||||
Grid.SetColumnSpan(outlineRow, 3);
|
||||
sheet.Children.Add(outlineRow);
|
||||
AddRow(sheet, 3, "Part Spacing :", partSpacing, unit);
|
||||
|
||||
var edges = new Grid
|
||||
{
|
||||
ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"),
|
||||
RowDefinitions = new RowDefinitions("Auto,Auto,Auto,Auto"),
|
||||
ColumnSpacing = 8,
|
||||
RowSpacing = 8,
|
||||
};
|
||||
AddRow(edges, 0, "Left :", left, unit);
|
||||
AddRow(edges, 1, "Top :", top, unit);
|
||||
AddRow(edges, 2, "Right :", right, unit);
|
||||
AddRow(edges, 3, "Bottom :", bottom, unit);
|
||||
|
||||
var leftColumn = new StackPanel
|
||||
{
|
||||
Spacing = 14,
|
||||
Width = 300,
|
||||
Children = { sheet, Group("Edge Spacing", edges) },
|
||||
};
|
||||
var columns = new StackPanel
|
||||
{
|
||||
Orientation = Orientation.Horizontal,
|
||||
Spacing = 18,
|
||||
Children = { leftColumn, Group("Quadrant", quadrant) },
|
||||
};
|
||||
Content = new StackPanel
|
||||
{
|
||||
Margin = new Thickness(18),
|
||||
Spacing = 18,
|
||||
Children =
|
||||
{
|
||||
columns,
|
||||
new StackPanel
|
||||
{
|
||||
Orientation = Orientation.Horizontal,
|
||||
HorizontalAlignment = HorizontalAlignment.Right,
|
||||
Spacing = 8,
|
||||
Children = { done, cancel },
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
AddHandler(KeyDownEvent, (_, e) =>
|
||||
{
|
||||
if (e.Key != Key.Escape)
|
||||
return;
|
||||
e.Handled = true;
|
||||
Close(null);
|
||||
}, RoutingStrategies.Tunnel);
|
||||
Opened += (_, _) => size.Focus();
|
||||
EnableCheck();
|
||||
}
|
||||
|
||||
/// <summary>The values to write to the plate, or null when the user cancelled.</summary>
|
||||
public static Task<PlateEditValues> ShowAsync(Window owner, Plate plate, Units units) =>
|
||||
new EditPlateDialog(plate, units).ShowDialog<PlateEditValues>(owner);
|
||||
|
||||
// As the WinForms boxes: 0 to 100, widened to hold a plate's larger value.
|
||||
private static NumericUpDown Box(string name, double value, int decimals, double increment) => new()
|
||||
{
|
||||
Name = name,
|
||||
Minimum = (decimal)PlateEditValues.BoxMinimum,
|
||||
Maximum = (decimal)System.Math.Max(PlateEditValues.BoxMaximum, value),
|
||||
Increment = (decimal)increment,
|
||||
ClipValueToMinMax = true,
|
||||
FormatString = decimals == 0 ? "0" : "0." + new string('0', decimals),
|
||||
Value = (decimal)value,
|
||||
MinWidth = 160,
|
||||
};
|
||||
|
||||
private static void AddRow(Grid grid, int row, string label, Control field, string suffix)
|
||||
{
|
||||
var text = new TextBlock { Text = label, VerticalAlignment = VerticalAlignment.Center };
|
||||
Grid.SetRow(text, row);
|
||||
grid.Children.Add(text);
|
||||
Grid.SetRow(field, row);
|
||||
Grid.SetColumn(field, 1);
|
||||
grid.Children.Add(field);
|
||||
if (suffix == null)
|
||||
return;
|
||||
var unit = new TextBlock { Text = suffix, VerticalAlignment = VerticalAlignment.Center };
|
||||
Grid.SetRow(unit, row);
|
||||
Grid.SetColumn(unit, 2);
|
||||
grid.Children.Add(unit);
|
||||
}
|
||||
|
||||
// A titled box, as the WinForms group boxes.
|
||||
private static Control Group(string header, Control content) => new StackPanel
|
||||
{
|
||||
Spacing = 4,
|
||||
Children =
|
||||
{
|
||||
new TextBlock { Text = header, FontWeight = global::Avalonia.Media.FontWeight.SemiBold },
|
||||
new Border
|
||||
{
|
||||
BorderBrush = global::Avalonia.Media.Brush.Parse("#C8CDD2"),
|
||||
BorderThickness = new Thickness(1),
|
||||
Padding = new Thickness(10),
|
||||
Child = content,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
private static double Number(NumericUpDown box) => (double)(box.Value ?? 0);
|
||||
|
||||
// Every value but the size, which is the size box's text or the outline's bounds.
|
||||
private PlateEditValues Values() => new()
|
||||
{
|
||||
Size = outline?.Size ?? (Geometry.Size.TryParse(size.Text, out var typed) ? typed : default),
|
||||
Quantity = (int)Number(quantity),
|
||||
PartSpacing = Number(partSpacing),
|
||||
LeftSpacing = Number(left),
|
||||
TopSpacing = Number(top),
|
||||
RightSpacing = Number(right),
|
||||
BottomSpacing = Number(bottom),
|
||||
Quadrant = quadrant.Quadrant,
|
||||
Outline = outline,
|
||||
};
|
||||
|
||||
private void EnableCheck() => done.IsEnabled = Values().CanApplyWithSize(size.Text, out _);
|
||||
|
||||
// An outlined sheet's size is its outline's bounds, so the size box is read-only.
|
||||
private void SetOutline(SheetOutline value)
|
||||
{
|
||||
outline = value;
|
||||
size.IsReadOnly = value != null;
|
||||
clearOutline.IsEnabled = value != null;
|
||||
if (value != null)
|
||||
size.Text = value.Size.ToString(4);
|
||||
outlineText.Text = PlateEditValues.OutlineText(value);
|
||||
EnableCheck();
|
||||
}
|
||||
|
||||
private async Task ImportOutlineAsync()
|
||||
{
|
||||
var files = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
|
||||
{
|
||||
Title = "Import Sheet Outline",
|
||||
AllowMultiple = false,
|
||||
FileTypeFilter = new[] { CadFiles },
|
||||
});
|
||||
var path = files.Count > 0 ? files[0].TryGetLocalPath() : null;
|
||||
if (path == null)
|
||||
return;
|
||||
try
|
||||
{
|
||||
var (import, perInch) = await SvgScaleDialog.ResolveAsync(this, path, units);
|
||||
if (!import)
|
||||
return;
|
||||
SetOutline(SheetOutlineImport.Read(path, units, perInch));
|
||||
}
|
||||
catch (Exception exception) when (SheetOutlineImport.IsReadFailure(exception))
|
||||
{
|
||||
await ConfirmDialog.ShowAsync(this, "Import Sheet Outline", SheetOutlineImport.FailureText(exception));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.Interactivity;
|
||||
using OpenNest.Data;
|
||||
using OpenNest.Desktop;
|
||||
|
||||
namespace OpenNest.Avalonia
|
||||
{
|
||||
/// <summary>
|
||||
/// The Plate menu's Edit, Set as Default, Rotate and Resize to Fit (Ctrl+P), and Nest >
|
||||
/// Remove Empty Plates, on the active nest's shown plate as in the WinForms main window. None
|
||||
/// runs while Auto Nest works on the nest.
|
||||
/// </summary>
|
||||
public partial class MainWindow
|
||||
{
|
||||
private void InitializePlateCommands() =>
|
||||
KeyBindings.Add(new KeyBinding
|
||||
{
|
||||
Gesture = new KeyGesture(Key.P, KeyModifiers.Control),
|
||||
Command = new Command(() => OnResizeToFit(null, null)),
|
||||
});
|
||||
|
||||
// The active view, when its plates can be changed now; otherwise says why not.
|
||||
private NestView PlateCommandView(string doing)
|
||||
{
|
||||
var view = ActiveView;
|
||||
if (view == null || IsNesting(view.Tab, doing) || !view.CanEditPlates)
|
||||
return null;
|
||||
return view;
|
||||
}
|
||||
|
||||
private async void OnEditPlate(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (PlateCommandView("editing a plate") is { } view)
|
||||
await view.EditCurrentPlateAsync();
|
||||
}
|
||||
|
||||
// As WinForms: the nest's next plates and every new nest start from the shown plate.
|
||||
private async void OnSetPlateAsDefault(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (PlateCommandView("changing its default plate") is not { } view
|
||||
|| view.SetPlateAsNestDefault() is not { } plate)
|
||||
return;
|
||||
var nest = view.Tab.Document.Nest;
|
||||
try
|
||||
{
|
||||
var machines = DesktopSettings.Machines;
|
||||
machines.SaveNestDefaults(PlateCommands.NewNestDefaults(nest, plate, machines.LoadSavedNestDefaults(out _)));
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
await ConfirmDialog.ShowAsync(this, "Nest Defaults",
|
||||
"The nest defaults could not be saved.\n\n" + ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnRotatePlateCw(object sender, RoutedEventArgs e) => RotatePlate(PlateRotation.Clockwise);
|
||||
|
||||
private void OnRotatePlateCcw(object sender, RoutedEventArgs e) => RotatePlate(PlateRotation.CounterClockwise);
|
||||
|
||||
private void OnRotatePlate180(object sender, RoutedEventArgs e) => RotatePlate(PlateRotation.HalfTurn);
|
||||
|
||||
private void RotatePlate(PlateRotation rotation) =>
|
||||
PlateCommandView("rotating a plate")?.RotatePlate(rotation);
|
||||
|
||||
// The rounding is Tools > Options' auto-size factor, read at each use as WinForms reads its setting.
|
||||
private void OnResizeToFit(object sender, RoutedEventArgs e) =>
|
||||
PlateCommandView("resizing a plate")?.ResizePlateToFit(
|
||||
DesktopOptions.Read(UserSettingsFile.Read(UserSettingsFile.DefaultPath)).AutoSizePlateFactor);
|
||||
|
||||
private void OnRemoveEmptyPlates(object sender, RoutedEventArgs e) =>
|
||||
PlateCommandView("removing its empty plates")?.RemoveEmptyPlates();
|
||||
}
|
||||
}
|
||||
@@ -48,8 +48,21 @@
|
||||
<MenuItem Header="_Previous Plate" InputGesture="Ctrl+Left" Click="OnPreviousPlate" />
|
||||
<Separator />
|
||||
<MenuItem x:Name="AutoNestMenuItem" Header="_Auto Nest" Click="OnAutoNest" />
|
||||
<MenuItem x:Name="RemoveEmptyPlatesMenuItem" Header="Remove _Empty Plates" Click="OnRemoveEmptyPlates" />
|
||||
</MenuItem>
|
||||
<MenuItem Header="_Plate">
|
||||
<MenuItem x:Name="EditPlateMenuItem" Header="_Edit" Click="OnEditPlate" />
|
||||
<MenuItem x:Name="SetPlateAsDefaultMenuItem" Header="Set as _Default" Click="OnSetPlateAsDefault" />
|
||||
<Separator />
|
||||
<MenuItem x:Name="RotatePlateMenuItem" Header="_Rotate">
|
||||
<MenuItem Header="90° CW" Click="OnRotatePlateCw" />
|
||||
<MenuItem Header="90° CCW" Click="OnRotatePlateCcw" />
|
||||
<Separator />
|
||||
<MenuItem Header="180°" Click="OnRotatePlate180" />
|
||||
</MenuItem>
|
||||
<!-- Ctrl+P is bound in MainWindow.Plates.cs. -->
|
||||
<MenuItem x:Name="ResizeToFitMenuItem" Header="Resize to _Fit" InputGesture="Ctrl+P" Click="OnResizeToFit" />
|
||||
<Separator />
|
||||
<!-- Plate > Arrange, as WinForms: MainWindow.Arrange.cs. -->
|
||||
<MenuItem x:Name="ArrangeMenu" Header="_Arrange" SubmenuOpened="OnArrangeMenuOpened">
|
||||
<MenuItem x:Name="AlignLeftMenuItem" Header="_Left" Tag="Left" Click="OnAlign" />
|
||||
|
||||
@@ -118,6 +118,7 @@ namespace OpenNest.Avalonia
|
||||
Command = new Command(() => OnSetRotationIncrement(null, null)),
|
||||
});
|
||||
AddViewKeyBindings();
|
||||
InitializePlateCommands();
|
||||
// Ctrl+Tab before focus navigation takes the Tab key.
|
||||
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
|
||||
// .nest files dropped anywhere on the window, the nest view included, open in tabs.
|
||||
|
||||
@@ -0,0 +1,341 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.Interactivity;
|
||||
using Avalonia.VisualTree;
|
||||
using OpenNest.Desktop;
|
||||
using OpenNest.Undo;
|
||||
|
||||
namespace OpenNest.Avalonia
|
||||
{
|
||||
/// <summary>
|
||||
/// The Plates tab list and the plate commands of the WinForms nest window, through the shared
|
||||
/// <see cref="PlateCommands"/>: a click shows a plate, a double-click edits it, its menu
|
||||
/// duplicates or deletes it, dragging a row moves the plate (Ctrl+drag copies it), and
|
||||
/// Alt+Up and Alt+Down move the current plate. Each is one undo step of the nest; none runs
|
||||
/// while Auto Nest works on it. The trailing empty plate stays last and cannot be dragged.
|
||||
/// </summary>
|
||||
public partial class NestView
|
||||
{
|
||||
/// <summary>The drag format carrying a <see cref="PlateDrag"/> within one nest's list.</summary>
|
||||
public const string PlateFormat = "OpenNest.Plate";
|
||||
|
||||
/// <summary>A plate row dragged in a nest's list.</summary>
|
||||
private sealed record PlateDrag(NestView Owner, int Index);
|
||||
|
||||
// While a plate command runs: the list rebuilds once it is done, on the plate it leaves current.
|
||||
private bool runningPlateCommand;
|
||||
private int pressedPlate = -1;
|
||||
private Point platePressPoint;
|
||||
|
||||
private ChangeScope BeginChange(string label) => Tab.Undo.BeginChange(label);
|
||||
|
||||
private void InitializePlateList()
|
||||
{
|
||||
PlateList.DoubleTapped += async (_, e) =>
|
||||
{
|
||||
if (RowUnder(e.Source) >= 0)
|
||||
await EditCurrentPlateAsync();
|
||||
};
|
||||
PlateList.AddHandler(KeyDownEvent, OnPlateListKeyDown, RoutingStrategies.Tunnel);
|
||||
PlateList.AddHandler(PointerPressedEvent, OnPlatePressed, RoutingStrategies.Tunnel,
|
||||
handledEventsToo: true);
|
||||
PlateList.AddHandler(PointerMovedEvent, OnPlateDragged, RoutingStrategies.Tunnel,
|
||||
handledEventsToo: true);
|
||||
PlateList.AddHandler(PointerReleasedEvent, (_, _) => pressedPlate = -1,
|
||||
RoutingStrategies.Tunnel, handledEventsToo: true);
|
||||
DragDrop.SetAllowDrop(PlateList, true);
|
||||
PlateList.AddHandler(DragDrop.DragEnterEvent, OnPlateDragOver);
|
||||
PlateList.AddHandler(DragDrop.DragOverEvent, OnPlateDragOver);
|
||||
PlateList.AddHandler(DragDrop.DragLeaveEvent, (_, _) => HidePlateDropIndicator());
|
||||
PlateList.AddHandler(DragDrop.DropEvent, OnPlateDrop);
|
||||
|
||||
DuplicatePlateMenuItem.Click += (_, _) => DuplicateCurrentPlate();
|
||||
DeletePlateMenuItem.Click += (_, _) => RemoveCurrentPlate();
|
||||
PlateMenu.Opening += (_, _) =>
|
||||
{
|
||||
SyncCurrentPlate();
|
||||
var index = plates.CurrentIndex;
|
||||
DuplicatePlateMenuItem.IsEnabled = !Canvas.EditsLocked && plates.CanDuplicatePlate(index, index + 1);
|
||||
DeletePlateMenuItem.IsEnabled = !Canvas.EditsLocked && plates.CanRemoveCurrent;
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether the plate commands can run: not while Auto Nest works on the nest, as the
|
||||
/// WinForms progress window prevents them.
|
||||
/// </summary>
|
||||
public bool CanEditPlates => !Canvas.EditsLocked;
|
||||
|
||||
// The manager's current plate follows the list, which other edits do not move.
|
||||
private void SyncCurrentPlate()
|
||||
{
|
||||
var index = PlateList.SelectedIndex;
|
||||
if (index >= 0 && index < plates.Count && index != plates.CurrentIndex)
|
||||
plates.LoadAt(index);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs a plate command of the current plate, then shows the plate the manager leaves
|
||||
/// current, keeping the zoom, pan and selection when <paramref name="keepView"/>.
|
||||
/// </summary>
|
||||
private bool RunPlateCommand(Action command, bool keepView)
|
||||
{
|
||||
if (!CanEditPlates)
|
||||
return false;
|
||||
SyncCurrentPlate();
|
||||
runningPlateCommand = true;
|
||||
try
|
||||
{
|
||||
command();
|
||||
}
|
||||
finally
|
||||
{
|
||||
runningPlateCommand = false;
|
||||
}
|
||||
ShowPlates(plates.CurrentIndex, keepView);
|
||||
return true;
|
||||
}
|
||||
|
||||
private void ShowPlates(int index, bool keep)
|
||||
{
|
||||
var shown = Canvas.Plate;
|
||||
keptSelection = keep && shown != null
|
||||
? (Canvas.Selection.PartIndices, shown.Parts.Count)
|
||||
: (Array.Empty<int>(), -1);
|
||||
keepView = keep;
|
||||
try
|
||||
{
|
||||
Refresh(index);
|
||||
}
|
||||
finally
|
||||
{
|
||||
keepView = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Delete Plate: removes the current plate.</summary>
|
||||
public void RemoveCurrentPlate() =>
|
||||
RunPlateCommand(() => PlateCommands.RemoveCurrentPlate(plates, BeginChange), keepView: false);
|
||||
|
||||
/// <summary>Duplicate Plate: a copy of the current plate right after it, which becomes current.</summary>
|
||||
public void DuplicateCurrentPlate()
|
||||
{
|
||||
SyncCurrentPlate();
|
||||
var index = plates.CurrentIndex;
|
||||
DuplicatePlate(index, index + 1);
|
||||
}
|
||||
|
||||
private void DuplicatePlate(int fromIndex, int toIndex)
|
||||
{
|
||||
if (plates.CanDuplicatePlate(fromIndex, toIndex))
|
||||
RunPlateCommand(() => PlateCommands.DuplicatePlate(plates, fromIndex, toIndex, BeginChange),
|
||||
keepView: false);
|
||||
}
|
||||
|
||||
private void MovePlate(int fromIndex, int toIndex)
|
||||
{
|
||||
if (plates.CanMovePlate(fromIndex, toIndex))
|
||||
RunPlateCommand(() => PlateCommands.MovePlate(plates, fromIndex, toIndex, BeginChange),
|
||||
keepView: true);
|
||||
}
|
||||
|
||||
/// <summary>Nest > Remove Empty Plates.</summary>
|
||||
public void RemoveEmptyPlates() =>
|
||||
RunPlateCommand(() => PlateCommands.RemoveEmptyPlates(Tab.Document.Nest, BeginChange), keepView: false);
|
||||
|
||||
/// <summary>Plate > Rotate, fitting the turned plate in the view.</summary>
|
||||
public void RotatePlate(PlateRotation rotation)
|
||||
{
|
||||
if (Canvas.Plate is { } plate)
|
||||
RunPlateCommand(() => PlateCommands.Rotate(plate, rotation, BeginChange), keepView: false);
|
||||
}
|
||||
|
||||
/// <summary>Plate > Resize to Fit, rounding up to <paramref name="roundingFactor"/>.</summary>
|
||||
public void ResizePlateToFit(double roundingFactor)
|
||||
{
|
||||
if (Canvas.Plate is { } plate)
|
||||
RunPlateCommand(() => PlateCommands.ResizeToFit(plate, roundingFactor, BeginChange), keepView: false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Plate > Set as Default, the nest's part: the shown plate becomes the nest's default
|
||||
/// plate. Returns the plate, for the caller to save as the new-nest defaults; null when
|
||||
/// nothing ran.
|
||||
/// </summary>
|
||||
public Plate SetPlateAsNestDefault()
|
||||
{
|
||||
var plate = Canvas.Plate;
|
||||
return plate != null
|
||||
&& RunPlateCommand(() => PlateCommands.SetAsNestDefault(Tab.Document.Nest, plates, plate, BeginChange),
|
||||
keepView: true)
|
||||
? plate
|
||||
: null;
|
||||
}
|
||||
|
||||
/// <summary>Plate > Edit (or a double-click in the list): the Edit Plate dialog for the shown plate.</summary>
|
||||
public async Task EditCurrentPlateAsync()
|
||||
{
|
||||
var plate = Canvas.Plate;
|
||||
if (plate == null || !CanEditPlates || TopLevel.GetTopLevel(this) is not Window owner)
|
||||
return;
|
||||
var values = await EditPlateDialog.ShowAsync(owner, plate, Tab.Document.Nest.Units);
|
||||
// The dialog is modal, but Auto Nest may have started on the nest before it opened.
|
||||
if (values == null || !Tab.Document.Nest.Plates.Contains(plate))
|
||||
return;
|
||||
RunPlateCommand(() => PlateCommands.EditPlate(Tab.Document.Nest, plates, plate, values, BeginChange),
|
||||
keepView: true);
|
||||
}
|
||||
|
||||
private void OnPlateListKeyDown(object sender, KeyEventArgs e)
|
||||
{
|
||||
if (e.KeyModifiers != KeyModifiers.Alt || e.Key is not (Key.Up or Key.Down))
|
||||
return;
|
||||
SyncCurrentPlate();
|
||||
var from = plates.CurrentIndex;
|
||||
MovePlate(from, PlateCommands.StepTarget(from, e.Key == Key.Up));
|
||||
e.Handled = true;
|
||||
}
|
||||
|
||||
private int RowUnder(object source) =>
|
||||
(source as Visual)?.FindAncestorOfType<ListBoxItem>(includeSelf: true) is { } item
|
||||
? PlateList.IndexFromContainer(item)
|
||||
: -1;
|
||||
|
||||
private void OnPlatePressed(object sender, PointerPressedEventArgs e)
|
||||
{
|
||||
var point = e.GetCurrentPoint(PlateList);
|
||||
pressedPlate = point.Properties.IsLeftButtonPressed && e.ClickCount == 1 ? RowUnder(e.Source) : -1;
|
||||
platePressPoint = point.Position;
|
||||
}
|
||||
|
||||
// A press moved more than 3 pixels drags the plate; the trailing empty plate stays put.
|
||||
private async void OnPlateDragged(object sender, PointerEventArgs e)
|
||||
{
|
||||
var index = pressedPlate;
|
||||
var point = e.GetCurrentPoint(PlateList);
|
||||
if (index < 0 || !point.Properties.IsLeftButtonPressed)
|
||||
return;
|
||||
var dx = point.Position.X - platePressPoint.X;
|
||||
var dy = point.Position.Y - platePressPoint.Y;
|
||||
if (dx * dx + dy * dy <= 9)
|
||||
return;
|
||||
pressedPlate = -1;
|
||||
if (!CanEditPlates || index >= plates.MovableCount)
|
||||
return;
|
||||
|
||||
var effects = DragDropEffects.None;
|
||||
if (plates.MovableCount >= 2)
|
||||
effects |= DragDropEffects.Move;
|
||||
if (plates.CanDuplicatePlate(index, index + 1))
|
||||
effects |= DragDropEffects.Copy;
|
||||
if (effects == DragDropEffects.None)
|
||||
return;
|
||||
|
||||
var data = new DataObject();
|
||||
data.Set(PlateFormat, new PlateDrag(this, index));
|
||||
try
|
||||
{
|
||||
await DragDrop.DoDragDrop(e, data, effects);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
System.Diagnostics.Debug.WriteLine($"Plate drag failed: {ex}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
HidePlateDropIndicator();
|
||||
}
|
||||
}
|
||||
|
||||
private PlateDrag DraggedPlate(DragEventArgs e) =>
|
||||
e.Data.Get(PlateFormat) is PlateDrag drag && ReferenceEquals(drag.Owner, this) ? drag : null;
|
||||
|
||||
// The gap the pointer is over: before the row under it in its upper half, after it
|
||||
// otherwise; the new-plate row and below drop after the last plate.
|
||||
private int DropSlot(DragEventArgs e)
|
||||
{
|
||||
var row = RowUnder(e.Source);
|
||||
var upperHalf = false;
|
||||
if (row >= 0 && PlateList.ContainerFromIndex(row) is { } item)
|
||||
upperHalf = e.GetPosition(item).Y < item.Bounds.Height / 2;
|
||||
return PlateListRow.DropSlot(row, upperHalf, plates.MovableCount);
|
||||
}
|
||||
|
||||
// Ctrl during the drag drops a copy where the plate allows one.
|
||||
private static bool IsCopyDrag(DragEventArgs e) =>
|
||||
e.KeyModifiers.HasFlag(KeyModifiers.Control);
|
||||
|
||||
private bool CanDrop(PlateDrag drag, int slot, bool copying) =>
|
||||
CanEditPlates && (copying
|
||||
? plates.CanDuplicatePlate(drag.Index, slot)
|
||||
: plates.CanMovePlate(drag.Index, PlateListRow.DropTarget(drag.Index, slot)));
|
||||
|
||||
private void OnPlateDragOver(object sender, DragEventArgs e)
|
||||
{
|
||||
if (!e.Data.Contains(PlateFormat))
|
||||
return;
|
||||
e.Handled = true;
|
||||
var drag = DraggedPlate(e);
|
||||
var slot = drag != null ? DropSlot(e) : -1;
|
||||
var copying = IsCopyDrag(e);
|
||||
if (drag == null || !CanDrop(drag, slot, copying))
|
||||
{
|
||||
e.DragEffects = DragDropEffects.None;
|
||||
HidePlateDropIndicator();
|
||||
return;
|
||||
}
|
||||
e.DragEffects = copying ? DragDropEffects.Copy : DragDropEffects.Move;
|
||||
ShowPlateDropIndicator(slot);
|
||||
}
|
||||
|
||||
private void OnPlateDrop(object sender, DragEventArgs e)
|
||||
{
|
||||
if (!e.Data.Contains(PlateFormat))
|
||||
return;
|
||||
e.Handled = true;
|
||||
HidePlateDropIndicator();
|
||||
var drag = DraggedPlate(e);
|
||||
if (drag == null)
|
||||
return;
|
||||
var slot = DropSlot(e);
|
||||
var copying = IsCopyDrag(e);
|
||||
if (!CanDrop(drag, slot, copying))
|
||||
{
|
||||
e.DragEffects = DragDropEffects.None;
|
||||
return;
|
||||
}
|
||||
e.DragEffects = copying ? DragDropEffects.Copy : DragDropEffects.Move;
|
||||
if (copying)
|
||||
DuplicatePlate(drag.Index, slot);
|
||||
else
|
||||
MovePlate(drag.Index, PlateListRow.DropTarget(drag.Index, slot));
|
||||
}
|
||||
|
||||
// A line along the top of the row at the slot, or the bottom of the last row before it.
|
||||
private void ShowPlateDropIndicator(int slot)
|
||||
{
|
||||
var count = PlateList.ItemCount;
|
||||
if (count == 0)
|
||||
return;
|
||||
var below = slot >= count;
|
||||
if (PlateList.ContainerFromIndex(below ? slot - 1 : slot) is not { } item)
|
||||
{
|
||||
HidePlateDropIndicator();
|
||||
return;
|
||||
}
|
||||
var edge = item.TranslatePoint(new Point(0, below ? item.Bounds.Height : 0), PlateListHost);
|
||||
if (edge is not { } at)
|
||||
{
|
||||
HidePlateDropIndicator();
|
||||
return;
|
||||
}
|
||||
PlateDropIndicator.Margin = new Thickness(0, System.Math.Max(0, at.Y - 1), 0, 0);
|
||||
PlateDropIndicator.IsVisible = true;
|
||||
}
|
||||
|
||||
private void HidePlateDropIndicator() => PlateDropIndicator.IsVisible = false;
|
||||
}
|
||||
}
|
||||
@@ -2,12 +2,42 @@
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:c="using:OpenNest.Avalonia.Controls"
|
||||
xmlns:local="using:OpenNest.Avalonia"
|
||||
xmlns:d="using:OpenNest.Desktop"
|
||||
x:Class="OpenNest.Avalonia.NestView">
|
||||
<Grid ColumnDefinitions="290,4,*">
|
||||
<Border Grid.Column="0" Background="White">
|
||||
<TabControl x:Name="SideTabs" Padding="0">
|
||||
<TabItem Header="Plates" FontSize="14" MinHeight="34">
|
||||
<ListBox x:Name="PlateList" SelectionChanged="OnPlateSelected" />
|
||||
<!-- As the WinForms list: drag a row to move the plate, Ctrl+drag to copy it, Alt+Up and
|
||||
Alt+Down to move the current plate, double-click to edit it (NestView.Plates.cs). -->
|
||||
<Panel x:Name="PlateListHost">
|
||||
<ListBox x:Name="PlateList" SelectionChanged="OnPlateSelected">
|
||||
<ListBox.ContextMenu>
|
||||
<ContextMenu x:Name="PlateMenu">
|
||||
<MenuItem x:Name="DuplicatePlateMenuItem" Header="Duplicate Plate" />
|
||||
<MenuItem x:Name="DeletePlateMenuItem" Header="Delete Plate" />
|
||||
</ContextMenu>
|
||||
</ListBox.ContextMenu>
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate x:DataType="d:PlateListRow">
|
||||
<Grid ColumnDefinitions="*,Auto" Margin="2,4">
|
||||
<StackPanel Spacing="2">
|
||||
<TextBlock Text="{Binding Name}" FontWeight="Bold" FontSize="13" />
|
||||
<TextBlock Text="{Binding Size}" Foreground="Gray" />
|
||||
<TextBlock Text="{Binding Parts}" Foreground="Gray" />
|
||||
<TextBlock Text="{Binding Utilization}" Foreground="Gray"
|
||||
IsVisible="{Binding Utilization, Converter={x:Static StringConverters.IsNotNullOrEmpty}}" />
|
||||
</StackPanel>
|
||||
<TextBlock Grid.Column="1" Text="{Binding Quantity}" FontSize="20" FontWeight="Bold"
|
||||
Foreground="Gray" VerticalAlignment="Center" Margin="8,0" />
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
<!-- Where a dragged plate drops. -->
|
||||
<Border x:Name="PlateDropIndicator" Height="2" Background="#3368A0"
|
||||
VerticalAlignment="Top" IsHitTestVisible="False" IsVisible="False" />
|
||||
</Panel>
|
||||
</TabItem>
|
||||
<TabItem Header="Drawings" FontSize="14" MinHeight="34">
|
||||
<DataGrid x:Name="DrawingGrid" x:DataType="local:DrawingRow" IsReadOnly="True"
|
||||
|
||||
@@ -52,6 +52,7 @@ namespace OpenNest.Avalonia
|
||||
Canvas.AddHandler(DragDrop.DragEnterEvent, OnDrawingDragOver);
|
||||
Canvas.AddHandler(DragDrop.DragOverEvent, OnDrawingDragOver);
|
||||
Canvas.AddHandler(DragDrop.DropEvent, OnDrawingDrop);
|
||||
InitializePlateList();
|
||||
}
|
||||
|
||||
/// <summary>The drag format carrying a <see cref="Drawing"/> from the list.</summary>
|
||||
@@ -229,10 +230,7 @@ namespace OpenNest.Avalonia
|
||||
// new nest shows Plate 1. Files leave empty plates out, so saving is unchanged. The
|
||||
// tab put it there on opening and the manager keeps it, so this only reads.
|
||||
Canvas.ClearCache();
|
||||
PlateList.ItemsSource = nest.Plates
|
||||
.Select((plate, i) =>
|
||||
$"Plate {i + 1} {SizeText(plate)} ({plate.Parts.Count} parts)")
|
||||
.ToList();
|
||||
PlateList.ItemsSource = PlateListRow.For(nest.Plates);
|
||||
PlateList.SelectedIndex = nest.Plates.Count > 0
|
||||
? System.Math.Clamp(selectIndex, 0, nest.Plates.Count - 1)
|
||||
: -1;
|
||||
@@ -264,6 +262,9 @@ namespace OpenNest.Avalonia
|
||||
// plate, its zoom and the selection, as an Undo does.
|
||||
private void RefreshCounts()
|
||||
{
|
||||
// A plate command shows the plate it leaves current itself.
|
||||
if (runningPlateCommand)
|
||||
return;
|
||||
var nest = Tab.Document.Nest;
|
||||
var counts = CountsText(nest);
|
||||
if (counts != shownCounts)
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Layout;
|
||||
using OpenNest.Desktop;
|
||||
|
||||
namespace OpenNest.Avalonia
|
||||
{
|
||||
/// <summary>
|
||||
/// What an SVG's numbers mean when the file does not state its real-world size, as the
|
||||
/// WinForms SVG Scale form asks, showing the size each choice gives. OK returns the chosen
|
||||
/// units per inch; Skip File, Esc or closing returns null and the file is not imported.
|
||||
/// </summary>
|
||||
internal sealed class SvgScaleDialog : Window
|
||||
{
|
||||
private SvgScaleDialog(string path, double width, double height, Units units)
|
||||
{
|
||||
Title = "SVG Scale";
|
||||
Width = 440;
|
||||
SizeToContent = SizeToContent.Height;
|
||||
CanResize = false;
|
||||
ShowInTaskbar = false;
|
||||
WindowStartupLocation = WindowStartupLocation.CenterOwner;
|
||||
|
||||
var size = new TextBlock();
|
||||
var choices = new List<(RadioButton Button, double PerInch)>();
|
||||
var options = new StackPanel { Spacing = 4 };
|
||||
foreach (var (text, perInch) in SvgScale.Choices)
|
||||
{
|
||||
var button = new RadioButton { Content = text, GroupName = "SvgScale", IsChecked = choices.Count == 0 };
|
||||
button.IsCheckedChanged += (_, _) => UpdateSize();
|
||||
choices.Add((button, perInch));
|
||||
options.Children.Add(button);
|
||||
}
|
||||
|
||||
double Chosen()
|
||||
{
|
||||
foreach (var (button, perInch) in choices)
|
||||
{
|
||||
if (button.IsChecked == true)
|
||||
return perInch;
|
||||
}
|
||||
return choices[0].PerInch;
|
||||
}
|
||||
|
||||
void UpdateSize() => size.Text = SvgScale.ImportedSizeText(width, height, Chosen(), units);
|
||||
UpdateSize();
|
||||
|
||||
var ok = new Button { Content = "OK", IsDefault = true, MinWidth = 80 };
|
||||
ok.Click += (_, _) => Close(Chosen());
|
||||
var skip = new Button { Content = "Skip File", IsCancel = true, MinWidth = 80 };
|
||||
skip.Click += (_, _) => Close(null);
|
||||
|
||||
Content = new StackPanel
|
||||
{
|
||||
Margin = new Thickness(18),
|
||||
Spacing = 12,
|
||||
Children =
|
||||
{
|
||||
new TextBlock { Text = SvgScale.Question(Path.GetFileName(path)), TextWrapping = global::Avalonia.Media.TextWrapping.Wrap },
|
||||
options,
|
||||
size,
|
||||
new StackPanel
|
||||
{
|
||||
Orientation = Orientation.Horizontal,
|
||||
HorizontalAlignment = HorizontalAlignment.Right,
|
||||
Spacing = 8,
|
||||
Children = { ok, skip },
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether to import <paramref name="path"/>, and the SVG user units per inch the user
|
||||
/// chose: null when the file needs no scale (not an SVG, or one stating its size).
|
||||
/// Import is false when the user skipped the file.
|
||||
/// </summary>
|
||||
public static async Task<(bool Import, double? UserUnitsPerInch)> ResolveAsync(
|
||||
Window owner, string path, Units units)
|
||||
{
|
||||
if (SvgScale.SizeToAsk(path) is not { } size)
|
||||
return (true, null);
|
||||
var chosen = await new SvgScaleDialog(path, size.Width, size.Height, units)
|
||||
.ShowDialog<double?>(owner);
|
||||
return (chosen != null, chosen);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
using OpenNest.CNC;
|
||||
using OpenNest.CommonLines;
|
||||
using OpenNest.Data;
|
||||
using OpenNest.Geometry;
|
||||
using OpenNest.Undo;
|
||||
|
||||
namespace OpenNest.Desktop.Tests.Plates;
|
||||
|
||||
public class PlateCommandsTests
|
||||
{
|
||||
/// <summary>
|
||||
/// A nest window's state: three plates with one part each, then the trailing empty plate the
|
||||
/// manager keeps, and a history started on it.
|
||||
/// </summary>
|
||||
private sealed class Env
|
||||
{
|
||||
public Env(int platesWithParts = 3)
|
||||
{
|
||||
var nest = TestNests.OneSquare();
|
||||
nest.PlateDefaults.Size = new Size(48, 96);
|
||||
var drawing = nest.Drawings.First();
|
||||
if (platesWithParts == 0)
|
||||
nest.Plates.Clear();
|
||||
else
|
||||
nest.Plates[0].Quantity = 1;
|
||||
for (var i = 1; i < platesWithParts; i++)
|
||||
{
|
||||
var plate = new Plate(new Size(48 + i, 96 + i)) { Quantity = 1 };
|
||||
plate.Parts.Add(new Part(drawing));
|
||||
nest.Plates.Add(plate);
|
||||
}
|
||||
nest.UpdateDrawingQuantities();
|
||||
Document = new Document { Nest = nest };
|
||||
Plates = new PlateManager(nest);
|
||||
Plates.EnsureSentinel();
|
||||
Undo = new NestUndoRecorder(Document);
|
||||
Undo.Reset();
|
||||
}
|
||||
|
||||
public Document Document { get; }
|
||||
public Nest Nest => Document.Nest;
|
||||
public PlateManager Plates { get; }
|
||||
public NestUndoRecorder Undo { get; }
|
||||
|
||||
public ChangeScope BeginChange(string label) => Undo.BeginChange(label);
|
||||
|
||||
public int Steps => Undo.History.UndoCount;
|
||||
|
||||
public IReadOnlyList<double> Lengths => Nest.Plates.Select(p => p.Size.Length).ToList();
|
||||
}
|
||||
|
||||
private static Part Square(Drawing drawing, double x, double y) => new(drawing, new Vector(x, y));
|
||||
|
||||
[Fact]
|
||||
public void RemoveCurrentPlate_IsOneRemovePlateStep_AndUndoes()
|
||||
{
|
||||
var env = new Env();
|
||||
env.Plates.LoadAt(1);
|
||||
|
||||
PlateCommands.RemoveCurrentPlate(env.Plates, env.BeginChange);
|
||||
|
||||
Assert.Equal([96, 98], env.Lengths.Take(2));
|
||||
Assert.Equal(3, env.Nest.Plates.Count);
|
||||
Assert.Equal("Undo Remove Plate", env.Undo.UndoText);
|
||||
env.Undo.Undo();
|
||||
Assert.Equal([96, 97, 98, 96], env.Lengths);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RemoveCurrentPlate_WithOnePlate_RecordsNothing()
|
||||
{
|
||||
var env = new Env(platesWithParts: 0);
|
||||
Assert.Single(env.Nest.Plates);
|
||||
|
||||
PlateCommands.RemoveCurrentPlate(env.Plates, env.BeginChange);
|
||||
|
||||
Assert.Single(env.Nest.Plates);
|
||||
Assert.False(env.Undo.CanUndo);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RemoveEmptyPlates_RemovesEmptyPlatesButKeepsTheTrailingOne()
|
||||
{
|
||||
var env = new Env();
|
||||
env.Nest.Plates[1].Parts.Clear();
|
||||
env.Undo.Reset();
|
||||
Assert.True(PlateCommands.HasEmptyPlatesToRemove(env.Nest));
|
||||
|
||||
PlateCommands.RemoveEmptyPlates(env.Nest, env.BeginChange);
|
||||
|
||||
Assert.Equal([96, 98, 96], env.Lengths);
|
||||
Assert.Empty(env.Nest.Plates[^1].Parts);
|
||||
Assert.Equal("Undo Remove Empty Plates", env.Undo.UndoText);
|
||||
Assert.False(PlateCommands.HasEmptyPlatesToRemove(env.Nest));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RemoveEmptyPlates_WithNoneToRemove_RecordsNothing()
|
||||
{
|
||||
var env = new Env();
|
||||
|
||||
PlateCommands.RemoveEmptyPlates(env.Nest, env.BeginChange);
|
||||
|
||||
Assert.Equal(4, env.Nest.Plates.Count);
|
||||
Assert.False(env.Undo.CanUndo);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DuplicatePlate_InsertsACopyThatBecomesCurrent_WithItsOwnCuttingParameters()
|
||||
{
|
||||
var env = new Env();
|
||||
var source = env.Nest.Plates[0];
|
||||
source.CuttingParameters = new CNC.CuttingStrategy.CuttingParameters();
|
||||
env.Undo.Reset();
|
||||
|
||||
var copy = PlateCommands.DuplicatePlate(env.Plates, 0, 1, env.BeginChange);
|
||||
|
||||
Assert.NotNull(copy);
|
||||
Assert.Same(copy, env.Nest.Plates[1]);
|
||||
Assert.Equal(1, env.Plates.CurrentIndex);
|
||||
Assert.Equal(source.Parts.Count, copy.Parts.Count);
|
||||
Assert.NotSame(source.CuttingParameters, copy.CuttingParameters);
|
||||
Assert.Equal(5, env.Nest.Plates.Count);
|
||||
Assert.Equal(1, env.Steps);
|
||||
Assert.Equal("Undo Duplicate Plate", env.Undo.UndoText);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DuplicatePlate_OfTheTrailingEmptyPlate_IsRefused()
|
||||
{
|
||||
var env = new Env();
|
||||
|
||||
Assert.Null(PlateCommands.DuplicatePlate(env.Plates, 3, 0, env.BeginChange));
|
||||
Assert.False(env.Undo.CanUndo);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MovePlate_ReordersAsOneStep_KeepingItCurrent()
|
||||
{
|
||||
var env = new Env();
|
||||
env.Plates.LoadAt(2);
|
||||
|
||||
Assert.True(PlateCommands.MovePlate(env.Plates, 2, 0, env.BeginChange));
|
||||
|
||||
Assert.Equal([98, 96, 97, 96], env.Lengths);
|
||||
Assert.Equal(0, env.Plates.CurrentIndex);
|
||||
Assert.Equal("Undo Move Plate", env.Undo.UndoText);
|
||||
env.Undo.Undo();
|
||||
Assert.Equal([96, 97, 98, 96], env.Lengths);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1, 1)]
|
||||
[InlineData(0, 3)]
|
||||
[InlineData(3, 0)]
|
||||
[InlineData(-1, 0)]
|
||||
public void MovePlate_ThatChangesNothingOrPassesTheTrailingPlate_IsRefused(int from, int to)
|
||||
{
|
||||
var env = new Env();
|
||||
|
||||
Assert.False(PlateCommands.MovePlate(env.Plates, from, to, env.BeginChange));
|
||||
Assert.False(env.Undo.CanUndo);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(2, true, 1)]
|
||||
[InlineData(2, false, 3)]
|
||||
public void StepTarget_IsOnePlaceUpOrDown(int current, bool up, int expected) =>
|
||||
Assert.Equal(expected, PlateCommands.StepTarget(current, up));
|
||||
|
||||
[Theory]
|
||||
[InlineData(PlateRotation.Clockwise)]
|
||||
[InlineData(PlateRotation.CounterClockwise)]
|
||||
public void Rotate_AQuarterTurn_SwapsTheSheetsSides(PlateRotation rotation)
|
||||
{
|
||||
var env = new Env();
|
||||
var plate = env.Nest.Plates[0];
|
||||
|
||||
PlateCommands.Rotate(plate, rotation, env.BeginChange);
|
||||
|
||||
Assert.Equal(new Size(96, 48), plate.Size);
|
||||
Assert.Equal("Undo Rotate Plate", env.Undo.UndoText);
|
||||
env.Undo.Undo();
|
||||
Assert.Equal(new Size(48, 96), env.Nest.Plates[0].Size);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Rotate_HalfTurn_KeepsTheSizeAndMovesTheParts()
|
||||
{
|
||||
var env = new Env();
|
||||
var plate = env.Nest.Plates[0];
|
||||
var before = plate.Parts[0].BoundingBox.Center;
|
||||
|
||||
PlateCommands.Rotate(plate, PlateRotation.HalfTurn, env.BeginChange);
|
||||
|
||||
Assert.Equal(new Size(48, 96), plate.Size);
|
||||
Assert.NotEqual(before, plate.Parts[0].BoundingBox.Center);
|
||||
Assert.Equal("Undo Rotate Plate", env.Undo.UndoText);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResizeToFit_ShrinksThePlateToItsPartsRoundedUp()
|
||||
{
|
||||
var env = new Env();
|
||||
var plate = env.Nest.Plates[0];
|
||||
plate.Parts.Add(Square(env.Nest.Drawings.First(), 20, 30));
|
||||
|
||||
PlateCommands.ResizeToFit(plate, 4, env.BeginChange);
|
||||
|
||||
Assert.True(plate.Size.Length < 96);
|
||||
Assert.Equal(0, plate.Size.Length % 4, 6);
|
||||
Assert.Equal(0, plate.Size.Width % 4, 6);
|
||||
Assert.Equal("Undo Resize Plate", env.Undo.UndoText);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SetAsNestDefault_MakesThePlateTheNestDefault_AndTheTrailingPlateFollows()
|
||||
{
|
||||
var env = new Env();
|
||||
var plate = env.Nest.Plates[1];
|
||||
plate.PartSpacing = 0.375;
|
||||
env.Undo.Reset();
|
||||
|
||||
PlateCommands.SetAsNestDefault(env.Nest, env.Plates, plate, env.BeginChange);
|
||||
|
||||
Assert.Equal(plate.Size, env.Nest.PlateDefaults.Size);
|
||||
Assert.Equal(0.375, env.Nest.PlateDefaults.PartSpacing);
|
||||
Assert.Equal(plate.Size, env.Nest.Plates[^1].Size);
|
||||
Assert.Equal("Undo Set Nest Default Plate", env.Undo.UndoText);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NewNestDefaults_TakeThePlateTheSavedCommonLineUsageAndTheNestsMachine()
|
||||
{
|
||||
var nest = TestNests.OneSquare();
|
||||
nest.Units = Units.Millimeters;
|
||||
var machine = Guid.NewGuid();
|
||||
nest.Machine = new NestMachine(machine, "Laser");
|
||||
var plate = nest.Plates[0];
|
||||
plate.Quadrant = 3;
|
||||
var saved = new NestDefaults { CommonLineUsage = CommonLineUsage.Whenever, MachineId = Guid.NewGuid() };
|
||||
|
||||
var defaults = PlateCommands.NewNestDefaults(nest, plate, saved);
|
||||
|
||||
Assert.Equal(Units.Millimeters, defaults.Units);
|
||||
Assert.Equal(plate.Size, defaults.Size);
|
||||
Assert.Equal(3, defaults.Quadrant);
|
||||
Assert.Equal(CommonLineUsage.Whenever, defaults.CommonLineUsage);
|
||||
Assert.Equal(machine, defaults.MachineId);
|
||||
|
||||
nest.Machine = null;
|
||||
Assert.Equal(saved.MachineId, PlateCommands.NewNestDefaults(nest, plate, saved).MachineId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EditPlate_WritesTheValuesAsOneStep_AndCountsQuantitiesAgain()
|
||||
{
|
||||
var env = new Env();
|
||||
var plate = env.Nest.Plates[0];
|
||||
var values = PlateEditValues.FromPlate(plate) with { Quantity = 3, PartSpacing = 0.5 };
|
||||
|
||||
PlateCommands.EditPlate(env.Nest, env.Plates, plate, values, env.BeginChange);
|
||||
|
||||
Assert.Equal(3, plate.Quantity);
|
||||
Assert.Equal(0.5, plate.PartSpacing);
|
||||
// Three sheets of plate 1 and one each of plates 2 and 3.
|
||||
Assert.Equal(5, env.Nest.Drawings.First().Quantity.Nested);
|
||||
Assert.Equal("Undo Edit Plate", env.Undo.UndoText);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EditPlate_Cancelled_RecordsNothing()
|
||||
{
|
||||
var env = new Env();
|
||||
|
||||
PlateCommands.EditPlate(env.Nest, env.Plates, env.Nest.Plates[0], null, env.BeginChange);
|
||||
|
||||
Assert.False(env.Undo.CanUndo);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EditPlate_OfAnEmptyPlate_MakesItsSettingsTheNestDefaults()
|
||||
{
|
||||
var env = new Env();
|
||||
var trailing = env.Nest.Plates[^1];
|
||||
var values = PlateEditValues.FromPlate(trailing) with { Size = new Size(60, 120), Quadrant = 2 };
|
||||
|
||||
PlateCommands.EditPlate(env.Nest, env.Plates, trailing, values, env.BeginChange);
|
||||
|
||||
Assert.Equal(new Size(60, 120), env.Nest.PlateDefaults.Size);
|
||||
Assert.Equal(2, env.Nest.PlateDefaults.Quadrant);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
using OpenNest.Geometry;
|
||||
|
||||
namespace OpenNest.Desktop.Tests.Plates;
|
||||
|
||||
public class PlateEditValuesTests
|
||||
{
|
||||
private static SheetOutline Ell() => new(new[]
|
||||
{
|
||||
new Vector(0, 0), new Vector(96, 0), new Vector(96, 24), new Vector(48, 24), new Vector(48, 48), new Vector(0, 48),
|
||||
});
|
||||
|
||||
[Fact]
|
||||
public void FromPlate_ReadsEveryValue_AndApplyToWritesThemBack()
|
||||
{
|
||||
var plate = new Plate(new Size(48, 96)) { Quantity = 4, PartSpacing = 0.25, Quadrant = 3 };
|
||||
plate.EdgeSpacing.Left = 1;
|
||||
plate.EdgeSpacing.Top = 2;
|
||||
plate.EdgeSpacing.Right = 3;
|
||||
plate.EdgeSpacing.Bottom = 4;
|
||||
|
||||
var values = PlateEditValues.FromPlate(plate);
|
||||
Assert.Equal(new Size(48, 96), values.Size);
|
||||
Assert.Equal(4, values.Quantity);
|
||||
Assert.Equal(0.25, values.PartSpacing);
|
||||
Assert.Equal(3, values.Quadrant);
|
||||
Assert.Equal((1, 2, 3, 4), (values.LeftSpacing, values.TopSpacing, values.RightSpacing, values.BottomSpacing));
|
||||
Assert.Null(values.Outline);
|
||||
|
||||
var other = new Plate(new Size(10, 10));
|
||||
values.ApplyTo(other);
|
||||
Assert.Equal(PlateEditValues.FromPlate(plate), PlateEditValues.FromPlate(other));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1, 1, 1, 1, true)]
|
||||
[InlineData(48, 48, 1, 1, false)] // left + right reach the length
|
||||
[InlineData(1, 1, 24, 24, false)] // top + bottom reach the width
|
||||
public void CanApply_NeedsRoomOnTheSheetBothWays(double left, double right, double top, double bottom, bool expected)
|
||||
{
|
||||
var values = new PlateEditValues
|
||||
{
|
||||
Size = new Size(48, 96),
|
||||
LeftSpacing = left,
|
||||
RightSpacing = right,
|
||||
TopSpacing = top,
|
||||
BottomSpacing = bottom,
|
||||
};
|
||||
|
||||
Assert.Equal(expected, values.CanApply);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CanApplyWithSize_NeedsASizeThatParses()
|
||||
{
|
||||
var values = new PlateEditValues();
|
||||
|
||||
Assert.True(values.CanApplyWithSize("48 x 96", out var size));
|
||||
Assert.Equal(new Size(48, 96), size);
|
||||
Assert.False(values.CanApplyWithSize("48 by", out _));
|
||||
Assert.False(values.CanApplyWithSize("0 x 0", out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnOutline_SetsTheSize_AndApplyKeepsIt()
|
||||
{
|
||||
var plate = new Plate(new Size(60, 120));
|
||||
var values = PlateEditValues.FromPlate(plate).WithOutline(Ell());
|
||||
|
||||
Assert.Equal(new Size(48, 96), values.Size);
|
||||
values.ApplyTo(plate);
|
||||
|
||||
Assert.Equal(Ell(), plate.Outline);
|
||||
Assert.Equal(new Size(48, 96), plate.Size);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ClearingTheOutline_LeavesARectangleOfTheSameSize()
|
||||
{
|
||||
var plate = new Plate { Outline = Ell(), Quadrant = 2 };
|
||||
var values = PlateEditValues.FromPlate(plate).WithOutline(null);
|
||||
|
||||
values.ApplyTo(plate);
|
||||
|
||||
Assert.Null(plate.Outline);
|
||||
Assert.Equal(new Size(48, 96), plate.Size);
|
||||
Assert.Equal(2, plate.Quadrant);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OutlineText_DescribesTheSheet()
|
||||
{
|
||||
Assert.Equal("Rectangular sheet", PlateEditValues.OutlineText(null));
|
||||
Assert.Equal("6 vertices", PlateEditValues.OutlineText(Ell()));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(Units.Inches, 0.25)]
|
||||
[InlineData(Units.Millimeters, 1)]
|
||||
public void SpacingIncrement_IsAQuarterInchOrAMillimeter(Units units, double expected) =>
|
||||
Assert.Equal(expected, PlateEditValues.SpacingIncrement(units));
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
using OpenNest.Geometry;
|
||||
|
||||
namespace OpenNest.Desktop.Tests.Plates;
|
||||
|
||||
public class PlateListRowTests
|
||||
{
|
||||
[Fact]
|
||||
public void APlateWithParts_ShowsItsNumberSizePartsAndUtilization()
|
||||
{
|
||||
var nest = TestNests.OneSquare();
|
||||
nest.Plates[0].Quantity = 3;
|
||||
nest.Plates.Add(new Plate(new Size(48, 96)));
|
||||
|
||||
var rows = PlateListRow.For(nest.Plates);
|
||||
|
||||
Assert.Equal("Plate 1", rows[0].Name);
|
||||
Assert.Equal(nest.Plates[0].Size.ToString(4), rows[0].Size);
|
||||
Assert.Equal("1 part", rows[0].Parts);
|
||||
Assert.Equal($"{nest.Plates[0].Utilization():P0} utilized", rows[0].Utilization);
|
||||
Assert.Equal("×3", rows[0].Quantity);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheTrailingEmptyPlate_IsTheNewPlate()
|
||||
{
|
||||
var nest = TestNests.OneSquare();
|
||||
nest.Plates.Add(new Plate(new Size(48, 96)));
|
||||
|
||||
var row = PlateListRow.For(nest.Plates, 1);
|
||||
|
||||
Assert.Equal("New plate", row.Name);
|
||||
Assert.Equal("Empty", row.Parts);
|
||||
Assert.Equal("", row.Utilization);
|
||||
Assert.Equal("", row.Quantity);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnEmptyPlateBeforeTheEnd_IsNumbered()
|
||||
{
|
||||
var nest = TestNests.OneSquare();
|
||||
nest.Plates.Insert(0, new Plate(new Size(48, 96)));
|
||||
|
||||
var row = PlateListRow.For(nest.Plates, 0);
|
||||
|
||||
Assert.Equal("Plate 1", row.Name);
|
||||
Assert.Equal("0 parts", row.Parts);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, true, 3, 0)]
|
||||
[InlineData(0, false, 3, 1)]
|
||||
[InlineData(2, false, 3, 3)]
|
||||
[InlineData(3, true, 3, 3)] // the new-plate row
|
||||
[InlineData(-1, false, 3, 3)] // below the rows
|
||||
public void DropSlot_IsBeforeOrAfterTheRowUnderThePointer(int row, bool upper, int movable, int expected) =>
|
||||
Assert.Equal(expected, PlateListRow.DropSlot(row, upper, movable));
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, 3, 2)]
|
||||
[InlineData(2, 0, 0)]
|
||||
[InlineData(1, 1, 1)]
|
||||
public void DropTarget_AccountsForTheDraggedPlatesOwnPlace(int from, int slot, int expected) =>
|
||||
Assert.Equal(expected, PlateListRow.DropTarget(from, slot));
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
namespace OpenNest.Desktop.Tests.Plates;
|
||||
|
||||
public class QuadrantPickTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(150, 20, 1)]
|
||||
[InlineData(20, 20, 2)]
|
||||
[InlineData(20, 150, 3)]
|
||||
[InlineData(150, 150, 4)]
|
||||
public void At_NumbersTheQuadrantsAsOnAGraph(double x, double y, int expected) =>
|
||||
Assert.Equal(expected, QuadrantPick.At(x, y, 200, 200));
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, 1)]
|
||||
[InlineData(5, 1)]
|
||||
[InlineData(3, 3)]
|
||||
public void Normalize_KeepsOneToFour(int value, int expected) =>
|
||||
Assert.Equal(expected, QuadrantPick.Normalize(value));
|
||||
|
||||
[Fact]
|
||||
public void Cell_IsTheQuadrantsQuarter()
|
||||
{
|
||||
Assert.Equal((100.0, 0.0, 100.0, 50.0), QuadrantPick.Cell(1, 200, 100));
|
||||
Assert.Equal((0.0, 0.0, 100.0, 50.0), QuadrantPick.Cell(2, 200, 100));
|
||||
Assert.Equal((0.0, 50.0, 100.0, 50.0), QuadrantPick.Cell(3, 200, 100));
|
||||
Assert.Equal((100.0, 50.0, 100.0, 50.0), QuadrantPick.Cell(4, 200, 100));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
namespace OpenNest.Desktop.Tests.Plates;
|
||||
|
||||
public sealed class SheetOutlineImportTests : IDisposable
|
||||
{
|
||||
private readonly string directory = Path.Combine(Path.GetTempPath(), "opennest-outline-" + Guid.NewGuid().ToString("N"));
|
||||
|
||||
public SheetOutlineImportTests() => Directory.CreateDirectory(directory);
|
||||
|
||||
public void Dispose() => Directory.Delete(directory, recursive: true);
|
||||
|
||||
private string Write(string name, string svg)
|
||||
{
|
||||
var path = Path.Combine(directory, name);
|
||||
File.WriteAllText(path, svg);
|
||||
return path;
|
||||
}
|
||||
|
||||
// A 96 x 48 sheet with a 10 x 10 hole.
|
||||
private const string Body =
|
||||
"<path d='M0 0 H96 V48 H0 Z'/><path d='M20 20 H30 V30 H20 Z'/>";
|
||||
|
||||
[Fact]
|
||||
public void Read_TakesTheLargestContourAsTheSheetAndTheOthersAsObstacles()
|
||||
{
|
||||
var path = Write("sheet.svg",
|
||||
$"<svg xmlns='http://www.w3.org/2000/svg' width='96in' height='48in' viewBox='0 0 96 48'>{Body}</svg>");
|
||||
|
||||
Assert.Null(SvgScale.SizeToAsk(path));
|
||||
var outline = SheetOutlineImport.Read(path, Units.Inches);
|
||||
|
||||
Assert.Equal(96, outline.Size.Length, 3);
|
||||
Assert.Equal(48, outline.Size.Width, 3);
|
||||
Assert.Single(outline.Obstacles);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnSvgWithoutAStatedSize_AsksForItsScale()
|
||||
{
|
||||
var path = Write("bare.svg", $"<svg xmlns='http://www.w3.org/2000/svg'>{Body}</svg>");
|
||||
|
||||
var size = SvgScale.SizeToAsk(path);
|
||||
|
||||
Assert.NotNull(size);
|
||||
var outline = SheetOutlineImport.Read(path, Units.Inches, svgUserUnitsPerInch: 1);
|
||||
Assert.Equal(96, outline.Size.Length, 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AFileWithNoClosedContour_IsAReadFailure()
|
||||
{
|
||||
var path = Write("line.svg",
|
||||
"<svg xmlns='http://www.w3.org/2000/svg' width='10in' height='10in' viewBox='0 0 10 10'><path d='M0 0 L10 10'/></svg>");
|
||||
|
||||
var error = Record.Exception(() => SheetOutlineImport.Read(path, Units.Inches));
|
||||
|
||||
Assert.NotNull(error);
|
||||
Assert.True(SheetOutlineImport.IsReadFailure(error));
|
||||
Assert.StartsWith("The file does not hold a sheet outline: ", SheetOutlineImport.FailureText(error));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ADxfIsNeverAskedForAScale() =>
|
||||
Assert.Null(SvgScale.SizeToAsk(Path.Combine(directory, "sheet.dxf")));
|
||||
|
||||
[Fact]
|
||||
public void ImportedSizeText_ShowsTheSizeInTheNestsUnits()
|
||||
{
|
||||
Assert.Equal("Imported size: 1.000 x 0.500 in", SvgScale.ImportedSizeText(96, 48, 96, Units.Inches));
|
||||
Assert.Equal("Imported size: 25.4 x 12.7 mm", SvgScale.ImportedSizeText(96, 48, 96, Units.Millimeters));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using OpenNest.Collections;
|
||||
using OpenNest.Data;
|
||||
using OpenNest.IO;
|
||||
using OpenNest.Undo;
|
||||
|
||||
namespace OpenNest.Desktop;
|
||||
|
||||
/// <summary>
|
||||
/// The nest window's plate commands, toolkit-neutral: the Plates list's Remove, Duplicate and
|
||||
/// Move, Nest > Remove Empty Plates and the Plate menu's Set as Default, Rotate, Resize to
|
||||
/// Fit and Edit. Each one is one undo step under the WinForms label, opened with
|
||||
/// <paramref name="beginChange"/> (the window's <c>BeginChange</c>). The plate manager keeps the
|
||||
/// trailing empty plate inside the step and says which plate is current afterwards.
|
||||
/// </summary>
|
||||
public static class PlateCommands
|
||||
{
|
||||
/// <summary>
|
||||
/// Removes the current plate as one "Remove Plate" step. With fewer than two plates nothing
|
||||
/// is removed and nothing is recorded; the empty plate removed from the end comes back.
|
||||
/// </summary>
|
||||
public static void RemoveCurrentPlate(PlateManager plates, Func<string, ChangeScope> beginChange)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plates);
|
||||
ArgumentNullException.ThrowIfNull(beginChange);
|
||||
using var change = beginChange("Remove Plate");
|
||||
if (plates.Count >= 2)
|
||||
change.MarkChanged();
|
||||
plates.RemoveCurrent();
|
||||
change.Complete();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether <see cref="RemoveEmptyPlates"/> would remove a plate: an empty one before the
|
||||
/// trailing empty plate, which comes back as the new-plate sentinel.
|
||||
/// </summary>
|
||||
public static bool HasEmptyPlatesToRemove(Nest nest)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(nest);
|
||||
return nest.Plates.Count >= 2 && nest.Plates.SkipLast(1).Any(plate => plate.Parts.Count == 0);
|
||||
}
|
||||
|
||||
/// <summary>Nest > Remove Empty Plates, as one "Remove Empty Plates" step.</summary>
|
||||
public static void RemoveEmptyPlates(Nest nest, Func<string, ChangeScope> beginChange)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(nest);
|
||||
ArgumentNullException.ThrowIfNull(beginChange);
|
||||
using var change = beginChange("Remove Empty Plates");
|
||||
if (HasEmptyPlatesToRemove(nest))
|
||||
change.MarkChanged();
|
||||
nest.Plates.RemoveEmptyPlates();
|
||||
change.Complete();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Inserts a copy of the plate at <paramref name="fromIndex"/> so it lands at
|
||||
/// <paramref name="toIndex"/>, as one "Duplicate Plate" step; the copy becomes the current
|
||||
/// plate and gets its own cutting parameters, so editing one sheet's leaves the other's alone.
|
||||
/// </summary>
|
||||
/// <returns>The copy, or null when the plate cannot be copied there (nothing is recorded).</returns>
|
||||
public static Plate DuplicatePlate(
|
||||
PlateManager plates, int fromIndex, int toIndex, Func<string, ChangeScope> beginChange)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plates);
|
||||
ArgumentNullException.ThrowIfNull(beginChange);
|
||||
if (!plates.CanDuplicatePlate(fromIndex, toIndex))
|
||||
return null;
|
||||
|
||||
using var change = beginChange("Duplicate Plate");
|
||||
change.MarkChanged();
|
||||
var copy = plates.DuplicatePlate(fromIndex, toIndex);
|
||||
if (copy.CuttingParameters != null)
|
||||
copy.CuttingParameters = CuttingParametersSerializer.FromDto(
|
||||
CuttingParametersSerializer.ToDto(copy.CuttingParameters));
|
||||
change.Complete();
|
||||
return copy;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves the plate at <paramref name="fromIndex"/> to <paramref name="toIndex"/> as one
|
||||
/// "Move Plate" step, keeping it the current plate.
|
||||
/// </summary>
|
||||
/// <returns>Whether the order changed; when it would not, nothing is recorded.</returns>
|
||||
public static bool MovePlate(
|
||||
PlateManager plates, int fromIndex, int toIndex, Func<string, ChangeScope> beginChange)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plates);
|
||||
ArgumentNullException.ThrowIfNull(beginChange);
|
||||
if (!plates.CanMovePlate(fromIndex, toIndex))
|
||||
return false;
|
||||
|
||||
using var change = beginChange("Move Plate");
|
||||
change.MarkChanged();
|
||||
plates.MovePlate(fromIndex, toIndex);
|
||||
change.Complete();
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The plate Alt+Up (<paramref name="up"/>) or Alt+Down moves the current plate to: one
|
||||
/// place earlier or later.
|
||||
/// </summary>
|
||||
public static int StepTarget(int currentIndex, bool up) => up ? currentIndex - 1 : currentIndex + 1;
|
||||
|
||||
/// <summary>
|
||||
/// Plate > Rotate: the plate and its parts turned a quarter turn either way or a half
|
||||
/// turn, keeping the quadrant, as one "Rotate Plate" step.
|
||||
/// </summary>
|
||||
public static void Rotate(Plate plate, PlateRotation rotation, Func<string, ChangeScope> beginChange)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plate);
|
||||
ArgumentNullException.ThrowIfNull(beginChange);
|
||||
using var change = beginChange("Rotate Plate");
|
||||
change.MarkChanged();
|
||||
switch (rotation)
|
||||
{
|
||||
case PlateRotation.Clockwise:
|
||||
plate.Rotate90(RotationType.CW);
|
||||
break;
|
||||
case PlateRotation.CounterClockwise:
|
||||
plate.Rotate90(RotationType.CCW);
|
||||
break;
|
||||
case PlateRotation.HalfTurn:
|
||||
plate.Rotate180();
|
||||
break;
|
||||
default:
|
||||
throw new ArgumentOutOfRangeException(nameof(rotation));
|
||||
}
|
||||
change.Complete();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Plate > Resize to Fit: the plate shrunk to its parts, rounded up to
|
||||
/// <paramref name="roundingFactor"/> (Tools > Options' auto-size factor), as one
|
||||
/// "Resize Plate" step.
|
||||
/// </summary>
|
||||
public static void ResizeToFit(Plate plate, double roundingFactor, Func<string, ChangeScope> beginChange)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plate);
|
||||
ArgumentNullException.ThrowIfNull(beginChange);
|
||||
using var change = beginChange("Resize Plate");
|
||||
change.MarkChanged();
|
||||
plate.AutoSize(roundingFactor);
|
||||
change.Complete();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Plate > Set as Default, the nest's part: <paramref name="plate"/>'s size, quadrant and
|
||||
/// spacing become the nest's plate defaults, saved with the nest, as one "Set Nest Default
|
||||
/// Plate" step. The trailing empty plate follows them while untouched. The front end then
|
||||
/// saves the plate as the defaults new nests start from (<see cref="NewNestDefaults"/>).
|
||||
/// </summary>
|
||||
public static void SetAsNestDefault(
|
||||
Nest nest, PlateManager plates, Plate plate, Func<string, ChangeScope> beginChange)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(nest);
|
||||
ArgumentNullException.ThrowIfNull(plates);
|
||||
ArgumentNullException.ThrowIfNull(plate);
|
||||
ArgumentNullException.ThrowIfNull(beginChange);
|
||||
using var change = beginChange("Set Nest Default Plate");
|
||||
change.MarkChanged();
|
||||
plates.ChangePlateDefaults(() => nest.PlateDefaults.SetFromExisting(plate));
|
||||
change.Complete();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The defaults new nests start from after Plate > Set as Default (or Tools > Save
|
||||
/// Current as Defaults): the plate's size, quadrant and spacing in the nest's units, the
|
||||
/// saved common-line usage (a plate holds none), and the nest's machine, or the saved choice
|
||||
/// for a nest without one.
|
||||
/// </summary>
|
||||
public static NestDefaults NewNestDefaults(Nest nest, Plate plate, NestDefaults saved)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(nest);
|
||||
ArgumentNullException.ThrowIfNull(plate);
|
||||
ArgumentNullException.ThrowIfNull(saved);
|
||||
var defaults = NestDefaults.FromPlate(nest.Units, plate, saved);
|
||||
defaults.MachineId = nest.Machine?.Id ?? saved.MachineId;
|
||||
return defaults;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Plate > Edit's commit: <paramref name="settings"/> written to the plate as one "Edit
|
||||
/// Plate" step (null, a cancelled dialog, records nothing). An empty plate's new settings
|
||||
/// become the nest's plate defaults (<see cref="FollowEditedPlate"/>), and the drawings'
|
||||
/// nested quantities are counted again, the plate's quantity being one of their factors.
|
||||
/// </summary>
|
||||
public static void EditPlate(
|
||||
Nest nest, PlateManager plates, Plate plate, PlateEditValues settings, Func<string, ChangeScope> beginChange)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(nest);
|
||||
ArgumentNullException.ThrowIfNull(plates);
|
||||
ArgumentNullException.ThrowIfNull(plate);
|
||||
ArgumentNullException.ThrowIfNull(beginChange);
|
||||
using var change = beginChange("Edit Plate");
|
||||
if (settings != null)
|
||||
{
|
||||
change.MarkChanged();
|
||||
settings.ApplyTo(plate);
|
||||
FollowEditedPlate(nest, plates, plate);
|
||||
}
|
||||
nest.UpdateDrawingQuantities();
|
||||
change.Complete();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// After Edit Plate wrote <paramref name="plate"/>: an empty plate's settings become the
|
||||
/// nest's plate defaults, the trailing empty plate following them while untouched.
|
||||
/// </summary>
|
||||
public static void FollowEditedPlate(Nest nest, PlateManager plates, Plate plate)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(nest);
|
||||
ArgumentNullException.ThrowIfNull(plates);
|
||||
ArgumentNullException.ThrowIfNull(plate);
|
||||
if (plate.Parts.Count == 0)
|
||||
plates.ChangePlateDefaults(() => nest.PlateDefaults.SetFromExisting(plate));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The turns of Plate > Rotate.</summary>
|
||||
public enum PlateRotation
|
||||
{
|
||||
/// <summary>90° CW.</summary>
|
||||
Clockwise,
|
||||
|
||||
/// <summary>90° CCW.</summary>
|
||||
CounterClockwise,
|
||||
|
||||
/// <summary>180°.</summary>
|
||||
HalfTurn,
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
using System;
|
||||
using OpenNest.Geometry;
|
||||
|
||||
namespace OpenNest.Desktop;
|
||||
|
||||
/// <summary>
|
||||
/// What the Edit Plate dialog edits: quantity, size, part and edge spacing, quadrant and the
|
||||
/// sheet outline. <see cref="FromPlate"/> reads a plate, <see cref="CanApply"/> is when the
|
||||
/// dialog's Done button is enabled and <see cref="ApplyTo"/> writes the plate as Done does.
|
||||
/// </summary>
|
||||
public sealed record PlateEditValues
|
||||
{
|
||||
/// <summary>The range of the dialog's quantity and spacing boxes (the WinForms box defaults).</summary>
|
||||
public const double BoxMinimum = 0;
|
||||
|
||||
public const double BoxMaximum = 100;
|
||||
|
||||
/// <summary>Decimals the spacing boxes show.</summary>
|
||||
public const int SpacingDecimals = 4;
|
||||
|
||||
public Size Size { get; init; }
|
||||
|
||||
public int Quantity { get; init; } = 1;
|
||||
|
||||
public double PartSpacing { get; init; }
|
||||
|
||||
public double LeftSpacing { get; init; }
|
||||
|
||||
public double TopSpacing { get; init; }
|
||||
|
||||
public double RightSpacing { get; init; }
|
||||
|
||||
public double BottomSpacing { get; init; }
|
||||
|
||||
/// <summary>The plate origin's quadrant, 1 to 4.</summary>
|
||||
public int Quadrant { get; init; } = 1;
|
||||
|
||||
/// <summary>
|
||||
/// The sheet outline the plate gets: null for a rectangular sheet. An outlined sheet's size
|
||||
/// is its outline's bounds (<see cref="WithOutline"/>).
|
||||
/// </summary>
|
||||
public SheetOutline Outline { get; init; }
|
||||
|
||||
/// <summary>The plate's current settings.</summary>
|
||||
public static PlateEditValues FromPlate(Plate plate)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plate);
|
||||
return new PlateEditValues
|
||||
{
|
||||
Size = plate.Size,
|
||||
Quantity = plate.Quantity,
|
||||
PartSpacing = plate.PartSpacing,
|
||||
LeftSpacing = plate.EdgeSpacing.Left,
|
||||
TopSpacing = plate.EdgeSpacing.Top,
|
||||
RightSpacing = plate.EdgeSpacing.Right,
|
||||
BottomSpacing = plate.EdgeSpacing.Bottom,
|
||||
Quadrant = plate.Quadrant,
|
||||
Outline = plate.Outline,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// These settings with <paramref name="outline"/> (null clears it, keeping the size); an
|
||||
/// outline sets the size to its bounds.
|
||||
/// </summary>
|
||||
public PlateEditValues WithOutline(SheetOutline outline) =>
|
||||
outline == null
|
||||
? this with { Outline = null }
|
||||
: this with { Outline = outline, Size = outline.Size };
|
||||
|
||||
/// <summary>
|
||||
/// Whether Done applies: the edge spacings leave room on the sheet both ways.
|
||||
/// </summary>
|
||||
public bool CanApply =>
|
||||
LeftSpacing + RightSpacing < Size.Length && TopSpacing + BottomSpacing < Size.Width;
|
||||
|
||||
/// <summary>
|
||||
/// Whether Done applies with <paramref name="sizeText"/> typed in the size box: it must
|
||||
/// parse as a size ("width x length"), and <see cref="CanApply"/> then holds for it.
|
||||
/// </summary>
|
||||
public bool CanApplyWithSize(string sizeText, out Size size) =>
|
||||
Size.TryParse(sizeText, out size) && (this with { Size = size }).CanApply;
|
||||
|
||||
/// <summary>Writes the settings to <paramref name="plate"/>, as the dialog's Done does.</summary>
|
||||
public void ApplyTo(Plate plate)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plate);
|
||||
// The outline carries its own size; setting the size would drop it.
|
||||
if (Outline != null)
|
||||
plate.Outline = Outline;
|
||||
else
|
||||
{
|
||||
plate.Size = Size;
|
||||
plate.Outline = null;
|
||||
}
|
||||
plate.EdgeSpacing.Left = LeftSpacing;
|
||||
plate.EdgeSpacing.Top = TopSpacing;
|
||||
plate.EdgeSpacing.Right = RightSpacing;
|
||||
plate.EdgeSpacing.Bottom = BottomSpacing;
|
||||
plate.PartSpacing = PartSpacing;
|
||||
plate.Quantity = Quantity;
|
||||
plate.Quadrant = Quadrant;
|
||||
}
|
||||
|
||||
/// <summary>The dialog's outline line: "Rectangular sheet" or its vertices and obstacles.</summary>
|
||||
public static string OutlineText(SheetOutline outline) =>
|
||||
outline == null
|
||||
? "Rectangular sheet"
|
||||
: $"{outline.Points.Count} vertices"
|
||||
+ (outline.Obstacles.Count == 0 ? "" : $", {outline.Obstacles.Count} obstacle(s)");
|
||||
|
||||
/// <summary>The step of the spacing boxes: a quarter inch, or one millimeter.</summary>
|
||||
public static double SpacingIncrement(Units units) => units == Units.Inches ? 0.25 : 1;
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace OpenNest.Desktop;
|
||||
|
||||
/// <summary>
|
||||
/// One row of the Plates tab list, as the WinForms list draws it: the plate's number ("New
|
||||
/// plate" for the trailing empty plate), its size, part count ("Empty" for the new plate),
|
||||
/// utilization once it holds parts, and how many sheets are cut from it when more than one.
|
||||
/// </summary>
|
||||
public sealed record PlateListRow(string Name, string Size, string Parts, string Utilization, string Quantity)
|
||||
{
|
||||
/// <summary>The row of the plate at <paramref name="index"/> among <paramref name="plates"/>.</summary>
|
||||
public static PlateListRow For(IList<Plate> plates, int index)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plates);
|
||||
var plate = plates[index];
|
||||
var isNewPlate = IsNewPlate(plates, index);
|
||||
var partCount = plate.Parts.Count(part => !part.BaseDrawing.IsCutOff);
|
||||
return new PlateListRow(
|
||||
isNewPlate ? "New plate" : $"Plate {index + 1}",
|
||||
plate.Size.ToString(4),
|
||||
isNewPlate ? "Empty" : $"{partCount} {(partCount == 1 ? "part" : "parts")}",
|
||||
partCount > 0 ? $"{plate.Utilization():P0} utilized" : "",
|
||||
plate.Quantity > 1 ? $"×{plate.Quantity}" : "");
|
||||
}
|
||||
|
||||
/// <summary>Every plate's row, in order.</summary>
|
||||
public static IReadOnlyList<PlateListRow> For(IList<Plate> plates)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plates);
|
||||
return Enumerable.Range(0, plates.Count).Select(i => For(plates, i)).ToList();
|
||||
}
|
||||
|
||||
/// <summary>The trailing empty plate the list shows as "New plate".</summary>
|
||||
public static bool IsNewPlate(IList<Plate> plates, int index) =>
|
||||
index == plates.Count - 1 && plates[index].Parts.Count == 0;
|
||||
|
||||
/// <summary>
|
||||
/// The gap a plate row dragged in the list is dropped into, 0 (before the first plate)
|
||||
/// through <paramref name="movableCount"/> (after the last movable plate): before the row
|
||||
/// under the pointer when in its upper half, after it otherwise. The new-plate row and below
|
||||
/// (<paramref name="rowIndex"/> -1) drop after the last plate.
|
||||
/// </summary>
|
||||
public static int DropSlot(int rowIndex, bool upperHalf, int movableCount)
|
||||
{
|
||||
if (rowIndex < 0)
|
||||
return movableCount;
|
||||
var slot = upperHalf ? rowIndex : rowIndex + 1;
|
||||
return System.Math.Min(slot, movableCount);
|
||||
}
|
||||
|
||||
/// <summary>The index a plate dragged from <paramref name="from"/> lands at when dropped in <paramref name="slot"/>.</summary>
|
||||
public static int DropTarget(int from, int slot) => slot > from ? slot - 1 : slot;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
namespace OpenNest.Desktop;
|
||||
|
||||
/// <summary>
|
||||
/// The Edit Plate dialog's quadrant picker: a square split in four, the plate origin's
|
||||
/// quadrant numbered as on a graph (1 upper right, 2 upper left, 3 lower left, 4 lower right).
|
||||
/// Coordinates are the control's, y growing down.
|
||||
/// </summary>
|
||||
public static class QuadrantPick
|
||||
{
|
||||
/// <summary><paramref name="value"/> when it is 1 to 4, otherwise 1, as the picker accepts it.</summary>
|
||||
public static int Normalize(int value) => value is >= 1 and <= 4 ? value : 1;
|
||||
|
||||
/// <summary>The quadrant a click at (<paramref name="x"/>, <paramref name="y"/>) picks.</summary>
|
||||
public static int At(double x, double y, double width, double height)
|
||||
{
|
||||
var left = x < width / 2;
|
||||
var top = y < height / 2;
|
||||
return left ? (top ? 2 : 3) : (top ? 1 : 4);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The highlighted cell of <paramref name="quadrant"/>: its left and top edges and size,
|
||||
/// in the control's coordinates.
|
||||
/// </summary>
|
||||
public static (double X, double Y, double Width, double Height) Cell(int quadrant, double width, double height)
|
||||
{
|
||||
var midX = width / 2;
|
||||
var midY = height / 2;
|
||||
return Normalize(quadrant) switch
|
||||
{
|
||||
1 => (midX, 0, width - midX, midY),
|
||||
2 => (0, 0, midX, midY),
|
||||
3 => (0, midY, midX, height - midY),
|
||||
_ => (midX, midY, width - midX, height - midY),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using OpenNest.IO;
|
||||
|
||||
namespace OpenNest.Desktop;
|
||||
|
||||
/// <summary>
|
||||
/// Edit Plate's Outline button: a sheet outline read from a DXF, DWG or SVG file, the largest
|
||||
/// closed contour being the sheet and every other closed contour an obstacle, in the file's
|
||||
/// units as drawings import. An SVG that does not state its real-world size needs the user to
|
||||
/// say what its units are first (<see cref="SvgScale"/>); import never guesses a scale.
|
||||
/// </summary>
|
||||
public static class SheetOutlineImport
|
||||
{
|
||||
/// <summary>
|
||||
/// Reads the outline. <paramref name="svgUserUnitsPerInch"/> is the scale the user chose
|
||||
/// for an SVG without a stated size, null otherwise.
|
||||
/// </summary>
|
||||
/// <exception cref="ArgumentException">The file holds no closed contour with an area.</exception>
|
||||
/// <exception cref="IOException">The file cannot be read.</exception>
|
||||
public static SheetOutline Read(string path, Units units, double? svgUserUnitsPerInch = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(path);
|
||||
var options = new CadImportOptions { DrawingUnits = units, SvgUserUnitsPerInch = svgUserUnitsPerInch };
|
||||
return SheetOutline.FromGeometry(CadImporter.Import(path, options).Entities);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether a failed read is the file not holding an outline (told to the user), rather than
|
||||
/// a fault in the app.
|
||||
/// </summary>
|
||||
public static bool IsReadFailure(Exception exception) =>
|
||||
exception is ArgumentException or IOException or InvalidOperationException or InvalidDataException;
|
||||
|
||||
/// <summary>What the user is told when <see cref="Read"/> fails.</summary>
|
||||
public static string FailureText(Exception exception) =>
|
||||
$"The file does not hold a sheet outline: {exception?.Message}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The scale prompt for an SVG that does not state its real-world size: what one of its units
|
||||
/// is, with the size each choice gives, so a wrong one is obvious before importing.
|
||||
/// </summary>
|
||||
public static class SvgScale
|
||||
{
|
||||
/// <summary>The choices, in the order offered; the first (CSS pixels) is the default.</summary>
|
||||
public static IReadOnlyList<(string Text, double UserUnitsPerInch)> Choices { get; } = new[]
|
||||
{
|
||||
("1/96 inch (web and Inkscape pixels)", 96.0),
|
||||
("1/72 inch (Illustrator points)", 72.0),
|
||||
("1 millimeter", 25.4),
|
||||
("1 inch", 1.0),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The SVG's width and height in its own units when the scale must be asked; null when the
|
||||
/// file is not an SVG, states its size, or cannot be read (the import then reports it).
|
||||
/// </summary>
|
||||
public static (double Width, double Height)? SizeToAsk(string path)
|
||||
{
|
||||
if (!Svg.IsSvg(path))
|
||||
return null;
|
||||
try
|
||||
{
|
||||
return Svg.UndeclaredSize(path);
|
||||
}
|
||||
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The prompt's question.</summary>
|
||||
public static string Question(string fileName) =>
|
||||
$"\"{fileName}\" does not state its real-world size. What is one of its units?";
|
||||
|
||||
/// <summary>The size the file imports at with <paramref name="userUnitsPerInch"/>, in <paramref name="units"/>.</summary>
|
||||
public static string ImportedSizeText(double width, double height, double userUnitsPerInch, Units units)
|
||||
{
|
||||
var perInch = units == Units.Millimeters ? 25.4 : 1;
|
||||
var scale = perInch / userUnitsPerInch;
|
||||
var format = units == Units.Millimeters ? "F1" : "F3";
|
||||
var unit = UnitsHelper.GetShortString(units);
|
||||
return $"Imported size: {(width * scale).ToString(format)} x {(height * scale).ToString(format)} {unit}";
|
||||
}
|
||||
}
|
||||
@@ -111,18 +111,13 @@ namespace OpenNest.Controls
|
||||
|
||||
g.DrawImage(GetPreview(plate), e.Bounds.X + 5, e.Bounds.Y + 5);
|
||||
|
||||
var isSentinel = e.Index == Items.Count - 1 && plate.Parts.Count == 0;
|
||||
var row = Desktop.PlateListRow.For(Items.Cast<Plate>().ToList(), e.Index);
|
||||
var pt = new PointF(e.Bounds.X + imageSize.Width + 15, e.Bounds.Y + 5);
|
||||
g.DrawString(isSentinel ? "New plate" : $"Plate {e.Index + 1}", nameFont, Brushes.Black, pt);
|
||||
g.DrawString(row.Name, nameFont, Brushes.Black, pt);
|
||||
|
||||
var partCount = plate.Parts.Count(part => !part.BaseDrawing.IsCutOff);
|
||||
var lines = new List<string>
|
||||
{
|
||||
plate.Size.ToString(4),
|
||||
isSentinel ? "Empty" : $"{partCount} {(partCount == 1 ? "part" : "parts")}",
|
||||
};
|
||||
if (partCount > 0)
|
||||
lines.Add($"{plate.Utilization():P0} utilized");
|
||||
var lines = new List<string> { row.Size, row.Parts };
|
||||
if (row.Utilization.Length > 0)
|
||||
lines.Add(row.Utilization);
|
||||
|
||||
foreach (var line in lines)
|
||||
{
|
||||
@@ -131,7 +126,7 @@ namespace OpenNest.Controls
|
||||
}
|
||||
|
||||
// How many sheets are cut from this layout, large at the right edge of the row.
|
||||
if (plate.Quantity > 1)
|
||||
if (row.Quantity.Length > 0)
|
||||
{
|
||||
var quantityBounds = new RectangleF(e.Bounds.X, e.Bounds.Y, e.Bounds.Width - 12, e.Bounds.Height);
|
||||
using var format = new StringFormat
|
||||
@@ -139,7 +134,7 @@ namespace OpenNest.Controls
|
||||
Alignment = StringAlignment.Far,
|
||||
LineAlignment = StringAlignment.Center,
|
||||
};
|
||||
g.DrawString($"×{plate.Quantity}", quantityFont, Brushes.Gray, quantityBounds, format);
|
||||
g.DrawString(row.Quantity, quantityFont, Brushes.Gray, quantityBounds, format);
|
||||
}
|
||||
|
||||
using var separatorPen = new Pen(Color.LightGray);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System.Drawing;
|
||||
using System.Drawing;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace OpenNest.Controls
|
||||
@@ -12,7 +12,7 @@ namespace OpenNest.Controls
|
||||
public int Quadrant
|
||||
{
|
||||
get { return quadrant; }
|
||||
set { quadrant = value <= 4 && value > 0 ? value : 1; }
|
||||
set { quadrant = Desktop.QuadrantPick.Normalize(value); }
|
||||
}
|
||||
|
||||
protected override void OnPaint(PaintEventArgs e)
|
||||
@@ -67,13 +67,8 @@ namespace OpenNest.Controls
|
||||
{
|
||||
base.OnMouseClick(e);
|
||||
|
||||
var midx = Width / 2;
|
||||
var midy = Height / 2;
|
||||
|
||||
if (e.X < midx)
|
||||
Quadrant = e.Y < midy ? 2 : 3;
|
||||
else
|
||||
Quadrant = e.Y < midy ? 1 : 4;
|
||||
// Whole pixels, as the control has always split itself.
|
||||
Quadrant = Desktop.QuadrantPick.At(e.X, e.Y, Width / 2 * 2, Height / 2 * 2);
|
||||
|
||||
Invalidate();
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using System.Drawing;
|
||||
using System.Windows.Forms;
|
||||
using OpenNest.Desktop;
|
||||
|
||||
namespace OpenNest.Forms
|
||||
{
|
||||
@@ -119,16 +120,8 @@ namespace OpenNest.Forms
|
||||
if (IsInspecting || !PlateManager.CanDuplicatePlate(fromIndex, toIndex))
|
||||
return false;
|
||||
|
||||
using (var change = BeginChange("Duplicate Plate"))
|
||||
{
|
||||
change.MarkChanged();
|
||||
var copy = PlateManager.DuplicatePlate(fromIndex, toIndex);
|
||||
// The copy gets its own parameters, so editing one sheet's leaves the other's alone.
|
||||
if (copy.CuttingParameters != null)
|
||||
copy.CuttingParameters = IO.CuttingParametersSerializer.FromDto(
|
||||
IO.CuttingParametersSerializer.ToDto(copy.CuttingParameters));
|
||||
change.Complete();
|
||||
}
|
||||
// The copy gets its own parameters, so editing one sheet's leaves the other's alone.
|
||||
PlateCommands.DuplicatePlate(PlateManager, fromIndex, toIndex, label => BeginChange(label));
|
||||
|
||||
FirePlateChanged();
|
||||
return true;
|
||||
@@ -151,12 +144,7 @@ namespace OpenNest.Forms
|
||||
if (IsInspecting || !PlateManager.CanMovePlate(fromIndex, toIndex))
|
||||
return false;
|
||||
|
||||
using (var change = BeginChange("Move Plate"))
|
||||
{
|
||||
change.MarkChanged();
|
||||
PlateManager.MovePlate(fromIndex, toIndex);
|
||||
change.Complete();
|
||||
}
|
||||
PlateCommands.MovePlate(PlateManager, fromIndex, toIndex, label => BeginChange(label));
|
||||
|
||||
// Navigation and the status bar read the current plate's index.
|
||||
FirePlateChanged();
|
||||
@@ -169,7 +157,7 @@ namespace OpenNest.Forms
|
||||
return;
|
||||
|
||||
var from = PlateManager.CurrentIndex;
|
||||
var to = e.KeyCode == Keys.Up ? from - 1 : from + 1;
|
||||
var to = PlateCommands.StepTarget(from, e.KeyCode == Keys.Up);
|
||||
MovePlate(from, to);
|
||||
e.Handled = true;
|
||||
e.SuppressKeyPress = true;
|
||||
@@ -269,12 +257,11 @@ namespace OpenNest.Forms
|
||||
}
|
||||
|
||||
var bounds = platesListView.GetItemRectangle(index);
|
||||
var slot = client.Y < bounds.Top + bounds.Height / 2 ? index : index + 1;
|
||||
return System.Math.Min(slot, movable);
|
||||
return PlateListRow.DropSlot(index, client.Y < bounds.Top + bounds.Height / 2, movable);
|
||||
}
|
||||
|
||||
/// <summary>The index a plate dragged from <paramref name="from"/> lands at when dropped in <paramref name="slot"/>.</summary>
|
||||
internal static int PlateDropTarget(int from, int slot) => slot > from ? slot - 1 : slot;
|
||||
internal static int PlateDropTarget(int from, int slot) => PlateListRow.DropTarget(from, slot);
|
||||
|
||||
private void ShowPlateDropIndicator(int slot)
|
||||
{
|
||||
|
||||
@@ -915,19 +915,19 @@ namespace OpenNest.Forms
|
||||
|
||||
public void RotateCw()
|
||||
{
|
||||
RecordChange("Rotate Plate", () => PlateView.Plate.Rotate90(RotationType.CW));
|
||||
PlateCommands.Rotate(PlateView.Plate, PlateRotation.Clockwise, label => BeginChange(label));
|
||||
PlateView.ZoomToFit();
|
||||
}
|
||||
|
||||
public void RotateCcw()
|
||||
{
|
||||
RecordChange("Rotate Plate", () => PlateView.Plate.Rotate90(RotationType.CCW));
|
||||
PlateCommands.Rotate(PlateView.Plate, PlateRotation.CounterClockwise, label => BeginChange(label));
|
||||
PlateView.ZoomToFit();
|
||||
}
|
||||
|
||||
public void Rotate180()
|
||||
{
|
||||
RecordChange("Rotate Plate", () => PlateView.Plate.Rotate180());
|
||||
PlateCommands.Rotate(PlateView.Plate, PlateRotation.HalfTurn, label => BeginChange(label));
|
||||
PlateView.ZoomToFit();
|
||||
}
|
||||
|
||||
@@ -1040,7 +1040,7 @@ namespace OpenNest.Forms
|
||||
|
||||
public void ResizePlateToFitParts()
|
||||
{
|
||||
RecordChange("Resize Plate", () => PlateView.Plate.AutoSize(Settings.Default.AutoSizePlateFactor));
|
||||
PlateCommands.ResizeToFit(PlateView.Plate, Settings.Default.AutoSizePlateFactor, label => BeginChange(label));
|
||||
PlateView.ZoomToPlate();
|
||||
PlateView.Refresh();
|
||||
UpdatePlateList();
|
||||
@@ -1103,8 +1103,7 @@ namespace OpenNest.Forms
|
||||
|
||||
// The defaults are saved with the nest and the trailing empty plate follows them.
|
||||
public void SetCurrentPlateAsNestDefault() =>
|
||||
RecordChange("Set Nest Default Plate",
|
||||
() => PlateManager.ChangePlateDefaults(() => Nest.PlateDefaults.SetFromExisting(PlateView.Plate)));
|
||||
PlateCommands.SetAsNestDefault(Nest, PlateManager, PlateView.Plate, label => BeginChange(label));
|
||||
|
||||
public void EditPlate()
|
||||
{
|
||||
@@ -1121,8 +1120,7 @@ namespace OpenNest.Forms
|
||||
UpdatePlateList();
|
||||
|
||||
// An empty plate's new settings become the nest's defaults.
|
||||
if (PlateView.Plate.Parts.Count == 0)
|
||||
PlateManager.ChangePlateDefaults(() => Nest.PlateDefaults.SetFromExisting(PlateView.Plate));
|
||||
PlateCommands.FollowEditedPlate(Nest, PlateManager, PlateView.Plate);
|
||||
}
|
||||
|
||||
Nest.UpdateDrawingQuantities();
|
||||
@@ -1172,14 +1170,7 @@ namespace OpenNest.Forms
|
||||
change.Complete();
|
||||
}
|
||||
|
||||
public void RemoveCurrentPlate()
|
||||
{
|
||||
using var change = BeginChange("Remove Plate");
|
||||
if (PlateManager.Count >= 2)
|
||||
change.MarkChanged();
|
||||
PlateManager.RemoveCurrent();
|
||||
change.Complete();
|
||||
}
|
||||
public void RemoveCurrentPlate() => PlateCommands.RemoveCurrentPlate(PlateManager, label => BeginChange(label));
|
||||
|
||||
public void ClearNest()
|
||||
{
|
||||
@@ -1190,15 +1181,8 @@ namespace OpenNest.Forms
|
||||
change.Complete();
|
||||
}
|
||||
|
||||
public void RemoveEmptyPlates()
|
||||
{
|
||||
using var change = BeginChange("Remove Empty Plates");
|
||||
// The trailing empty plate comes back as the new-plate sentinel.
|
||||
if (Nest.Plates.Count >= 2 && Nest.Plates.SkipLast(1).Any(plate => plate.Parts.Count == 0))
|
||||
change.MarkChanged();
|
||||
Nest.Plates.RemoveEmptyPlates();
|
||||
change.Complete();
|
||||
}
|
||||
// The trailing empty plate comes back as the new-plate sentinel.
|
||||
public void RemoveEmptyPlates() => PlateCommands.RemoveEmptyPlates(Nest, label => BeginChange(label));
|
||||
|
||||
public void AutoSequenceCurrentPlate()
|
||||
{
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Windows.Forms;
|
||||
using OpenNest.Desktop;
|
||||
using OpenNest.IO;
|
||||
using Timer = System.Windows.Forms.Timer;
|
||||
|
||||
@@ -54,12 +55,7 @@ namespace OpenNest.Forms
|
||||
private void SetUnits(Units units)
|
||||
{
|
||||
string suffix = " " + UnitsHelper.GetShortString(units);
|
||||
decimal increment;
|
||||
|
||||
if (units == Units.Inches)
|
||||
increment = 0.25m;
|
||||
else
|
||||
increment = 1;
|
||||
var increment = (decimal)PlateEditValues.SpacingIncrement(units);
|
||||
|
||||
var controls = new[]
|
||||
{
|
||||
@@ -141,71 +137,46 @@ namespace OpenNest.Forms
|
||||
buttonClearOutline.Enabled = value != null;
|
||||
if (value != null)
|
||||
textBoxSize.Text = value.Size.ToString(4);
|
||||
labelOutline.Text = value == null
|
||||
? "Rectangular sheet"
|
||||
: $"{value.Points.Count} vertices" + (value.Obstacles.Count == 0 ? "" : $", {value.Obstacles.Count} obstacle(s)");
|
||||
labelOutline.Text = PlateEditValues.OutlineText(value);
|
||||
EnableCheck();
|
||||
}
|
||||
}
|
||||
|
||||
public void EnableCheck()
|
||||
public void EnableCheck() => applyButton.Enabled = Values.CanApplyWithSize(SizeString, out _);
|
||||
|
||||
// The values but the size, which the size box holds as typed.
|
||||
private PlateEditValues Values => new()
|
||||
{
|
||||
OpenNest.Geometry.Size size;
|
||||
|
||||
if (!OpenNest.Geometry.Size.TryParse(SizeString, out size))
|
||||
{
|
||||
applyButton.Enabled = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (LeftSpacing + RightSpacing >= size.Length)
|
||||
{
|
||||
applyButton.Enabled = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (TopSpacing + BottomSpacing >= size.Width)
|
||||
{
|
||||
applyButton.Enabled = false;
|
||||
return;
|
||||
}
|
||||
|
||||
applyButton.Enabled = true;
|
||||
}
|
||||
LeftSpacing = LeftSpacing,
|
||||
TopSpacing = TopSpacing,
|
||||
RightSpacing = RightSpacing,
|
||||
BottomSpacing = BottomSpacing,
|
||||
PartSpacing = PartSpacing,
|
||||
Quantity = Quantity,
|
||||
Quadrant = Quadrant,
|
||||
Outline = Outline,
|
||||
};
|
||||
|
||||
private new void Load(Plate plate)
|
||||
{
|
||||
textBoxSize.Text = plate.Size.ToString();
|
||||
LeftSpacing = plate.EdgeSpacing.Left;
|
||||
TopSpacing = plate.EdgeSpacing.Top;
|
||||
RightSpacing = plate.EdgeSpacing.Right;
|
||||
BottomSpacing = plate.EdgeSpacing.Bottom;
|
||||
PartSpacing = plate.PartSpacing;
|
||||
Quantity = plate.Quantity;
|
||||
Quadrant = plate.Quadrant;
|
||||
Outline = plate.Outline;
|
||||
var values = PlateEditValues.FromPlate(plate);
|
||||
textBoxSize.Text = values.Size.ToString();
|
||||
LeftSpacing = values.LeftSpacing;
|
||||
TopSpacing = values.TopSpacing;
|
||||
RightSpacing = values.RightSpacing;
|
||||
BottomSpacing = values.BottomSpacing;
|
||||
PartSpacing = values.PartSpacing;
|
||||
Quantity = values.Quantity;
|
||||
Quadrant = values.Quadrant;
|
||||
Outline = values.Outline;
|
||||
}
|
||||
|
||||
/// <summary>Writes the dialog's values to the plate, as Done does.</summary>
|
||||
internal void Apply() => Save();
|
||||
|
||||
private void Save()
|
||||
{
|
||||
// The outline carries its own size; a parsed size would drop it.
|
||||
if (Outline != null)
|
||||
plate.Outline = Outline;
|
||||
else
|
||||
plate.Size = OpenNest.Geometry.Size.Parse(SizeString);
|
||||
if (Outline == null)
|
||||
plate.Outline = null;
|
||||
plate.EdgeSpacing.Left = LeftSpacing;
|
||||
plate.EdgeSpacing.Top = TopSpacing;
|
||||
plate.EdgeSpacing.Right = RightSpacing;
|
||||
plate.EdgeSpacing.Bottom = BottomSpacing;
|
||||
plate.PartSpacing = PartSpacing;
|
||||
plate.Quantity = Quantity;
|
||||
plate.Quadrant = Quadrant;
|
||||
}
|
||||
// The outline carries its own size; a parsed size would drop it.
|
||||
private void Save() =>
|
||||
(Values with { Size = Outline?.Size ?? OpenNest.Geometry.Size.Parse(SizeString) }).ApplyTo(plate);
|
||||
|
||||
private void textBox1_TextChanged(object sender, EventArgs e)
|
||||
{
|
||||
@@ -241,11 +212,11 @@ namespace OpenNest.Forms
|
||||
var options = new CadImportOptions { DrawingUnits = Units };
|
||||
if (!SvgScaleForm.TryResolve(this, dialog.FileName, options))
|
||||
return;
|
||||
Outline = SheetOutline.FromGeometry(CadImporter.Import(dialog.FileName, options).Entities);
|
||||
Outline = SheetOutlineImport.Read(dialog.FileName, Units, options.SvgUserUnitsPerInch);
|
||||
}
|
||||
catch (Exception exception) when (exception is ArgumentException or IOException or InvalidOperationException or InvalidDataException)
|
||||
catch (Exception exception) when (SheetOutlineImport.IsReadFailure(exception))
|
||||
{
|
||||
MessageBox.Show(this, $"The file does not hold a sheet outline: {exception.Message}",
|
||||
MessageBox.Show(this, SheetOutlineImport.FailureText(exception),
|
||||
"Import Sheet Outline", MessageBoxButtons.OK, MessageBoxIcon.Warning);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -266,8 +266,8 @@ namespace OpenNest.Forms
|
||||
return;
|
||||
|
||||
// A plate holds no common-line usage, so the saved defaults keep theirs.
|
||||
MachineSettings.SaveNestDefaults(this, NestDefaults.FromPlate(activeForm.Nest.Units, activeForm.PlateView.Plate,
|
||||
MachineSettings.LoadSavedNestDefaults(out _)), activeForm.Nest.Machine);
|
||||
MachineSettings.SaveNestDefaults(this, Desktop.PlateCommands.NewNestDefaults(activeForm.Nest,
|
||||
activeForm.PlateView.Plate, MachineSettings.LoadSavedNestDefaults(out _)));
|
||||
}
|
||||
|
||||
private void MachineConfig_Click(object sender, EventArgs e) => ShowMachineConfig(null);
|
||||
|
||||
@@ -26,7 +26,7 @@ namespace OpenNest.Forms
|
||||
fileWidth = width;
|
||||
fileHeight = height;
|
||||
this.units = units;
|
||||
labelMessage.Text = $"\"{fileName}\" does not state its real-world size. What is one of its units?";
|
||||
labelMessage.Text = Desktop.SvgScale.Question(fileName);
|
||||
UpdateSize(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
@@ -82,12 +82,7 @@ namespace OpenNest.Forms
|
||||
|
||||
private void UpdateSize(object sender, EventArgs e)
|
||||
{
|
||||
var perInch = units == Units.Millimeters ? 25.4 : 1;
|
||||
var scale = perInch / UserUnitsPerInch;
|
||||
var format = units == Units.Millimeters ? "F1" : "F3";
|
||||
var unit = UnitsHelper.GetShortString(units);
|
||||
labelSize.Text =
|
||||
$"Imported size: {(fileWidth * scale).ToString(format)} x {(fileHeight * scale).ToString(format)} {unit}";
|
||||
labelSize.Text = Desktop.SvgScale.ImportedSizeText(fileWidth, fileHeight, UserUnitsPerInch, units);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user