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 d70d4cb0..c5684588 100644 --- a/OpenNest.Avalonia/MainWindow.axaml +++ b/OpenNest.Avalonia/MainWindow.axaml @@ -36,8 +36,21 @@ + + + + + + + + + + + + + diff --git a/OpenNest.Avalonia/MainWindow.axaml.cs b/OpenNest.Avalonia/MainWindow.axaml.cs index 99ab51ad..4ed50de1 100644 --- a/OpenNest.Avalonia/MainWindow.axaml.cs +++ b/OpenNest.Avalonia/MainWindow.axaml.cs @@ -115,6 +115,7 @@ namespace OpenNest.Avalonia Gesture = new KeyGesture(Key.F6), Command = new Command(() => OnSetRotationIncrement(null, null)), }); + 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 75ec11bf..d9408971 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. @@ -225,10 +226,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; @@ -260,6 +258,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); + } + } +}