diff --git a/OpenNest.Avalonia/Controls/QuadrantPicker.cs b/OpenNest.Avalonia/Controls/QuadrantPicker.cs new file mode 100644 index 00000000..a88ef713 --- /dev/null +++ b/OpenNest.Avalonia/Controls/QuadrantPicker.cs @@ -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 +{ + /// + /// 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. + /// + 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; + } + + /// The picked quadrant, 1 to 4; anything else is taken as 1. + 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; + } + } +} diff --git a/OpenNest.Avalonia/EditPlateDialog.cs b/OpenNest.Avalonia/EditPlateDialog.cs new file mode 100644 index 00000000..84cbe71b --- /dev/null +++ b/OpenNest.Avalonia/EditPlateDialog.cs @@ -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 +{ + /// + /// 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. + /// + 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(); + } + + /// The values to write to the plate, or null when the user cancelled. + public static Task ShowAsync(Window owner, Plate plate, Units units) => + new EditPlateDialog(plate, units).ShowDialog(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)); + } + } + } +} diff --git a/OpenNest.Avalonia/MainWindow.Plates.cs b/OpenNest.Avalonia/MainWindow.Plates.cs new file mode 100644 index 00000000..bf2e27c7 --- /dev/null +++ b/OpenNest.Avalonia/MainWindow.Plates.cs @@ -0,0 +1,75 @@ +using System; +using System.IO; +using Avalonia.Input; +using Avalonia.Interactivity; +using OpenNest.Data; +using OpenNest.Desktop; + +namespace OpenNest.Avalonia +{ + /// + /// 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. + /// + 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(); + } +} diff --git a/OpenNest.Avalonia/MainWindow.axaml b/OpenNest.Avalonia/MainWindow.axaml index f8e2662f..f8788efa 100644 --- a/OpenNest.Avalonia/MainWindow.axaml +++ b/OpenNest.Avalonia/MainWindow.axaml @@ -48,8 +48,21 @@ + + + + + + + + + + + + + diff --git a/OpenNest.Avalonia/MainWindow.axaml.cs b/OpenNest.Avalonia/MainWindow.axaml.cs index 7938f4db..4e0040b4 100644 --- a/OpenNest.Avalonia/MainWindow.axaml.cs +++ b/OpenNest.Avalonia/MainWindow.axaml.cs @@ -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. diff --git a/OpenNest.Avalonia/NestView.Plates.cs b/OpenNest.Avalonia/NestView.Plates.cs new file mode 100644 index 00000000..af808d0b --- /dev/null +++ b/OpenNest.Avalonia/NestView.Plates.cs @@ -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 +{ + /// + /// The Plates tab list and the plate commands of the WinForms nest window, through the shared + /// : 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. + /// + public partial class NestView + { + /// The drag format carrying a within one nest's list. + public const string PlateFormat = "OpenNest.Plate"; + + /// A plate row dragged in a nest's list. + 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; + }; + } + + /// + /// Whether the plate commands can run: not while Auto Nest works on the nest, as the + /// WinForms progress window prevents them. + /// + 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); + } + + /// + /// Runs a plate command of the current plate, then shows the plate the manager leaves + /// current, keeping the zoom, pan and selection when . + /// + 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(), -1); + keepView = keep; + try + { + Refresh(index); + } + finally + { + keepView = false; + } + } + + /// Delete Plate: removes the current plate. + public void RemoveCurrentPlate() => + RunPlateCommand(() => PlateCommands.RemoveCurrentPlate(plates, BeginChange), keepView: false); + + /// Duplicate Plate: a copy of the current plate right after it, which becomes current. + 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); + } + + /// Nest > Remove Empty Plates. + public void RemoveEmptyPlates() => + RunPlateCommand(() => PlateCommands.RemoveEmptyPlates(Tab.Document.Nest, BeginChange), keepView: false); + + /// Plate > Rotate, fitting the turned plate in the view. + public void RotatePlate(PlateRotation rotation) + { + if (Canvas.Plate is { } plate) + RunPlateCommand(() => PlateCommands.Rotate(plate, rotation, BeginChange), keepView: false); + } + + /// Plate > Resize to Fit, rounding up to . + public void ResizePlateToFit(double roundingFactor) + { + if (Canvas.Plate is { } plate) + RunPlateCommand(() => PlateCommands.ResizeToFit(plate, roundingFactor, BeginChange), keepView: false); + } + + /// + /// 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. + /// + public Plate SetPlateAsNestDefault() + { + var plate = Canvas.Plate; + return plate != null + && RunPlateCommand(() => PlateCommands.SetAsNestDefault(Tab.Document.Nest, plates, plate, BeginChange), + keepView: true) + ? plate + : null; + } + + /// Plate > Edit (or a double-click in the list): the Edit Plate dialog for the shown plate. + 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(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; + } +} diff --git a/OpenNest.Avalonia/NestView.axaml b/OpenNest.Avalonia/NestView.axaml index c9bbf2bc..61304dd2 100644 --- a/OpenNest.Avalonia/NestView.axaml +++ b/OpenNest.Avalonia/NestView.axaml @@ -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"> - + + + + + + + + + + + + + + + + + + + + + + + + + + The drag format carrying a from the list. @@ -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) diff --git a/OpenNest.Avalonia/SvgScaleDialog.cs b/OpenNest.Avalonia/SvgScaleDialog.cs new file mode 100644 index 00000000..f7a57fa4 --- /dev/null +++ b/OpenNest.Avalonia/SvgScaleDialog.cs @@ -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 +{ + /// + /// 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. + /// + 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 }, + }, + }, + }; + } + + /// + /// Whether to import , 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. + /// + 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(owner); + return (chosen != null, chosen); + } + } +} diff --git a/OpenNest.Desktop.Tests/Plates/PlateCommandsTests.cs b/OpenNest.Desktop.Tests/Plates/PlateCommandsTests.cs new file mode 100644 index 00000000..a0c8fb92 --- /dev/null +++ b/OpenNest.Desktop.Tests/Plates/PlateCommandsTests.cs @@ -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 +{ + /// + /// 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. + /// + 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 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); + } +} diff --git a/OpenNest.Desktop.Tests/Plates/PlateEditValuesTests.cs b/OpenNest.Desktop.Tests/Plates/PlateEditValuesTests.cs new file mode 100644 index 00000000..99a93e97 --- /dev/null +++ b/OpenNest.Desktop.Tests/Plates/PlateEditValuesTests.cs @@ -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)); +} diff --git a/OpenNest.Desktop.Tests/Plates/PlateListRowTests.cs b/OpenNest.Desktop.Tests/Plates/PlateListRowTests.cs new file mode 100644 index 00000000..48eee7b8 --- /dev/null +++ b/OpenNest.Desktop.Tests/Plates/PlateListRowTests.cs @@ -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)); +} diff --git a/OpenNest.Desktop.Tests/Plates/QuadrantPickTests.cs b/OpenNest.Desktop.Tests/Plates/QuadrantPickTests.cs new file mode 100644 index 00000000..946bfbcf --- /dev/null +++ b/OpenNest.Desktop.Tests/Plates/QuadrantPickTests.cs @@ -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)); + } +} diff --git a/OpenNest.Desktop.Tests/Plates/SheetOutlineImportTests.cs b/OpenNest.Desktop.Tests/Plates/SheetOutlineImportTests.cs new file mode 100644 index 00000000..ae2b309b --- /dev/null +++ b/OpenNest.Desktop.Tests/Plates/SheetOutlineImportTests.cs @@ -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 = + ""; + + [Fact] + public void Read_TakesTheLargestContourAsTheSheetAndTheOthersAsObstacles() + { + var path = Write("sheet.svg", + $"{Body}"); + + 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", $"{Body}"); + + 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", + ""); + + 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)); + } +} diff --git a/OpenNest.Desktop/PlateCommands.cs b/OpenNest.Desktop/PlateCommands.cs new file mode 100644 index 00000000..05db9624 --- /dev/null +++ b/OpenNest.Desktop/PlateCommands.cs @@ -0,0 +1,232 @@ +using System; +using System.Linq; +using OpenNest.Collections; +using OpenNest.Data; +using OpenNest.IO; +using OpenNest.Undo; + +namespace OpenNest.Desktop; + +/// +/// 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 +/// (the window's BeginChange). The plate manager keeps the +/// trailing empty plate inside the step and says which plate is current afterwards. +/// +public static class PlateCommands +{ + /// + /// 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. + /// + public static void RemoveCurrentPlate(PlateManager plates, Func beginChange) + { + ArgumentNullException.ThrowIfNull(plates); + ArgumentNullException.ThrowIfNull(beginChange); + using var change = beginChange("Remove Plate"); + if (plates.Count >= 2) + change.MarkChanged(); + plates.RemoveCurrent(); + change.Complete(); + } + + /// + /// Whether would remove a plate: an empty one before the + /// trailing empty plate, which comes back as the new-plate sentinel. + /// + public static bool HasEmptyPlatesToRemove(Nest nest) + { + ArgumentNullException.ThrowIfNull(nest); + return nest.Plates.Count >= 2 && nest.Plates.SkipLast(1).Any(plate => plate.Parts.Count == 0); + } + + /// Nest > Remove Empty Plates, as one "Remove Empty Plates" step. + public static void RemoveEmptyPlates(Nest nest, Func beginChange) + { + ArgumentNullException.ThrowIfNull(nest); + ArgumentNullException.ThrowIfNull(beginChange); + using var change = beginChange("Remove Empty Plates"); + if (HasEmptyPlatesToRemove(nest)) + change.MarkChanged(); + nest.Plates.RemoveEmptyPlates(); + change.Complete(); + } + + /// + /// Inserts a copy of the plate at so it lands at + /// , 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. + /// + /// The copy, or null when the plate cannot be copied there (nothing is recorded). + public static Plate DuplicatePlate( + PlateManager plates, int fromIndex, int toIndex, Func 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; + } + + /// + /// Moves the plate at to as one + /// "Move Plate" step, keeping it the current plate. + /// + /// Whether the order changed; when it would not, nothing is recorded. + public static bool MovePlate( + PlateManager plates, int fromIndex, int toIndex, Func 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; + } + + /// + /// The plate Alt+Up () or Alt+Down moves the current plate to: one + /// place earlier or later. + /// + public static int StepTarget(int currentIndex, bool up) => up ? currentIndex - 1 : currentIndex + 1; + + /// + /// 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. + /// + public static void Rotate(Plate plate, PlateRotation rotation, Func 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(); + } + + /// + /// Plate > Resize to Fit: the plate shrunk to its parts, rounded up to + /// (Tools > Options' auto-size factor), as one + /// "Resize Plate" step. + /// + public static void ResizeToFit(Plate plate, double roundingFactor, Func beginChange) + { + ArgumentNullException.ThrowIfNull(plate); + ArgumentNullException.ThrowIfNull(beginChange); + using var change = beginChange("Resize Plate"); + change.MarkChanged(); + plate.AutoSize(roundingFactor); + change.Complete(); + } + + /// + /// Plate > Set as Default, the nest's part: '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 (). + /// + public static void SetAsNestDefault( + Nest nest, PlateManager plates, Plate plate, Func 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(); + } + + /// + /// 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. + /// + 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; + } + + /// + /// Plate > Edit's commit: 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 (), and the drawings' + /// nested quantities are counted again, the plate's quantity being one of their factors. + /// + public static void EditPlate( + Nest nest, PlateManager plates, Plate plate, PlateEditValues settings, Func 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(); + } + + /// + /// After Edit Plate wrote : an empty plate's settings become the + /// nest's plate defaults, the trailing empty plate following them while untouched. + /// + 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)); + } +} + +/// The turns of Plate > Rotate. +public enum PlateRotation +{ + /// 90° CW. + Clockwise, + + /// 90° CCW. + CounterClockwise, + + /// 180°. + HalfTurn, +} diff --git a/OpenNest.Desktop/PlateEditValues.cs b/OpenNest.Desktop/PlateEditValues.cs new file mode 100644 index 00000000..2813162c --- /dev/null +++ b/OpenNest.Desktop/PlateEditValues.cs @@ -0,0 +1,114 @@ +using System; +using OpenNest.Geometry; + +namespace OpenNest.Desktop; + +/// +/// What the Edit Plate dialog edits: quantity, size, part and edge spacing, quadrant and the +/// sheet outline. reads a plate, is when the +/// dialog's Done button is enabled and writes the plate as Done does. +/// +public sealed record PlateEditValues +{ + /// The range of the dialog's quantity and spacing boxes (the WinForms box defaults). + public const double BoxMinimum = 0; + + public const double BoxMaximum = 100; + + /// Decimals the spacing boxes show. + 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; } + + /// The plate origin's quadrant, 1 to 4. + public int Quadrant { get; init; } = 1; + + /// + /// The sheet outline the plate gets: null for a rectangular sheet. An outlined sheet's size + /// is its outline's bounds (). + /// + public SheetOutline Outline { get; init; } + + /// The plate's current settings. + 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, + }; + } + + /// + /// These settings with (null clears it, keeping the size); an + /// outline sets the size to its bounds. + /// + public PlateEditValues WithOutline(SheetOutline outline) => + outline == null + ? this with { Outline = null } + : this with { Outline = outline, Size = outline.Size }; + + /// + /// Whether Done applies: the edge spacings leave room on the sheet both ways. + /// + public bool CanApply => + LeftSpacing + RightSpacing < Size.Length && TopSpacing + BottomSpacing < Size.Width; + + /// + /// Whether Done applies with typed in the size box: it must + /// parse as a size ("width x length"), and then holds for it. + /// + public bool CanApplyWithSize(string sizeText, out Size size) => + Size.TryParse(sizeText, out size) && (this with { Size = size }).CanApply; + + /// Writes the settings to , as the dialog's Done does. + 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; + } + + /// The dialog's outline line: "Rectangular sheet" or its vertices and obstacles. + public static string OutlineText(SheetOutline outline) => + outline == null + ? "Rectangular sheet" + : $"{outline.Points.Count} vertices" + + (outline.Obstacles.Count == 0 ? "" : $", {outline.Obstacles.Count} obstacle(s)"); + + /// The step of the spacing boxes: a quarter inch, or one millimeter. + public static double SpacingIncrement(Units units) => units == Units.Inches ? 0.25 : 1; +} diff --git a/OpenNest.Desktop/PlateListRow.cs b/OpenNest.Desktop/PlateListRow.cs new file mode 100644 index 00000000..a9033c23 --- /dev/null +++ b/OpenNest.Desktop/PlateListRow.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace OpenNest.Desktop; + +/// +/// 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. +/// +public sealed record PlateListRow(string Name, string Size, string Parts, string Utilization, string Quantity) +{ + /// The row of the plate at among . + public static PlateListRow For(IList 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}" : ""); + } + + /// Every plate's row, in order. + public static IReadOnlyList For(IList plates) + { + ArgumentNullException.ThrowIfNull(plates); + return Enumerable.Range(0, plates.Count).Select(i => For(plates, i)).ToList(); + } + + /// The trailing empty plate the list shows as "New plate". + public static bool IsNewPlate(IList plates, int index) => + index == plates.Count - 1 && plates[index].Parts.Count == 0; + + /// + /// The gap a plate row dragged in the list is dropped into, 0 (before the first plate) + /// through (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 + /// ( -1) drop after the last plate. + /// + 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); + } + + /// The index a plate dragged from lands at when dropped in . + public static int DropTarget(int from, int slot) => slot > from ? slot - 1 : slot; +} diff --git a/OpenNest.Desktop/QuadrantPick.cs b/OpenNest.Desktop/QuadrantPick.cs new file mode 100644 index 00000000..13f3959e --- /dev/null +++ b/OpenNest.Desktop/QuadrantPick.cs @@ -0,0 +1,37 @@ +namespace OpenNest.Desktop; + +/// +/// 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. +/// +public static class QuadrantPick +{ + /// when it is 1 to 4, otherwise 1, as the picker accepts it. + public static int Normalize(int value) => value is >= 1 and <= 4 ? value : 1; + + /// The quadrant a click at (, ) picks. + 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); + } + + /// + /// The highlighted cell of : its left and top edges and size, + /// in the control's coordinates. + /// + 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), + }; + } +} diff --git a/OpenNest.Desktop/SheetOutlineImport.cs b/OpenNest.Desktop/SheetOutlineImport.cs new file mode 100644 index 00000000..460bffeb --- /dev/null +++ b/OpenNest.Desktop/SheetOutlineImport.cs @@ -0,0 +1,87 @@ +using System; +using System.Collections.Generic; +using System.IO; +using OpenNest.IO; + +namespace OpenNest.Desktop; + +/// +/// 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 (); import never guesses a scale. +/// +public static class SheetOutlineImport +{ + /// + /// Reads the outline. is the scale the user chose + /// for an SVG without a stated size, null otherwise. + /// + /// The file holds no closed contour with an area. + /// The file cannot be read. + 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); + } + + /// + /// Whether a failed read is the file not holding an outline (told to the user), rather than + /// a fault in the app. + /// + public static bool IsReadFailure(Exception exception) => + exception is ArgumentException or IOException or InvalidOperationException or InvalidDataException; + + /// What the user is told when fails. + public static string FailureText(Exception exception) => + $"The file does not hold a sheet outline: {exception?.Message}"; +} + +/// +/// 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. +/// +public static class SvgScale +{ + /// The choices, in the order offered; the first (CSS pixels) is the default. + 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), + }; + + /// + /// 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). + /// + 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; + } + } + + /// The prompt's question. + public static string Question(string fileName) => + $"\"{fileName}\" does not state its real-world size. What is one of its units?"; + + /// The size the file imports at with , in . + 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}"; + } +} diff --git a/OpenNest/Controls/PlateListBox.cs b/OpenNest/Controls/PlateListBox.cs index 755e6e64..a871e2a0 100644 --- a/OpenNest/Controls/PlateListBox.cs +++ b/OpenNest/Controls/PlateListBox.cs @@ -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().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 - { - plate.Size.ToString(4), - isSentinel ? "Empty" : $"{partCount} {(partCount == 1 ? "part" : "parts")}", - }; - if (partCount > 0) - lines.Add($"{plate.Utilization():P0} utilized"); + var lines = new List { 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); diff --git a/OpenNest/Controls/QuadrantSelect.cs b/OpenNest/Controls/QuadrantSelect.cs index 29e81331..1ae6451e 100644 --- a/OpenNest/Controls/QuadrantSelect.cs +++ b/OpenNest/Controls/QuadrantSelect.cs @@ -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(); } diff --git a/OpenNest/Forms/EditNestForm.PlateOrder.cs b/OpenNest/Forms/EditNestForm.PlateOrder.cs index dc50ce8f..b28b2bc1 100644 --- a/OpenNest/Forms/EditNestForm.PlateOrder.cs +++ b/OpenNest/Forms/EditNestForm.PlateOrder.cs @@ -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); } /// The index a plate dragged from lands at when dropped in . - 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) { diff --git a/OpenNest/Forms/EditNestForm.cs b/OpenNest/Forms/EditNestForm.cs index 4e98eb66..78381648 100644 --- a/OpenNest/Forms/EditNestForm.cs +++ b/OpenNest/Forms/EditNestForm.cs @@ -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() { diff --git a/OpenNest/Forms/EditPlateForm.cs b/OpenNest/Forms/EditPlateForm.cs index 4829e718..041f26f9 100644 --- a/OpenNest/Forms/EditPlateForm.cs +++ b/OpenNest/Forms/EditPlateForm.cs @@ -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; } /// Writes the dialog's values to the plate, as Done does. 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); } } diff --git a/OpenNest/Forms/MainForm.Tools.cs b/OpenNest/Forms/MainForm.Tools.cs index 7ba11393..e5ef28f7 100644 --- a/OpenNest/Forms/MainForm.Tools.cs +++ b/OpenNest/Forms/MainForm.Tools.cs @@ -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); diff --git a/OpenNest/Forms/SvgScaleForm.cs b/OpenNest/Forms/SvgScaleForm.cs index 6490266c..cbb1cef3 100644 --- a/OpenNest/Forms/SvgScaleForm.cs +++ b/OpenNest/Forms/SvgScaleForm.cs @@ -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); } } }