diff --git a/OpenNest.Avalonia/DrawingListItem.cs b/OpenNest.Avalonia/DrawingListItem.cs new file mode 100644 index 00000000..c9fa38f1 --- /dev/null +++ b/OpenNest.Avalonia/DrawingListItem.cs @@ -0,0 +1,78 @@ +using System.ComponentModel; +using Avalonia.Media; +using Avalonia.Media.Imaging; +using OpenNest.Avalonia.Rendering; +using OpenNest.Desktop; + +namespace OpenNest.Avalonia +{ + /// + /// One row of the Drawings tab list: the shared with its picture + /// and the WinForms row colors (a pale yellow row once nothing remains to nest, a green or + /// orange bar for a required quantity that is or is not all nested). The list updates a row + /// in place while the drawings and their order stay the same. + /// + public sealed class DrawingListItem : INotifyPropertyChanged + { + /// The picture's size, as the WinForms list draws it. + public const int ThumbnailWidth = 85; + + public const int ThumbnailHeight = 75; + + private static readonly IBrush Plain = Brushes.White; + private static readonly IBrush Highlight = new SolidColorBrush(Color.FromRgb(255, 255, 225)); + private static readonly IBrush CompleteBar = new SolidColorBrush(Color.FromRgb(76, 175, 80)); + private static readonly IBrush ShortBar = new SolidColorBrush(Color.FromRgb(255, 152, 0)); + + private DrawingListRow row; + private double scaling; + + public DrawingListItem(DrawingListRow row, double scaling) + { + this.row = row; + this.scaling = scaling; + } + + public event PropertyChangedEventHandler PropertyChanged; + + public Drawing Drawing => row.Drawing; + + public string Name => row.Name; + + public string Quantity => row.Quantity; + + public bool HasQuantity => row.Quantity != null; + + public string Size => row.Size; + + public string Area => row.Area; + + public IBrush Background => row.IsHighlighted ? Highlight : Plain; + + public IBrush Bar => row.Bar switch + { + DrawingQuantityBar.Complete => CompleteBar, + DrawingQuantityBar.Short => ShortBar, + _ => Brushes.Transparent, + }; + + // Drawn when first shown and cached per drawing until its program or color changes. + public Bitmap Thumbnail => DrawingThumbnail.For(row.Drawing, ThumbnailWidth, ThumbnailHeight, scaling); + + /// Shows , the same drawing's current row. + public void Update(DrawingListRow value, double renderScaling) + { + row = value; + scaling = renderScaling; + // Every property: a color or program change redraws the picture too. + foreach (var name in Properties) + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); + } + + private static readonly string[] Properties = + { + nameof(Drawing), nameof(Name), nameof(Quantity), nameof(HasQuantity), nameof(Size), nameof(Area), + nameof(Background), nameof(Bar), nameof(Thumbnail), + }; + } +} diff --git a/OpenNest.Avalonia/DrawingPropertiesDialog.cs b/OpenNest.Avalonia/DrawingPropertiesDialog.cs new file mode 100644 index 00000000..888f8927 --- /dev/null +++ b/OpenNest.Avalonia/DrawingPropertiesDialog.cs @@ -0,0 +1,391 @@ +using System.Threading.Tasks; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.Primitives; +using Avalonia.Input; +using Avalonia.Interactivity; +using Avalonia.Layout; +using Avalonia.Media; +using OpenNest.Avalonia.Rendering; +using OpenNest.Desktop; +using DrawingColor = System.Drawing.Color; + +namespace OpenNest.Avalonia +{ + /// + /// The Drawings tab's double-click, as the WinForms Drawing Properties dialog: the drawing's + /// picture beside its name, customer and formed-after-cutting answer, its quantity (with how + /// many are nested and remain), priority, cut first and allow common line, its color (picked, + /// or Automatic from the color scheme) and its size, area and source file. OK returns the + /// edited (the caller saves them as one undo step); Cancel or + /// Esc returns null and changes nothing. + /// + internal sealed class DrawingPropertiesDialog : Window + { + private const int PreviewSize = 240; + + private readonly DrawingProperties properties; + private readonly TextBox name = new() { Name = "DrawingName", MinWidth = 260 }; + private readonly TextBox customer = new() { Name = "Customer", MinWidth = 260 }; + private readonly CheckBox formed = new() { Name = "Formed", Content = "Formed after cutting" }; + private readonly NumericUpDown quantity = new() + { + Name = "Quantity", + Minimum = 0, + Maximum = DrawingProperties.MaxQuantity, + Increment = 1, + FormatString = "0", + ClipValueToMinMax = true, + MinWidth = 140, + }; + private readonly NumericUpDown priority = new() + { + Name = "Priority", + Minimum = DrawingProperties.MinPriority, + Maximum = DrawingProperties.MaxPriority, + Increment = 1, + FormatString = "0", + ClipValueToMinMax = true, + MinWidth = 140, + }; + private readonly CheckBox cutFirst = new() { Name = "CutFirst", Content = "Cut first" }; + private readonly CheckBox allowCommonLine = new() { Name = "AllowCommonLine", Content = "Allow common line" }; + private readonly TextBlock nested = new() { Name = "Nested", VerticalAlignment = VerticalAlignment.Center }; + private readonly Border colorSwatch = new() + { + Name = "ColorSwatch", + Width = 28, + Height = 20, + BorderBrush = Brushes.Gray, + BorderThickness = new Thickness(1), + Cursor = new Cursor(StandardCursorType.Hand), + }; + private readonly TextBlock colorMode = new() { Name = "ColorMode", VerticalAlignment = VerticalAlignment.Center }; + private readonly Button automaticColor = new() { Name = "AutomaticColor", Content = "Automatic" }; + private readonly Image preview = new() { Width = PreviewSize, Height = PreviewSize }; + + private DrawingPropertiesDialog(Drawing drawing, Nest nest) + { + properties = new DrawingProperties(drawing, nest); + Title = properties.Title; + SizeToContent = SizeToContent.WidthAndHeight; + CanResize = false; + ShowInTaskbar = false; + WindowStartupLocation = WindowStartupLocation.CenterOwner; + + name.Text = properties.Name; + customer.Text = properties.Customer; + formed.IsChecked = properties.Formed; + quantity.Value = properties.Quantity; + priority.Value = properties.Priority; + cutFirst.IsChecked = properties.CutFirst; + allowCommonLine.IsChecked = properties.AllowCommonLine; + quantity.ValueChanged += (_, _) => UpdateNested(); + + var changeColor = new Button { Name = "ChangeColor", Content = "Change Color..." }; + changeColor.Click += async (_, _) => await ChangeColorAsync(); + colorSwatch.PointerReleased += async (_, _) => await ChangeColorAsync(); + automaticColor.Click += (_, _) => + { + properties.UseAutomaticColor(); + UpdateColor(); + }; + + var drawingGroup = Fields( + ("Name", name, null), + ("Customer", customer, null), + (null, formed, "Bent or rolled; marked F on the nest report")); + var nestingGroup = Fields( + ("Quantity", Row(quantity, nested), null), + ("Priority", priority, "Higher numbers nest first"), + (null, cutFirst, "Cut before other parts on the plate"), + (null, allowCommonLine, "Copies may share a cut, one kerf apart")); + var colorGroup = new StackPanel + { + Spacing = 6, + Children = + { + Row(colorSwatch, colorMode), + Row(changeColor, automaticColor), + }, + }; + var source = new TextBlock { Name = "Source", Text = properties.SourceText }; + if (properties.SourcePath != null) + ToolTip.SetTip(source, properties.SourcePath); + var detailsGroup = Fields( + ("Size", new TextBlock { Name = "DrawingSize", Text = properties.SizeText }, null), + ("Area", new TextBlock { Name = "Area", Text = properties.AreaText }, null), + ("Source", source, null)); + + var ok = new Button { Name = "Ok", Content = "OK", IsDefault = true, MinWidth = 90 }; + ok.Click += (_, _) => Close(Values()); + var cancel = new Button { Content = "Cancel", IsCancel = true, MinWidth = 90 }; + cancel.Click += (_, _) => Close(null); + + var fields = new StackPanel + { + Spacing = 14, + Width = 420, + Children = + { + Group("Drawing", drawingGroup), + Group("Nesting", nestingGroup), + Group("Color", colorGroup), + Group("Details", detailsGroup), + }, + }; + var previewBox = new Border + { + Background = Brushes.White, + BorderBrush = Brush.Parse("#C8CDD2"), + BorderThickness = new Thickness(1), + Padding = new Thickness(12), + VerticalAlignment = VerticalAlignment.Top, + Child = preview, + }; + Content = new StackPanel + { + Margin = new Thickness(18), + Spacing = 18, + Children = + { + new StackPanel + { + Orientation = Orientation.Horizontal, + Spacing = 18, + Children = { previewBox, fields }, + }, + new StackPanel + { + Orientation = Orientation.Horizontal, + HorizontalAlignment = HorizontalAlignment.Right, + Spacing = 8, + Children = { ok, cancel }, + }, + }, + }; + + AddHandler(KeyDownEvent, (_, e) => + { + if (e.Key != Key.Escape) + return; + e.Handled = true; + Close(null); + }, RoutingStrategies.Tunnel); + Opened += (_, _) => + { + UpdateColor(); + name.SelectAll(); + name.Focus(); + }; + UpdateNested(); + } + + /// The edited values, or null when the user cancelled. + public static Task ShowAsync(Window owner, Drawing drawing, Nest nest) => + new DrawingPropertiesDialog(drawing, nest).ShowDialog(owner); + + private DrawingProperties Values() + { + properties.Name = name.Text ?? ""; + properties.Customer = customer.Text ?? ""; + properties.Quantity = (int)(quantity.Value ?? 0); + properties.Priority = (int)(priority.Value ?? 0); + properties.CutFirst = cutFirst.IsChecked == true; + properties.AllowCommonLine = allowCommonLine.IsChecked == true; + properties.Formed = formed.IsChecked == true; + return properties; + } + + private void UpdateNested() + { + properties.Quantity = (int)(quantity.Value ?? 0); + nested.Text = properties.NestedText; + } + + private void UpdateColor() + { + var color = properties.Color; + colorSwatch.Background = new SolidColorBrush(Color.FromArgb(color.A, color.R, color.G, color.B)); + colorMode.Text = properties.ColorModeText; + automaticColor.IsEnabled = properties.CanUseAutomaticColor; + preview.Source = DrawingThumbnail.Preview(properties.Drawing, color, PreviewSize, PreviewSize, + RenderScaling); + } + + private async Task ChangeColorAsync() + { + var picked = await ColorChoiceDialog.ShowAsync(this, properties.Color); + if (picked is not { } color) + return; + // A picked color cancels a pending Automatic. + properties.PickColor(color); + UpdateColor(); + } + + private static StackPanel Row(params Control[] controls) + { + var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8 }; + foreach (var control in controls) + row.Children.Add(control); + return row; + } + + // Labeled fields, each with an optional gray hint below it. + private static Grid Fields(params (string Label, Control Field, string Hint)[] rows) + { + var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), ColumnSpacing = 10, RowSpacing = 6 }; + var row = 0; + foreach (var (label, field, hint) in rows) + { + grid.RowDefinitions.Add(new RowDefinition(GridLength.Auto)); + if (label != null) + { + 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); + row++; + if (hint == null) + continue; + grid.RowDefinitions.Add(new RowDefinition(GridLength.Auto)); + var note = new TextBlock { Text = hint, Foreground = Brushes.Gray, FontSize = 12, Margin = new Thickness(26, -4, 0, 0) }; + Grid.SetRow(note, row); + Grid.SetColumn(note, 1); + grid.Children.Add(note); + row++; + } + return grid; + } + + // 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 = FontWeight.SemiBold }, + new Border + { + BorderBrush = Brush.Parse("#C8CDD2"), + BorderThickness = new Thickness(1), + Padding = new Thickness(10), + Child = content, + }, + }, + }; + } + + /// + /// Change Color's chooser: the basic colors of the Windows color dialog the WinForms app + /// shows, and a "#RRGGBB" box for any other. OK returns the color; Cancel or Esc returns null. + /// + internal sealed class ColorChoiceDialog : Window + { + private static readonly string[] BasicColors = + { + "#FF8080", "#FFFF80", "#80FF80", "#00FF80", "#80FFFF", "#0080FF", "#FF80C0", "#FF80FF", + "#FF0000", "#FFFF00", "#80FF00", "#00FF40", "#00FFFF", "#0080C0", "#8080C0", "#FF00FF", + "#804040", "#FF8040", "#00FF00", "#008080", "#004080", "#8080FF", "#800040", "#FF0080", + "#800000", "#FF8000", "#008000", "#008040", "#0000FF", "#0000A0", "#800080", "#8000FF", + "#400000", "#804000", "#004000", "#004040", "#000080", "#000040", "#400040", "#400080", + "#000000", "#808000", "#808040", "#808080", "#408080", "#C0C0C0", "#404040", "#FFFFFF", + }; + + private readonly TextBox hex = new() { Name = "Hex", Width = 110 }; + private readonly Border sample = new() { Width = 40, Height = 24, BorderBrush = Brushes.Gray, BorderThickness = new Thickness(1) }; + private readonly Button ok = new() { Content = "OK", IsDefault = true, MinWidth = 90 }; + + private ColorChoiceDialog(DrawingColor current) + { + Title = "Color"; + SizeToContent = SizeToContent.WidthAndHeight; + CanResize = false; + ShowInTaskbar = false; + WindowStartupLocation = WindowStartupLocation.CenterOwner; + + var swatches = new UniformGrid { Columns = 8 }; + foreach (var text in BasicColors) + { + var color = Color.Parse(text); + var swatch = new Button + { + Width = 26, + Height = 22, + Margin = new Thickness(2), + Padding = new Thickness(0), + Background = new SolidColorBrush(color), + BorderBrush = Brushes.Gray, + BorderThickness = new Thickness(1), + }; + ToolTip.SetTip(swatch, text); + swatch.Click += (_, _) => hex.Text = text; + swatch.DoubleTapped += (_, _) => Close(Parse(text)); + swatches.Children.Add(swatch); + } + + hex.Text = $"#{current.R:X2}{current.G:X2}{current.B:X2}"; + hex.TextChanged += (_, _) => UpdateSample(); + ok.Click += (_, _) => Close(Parse(hex.Text)); + var cancel = new Button { Content = "Cancel", IsCancel = true, MinWidth = 90 }; + cancel.Click += (_, _) => Close(null); + + Content = new StackPanel + { + Margin = new Thickness(18), + Spacing = 14, + Children = + { + new TextBlock { Text = "Basic colors" }, + swatches, + new StackPanel + { + Orientation = Orientation.Horizontal, + Spacing = 8, + Children = { new TextBlock { Text = "Color", VerticalAlignment = VerticalAlignment.Center }, hex, sample }, + }, + new StackPanel + { + Orientation = Orientation.Horizontal, + HorizontalAlignment = HorizontalAlignment.Right, + Spacing = 8, + Children = { ok, cancel }, + }, + }, + }; + AddHandler(KeyDownEvent, (_, e) => + { + if (e.Key != Key.Escape) + return; + e.Handled = true; + Close(null); + }, RoutingStrategies.Tunnel); + UpdateSample(); + } + + /// The chosen color, or null when the user cancelled. + public static Task ShowAsync(Window owner, DrawingColor current) => + new ColorChoiceDialog(current).ShowDialog(owner); + + // "#RRGGBB" (the # optional) as an opaque color; null when it is not one. + internal static DrawingColor? Parse(string text) + { + var value = text?.Trim().TrimStart('#'); + if (value is not { Length: 6 } + || !int.TryParse(value, System.Globalization.NumberStyles.HexNumber, + System.Globalization.CultureInfo.InvariantCulture, out var rgb)) + return null; + return DrawingColor.FromArgb(255, (rgb >> 16) & 0xFF, (rgb >> 8) & 0xFF, rgb & 0xFF); + } + + private void UpdateSample() + { + var color = Parse(hex.Text); + ok.IsEnabled = color != null; + sample.Background = color is { } c ? new SolidColorBrush(Color.FromRgb(c.R, c.G, c.B)) : Brushes.Transparent; + } + } +} diff --git a/OpenNest.Avalonia/NestView.Drawings.cs b/OpenNest.Avalonia/NestView.Drawings.cs new file mode 100644 index 00000000..7757ae03 --- /dev/null +++ b/OpenNest.Avalonia/NestView.Drawings.cs @@ -0,0 +1,288 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Threading.Tasks; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.Primitives; +using Avalonia.Input; +using Avalonia.Interactivity; +using Avalonia.Threading; +using Avalonia.VisualTree; +using OpenNest.Collections; +using OpenNest.Data; +using OpenNest.Desktop; + +namespace OpenNest.Avalonia +{ + /// + /// The Drawings tab, as the WinForms nest window's drawing list: each drawing's picture, + /// name, "[on this plate] nested of required nested", size and area, refreshed shortly after + /// parts come and go on the shown plate or the nest is edited. Its toolbar sorts the list + /// (the choice shared with the WinForms app) and hides the fully nested drawings; its menu + /// deletes a drawing or removes the unused ones, and a double-click opens Drawing Properties. + /// Each edit is one undo step of the nest; none runs while Auto Nest works on it. + /// + public partial class NestView + { + // As the WinForms list's timer: a fill's many per-part events refresh the list once. + private static readonly TimeSpan DrawingListDelay = TimeSpan.FromMilliseconds(50); + + private readonly ObservableCollection drawingItems = new(); + private DispatcherTimer drawingListTimer; + private readonly MenuFlyout sortDrawingsMenu = new() { Placement = PlacementMode.BottomEdgeAlignedLeft }; + private DrawingSortOrder drawingSortOrder; + private Plate watchedPlate; + + private void InitializeDrawingList() + { + DrawingList.ItemsSource = drawingItems; + drawingListTimer = new DispatcherTimer { Interval = DrawingListDelay }; + drawingListTimer.Tick += (_, _) => + { + drawingListTimer.Stop(); + RefreshDrawingList(); + }; + // Recorded edits (Drawing Properties included) can change any row. + Tab.Undo.Changed += (_, _) => ScheduleDrawingListRefresh(); + + drawingSortOrder = DrawingSort.Parse(UserSettingText.ReadString( + UserSettingsFile.Read(UserSettingsFile.DefaultPath), DrawingSort.SettingName, null)); + foreach (var (order, text) in DrawingSort.Choices) + { + var item = new MenuItem { Header = text, Tag = order, ToggleType = MenuItemToggleType.Radio }; + item.Click += (_, _) => SetDrawingSortOrder(order); + sortDrawingsMenu.Items.Add(item); + } + SortDrawingsButton.Flyout = sortDrawingsMenu; + UpdateSortDrawingsChoice(); + + HideNestedButton.IsCheckedChanged += (_, _) => RefreshDrawingList(); + DrawingEmptyText.Text = DrawingListRow.AllHiddenText; + DrawingEmptyText.PointerReleased += (_, e) => + { + if (e.InitialPressMouseButton == MouseButton.Left) + HideNestedButton.IsChecked = false; + }; + + DrawingList.DoubleTapped += async (_, e) => + { + if (DrawingAt(e.Source) is { } drawing) + await EditDrawingPropertiesAsync(drawing); + }; + DeleteDrawingMenuItem.Click += async (_, _) => await DeleteSelectedDrawingAsync(); + RemoveUnusedDrawingsMenuItem.Click += async (_, _) => await RemoveUnusedDrawingsAsync(); + DrawingMenu.Opening += (_, _) => + { + // As WinForms: Delete needs a selected drawing; Remove Unused acts on the nest. + DeleteDrawingMenuItem.IsVisible = SelectedDrawing != null; + DrawingMenuSeparator.IsVisible = SelectedDrawing != null; + DeleteDrawingMenuItem.IsEnabled = CanEditDrawings; + RemoveUnusedDrawingsMenuItem.IsEnabled = CanEditDrawings; + }; + } + + /// The drawing selected in the list, or null. + public Drawing SelectedDrawing => (DrawingList.SelectedItem as DrawingListItem)?.Drawing; + + /// Whether the drawing commands can run: not while Auto Nest works on the nest. + public bool CanEditDrawings => !Canvas.EditsLocked; + + /// Whether Hide Fully Nested Drawings is on. + public bool HidesFullyNestedDrawings + { + get => HideNestedButton.IsChecked == true; + set => HideNestedButton.IsChecked = value; + } + + private static Drawing DrawingAt(object source) => + (source as Visual)?.FindAncestorOfType(includeSelf: true)?.DataContext is DrawingListItem item + ? item.Drawing + : null; + + /// Refreshes the list shortly, once however many parts change before then. + private void ScheduleDrawingListRefresh() + { + if (!Dispatcher.UIThread.CheckAccess()) + { + Dispatcher.UIThread.Post(ScheduleDrawingListRefresh); + return; + } + drawingListTimer.Stop(); + drawingListTimer.Start(); + } + + /// + /// Shows the nest's drawings in the chosen order, less the fully nested ones when hidden. + /// Rows update in place while the drawings and their order are unchanged; otherwise the + /// list is rebuilt keeping the selected drawing (by reference, or by name for the new + /// objects an Undo brings) and the scroll position. + /// + private void RefreshDrawingList() + { + drawingListTimer?.Stop(); + var nest = Tab.Document.Nest; + var units = nest.Units; + var plate = Canvas.Plate; + var scaling = TopLevel.GetTopLevel(this)?.RenderScaling ?? 1; + var arranged = DrawingSort.Arrange(nest.Drawings.Where(d => !d.IsCutOff), drawingSortOrder, + HidesFullyNestedDrawings); + + var unchanged = arranged.Count == drawingItems.Count; + for (var i = 0; unchanged && i < arranged.Count; i++) + unchanged = ReferenceEquals(arranged[i], drawingItems[i].Drawing); + + if (unchanged) + { + for (var i = 0; i < arranged.Count; i++) + drawingItems[i].Update(DrawingListRow.For(arranged[i], plate, units), scaling); + } + else + { + var selected = SelectedDrawing; + var scroller = DrawingList.FindDescendantOfType(); + var offset = scroller?.Offset ?? default; + drawingItems.Clear(); + foreach (var drawing in arranged) + drawingItems.Add(new DrawingListItem(DrawingListRow.For(drawing, plate, units), scaling)); + DrawingList.SelectedItem = selected == null + ? null + : drawingItems.FirstOrDefault(item => ReferenceEquals(item.Drawing, selected)) + ?? drawingItems.FirstOrDefault(item => item.Drawing.Name == selected.Name); + if (scroller != null) + Dispatcher.UIThread.Post(() => scroller.Offset = offset, DispatcherPriority.Background); + } + + DrawingEmptyText.IsVisible = drawingItems.Count == 0 + && DrawingListRow.EmptyText(HidesFullyNestedDrawings, nest.Drawings.Count) != null; + } + + // The shown plate's parts change the "[n]" counts and the nested quantities. + private void WatchShownPlate(Plate plate) + { + if (ReferenceEquals(watchedPlate, plate)) + return; + if (watchedPlate != null) + { + watchedPlate.PartAdded -= OnShownPlatePartAdded; + watchedPlate.PartRemoved -= OnShownPlatePartRemoved; + watchedPlate.PartsReordered -= OnShownPlatePartsReordered; + } + watchedPlate = plate; + if (plate != null) + { + plate.PartAdded += OnShownPlatePartAdded; + plate.PartRemoved += OnShownPlatePartRemoved; + plate.PartsReordered += OnShownPlatePartsReordered; + } + // The counts on the newly shown plate. + if (drawingListTimer != null) + ScheduleDrawingListRefresh(); + } + + private void OnShownPlatePartAdded(object sender, ItemAddedEventArgs e) => ScheduleDrawingListRefresh(); + + private void OnShownPlatePartRemoved(object sender, ItemRemovedEventArgs e) => ScheduleDrawingListRefresh(); + + private void OnShownPlatePartsReordered(object sender, EventArgs e) => ScheduleDrawingListRefresh(); + + private void SetDrawingSortOrder(DrawingSortOrder order) + { + if (order != drawingSortOrder) + { + drawingSortOrder = order; + // As WinForms' DrawingSortOrder setting, which the WinForms app reads too. + UserSettingsFile.Update(UserSettingsFile.DefaultPath, + values => values[DrawingSort.SettingName] = order.ToString()); + RefreshDrawingList(); + } + UpdateSortDrawingsChoice(); + } + + private void UpdateSortDrawingsChoice() + { + foreach (var item in sortDrawingsMenu.Items.OfType()) + item.IsChecked = item.Tag is DrawingSortOrder order && order == drawingSortOrder; + var text = DrawingSort.Choices.First(c => c.Order == drawingSortOrder).Text; + ToolTip.SetTip(SortDrawingsButton, $"Sort drawings: {text}"); + } + + /// + /// Runs a drawing command, then rebuilds both lists and redraws the plate (a drawing's + /// color may have changed), keeping its zoom, and its selection while its parts are + /// unchanged. A command that removes drawings first ends the plate tool + /// (), which may be placing one of them. + /// + private void RunDrawingCommand(Action command, bool endTool) + { + if (endTool) + { + Canvas.Tools.EndTool(); + pickup.PutDown(); + pressedDrawing = null; + } + runningPlateCommand = true; + try + { + command(); + } + finally + { + runningPlateCommand = false; + } + ShowPlates(System.Math.Max(0, PlateList.SelectedIndex), keep: true); + } + + /// The drawing menu's Delete: confirms, then deletes the drawing and its parts. + public async Task DeleteSelectedDrawingAsync() + { + var drawing = SelectedDrawing; + if (drawing == null || !CanEditDrawings || TopLevel.GetTopLevel(this) is not Window owner) + return; + if (!await ConfirmDialog.AskAsync(owner, DrawingCommands.DeleteTitle, + DrawingCommands.DeletePrompt(drawing), "Delete")) + return; + // Auto Nest may have started, or an Undo swapped the nest, while the question was open. + if (!CanEditDrawings || !Tab.Document.Nest.Drawings.Contains(drawing)) + return; + RunDrawingCommand(() => DrawingCommands.DeleteDrawing(Tab.Document.Nest, drawing, + label => Tab.Undo.BeginChange(label)), endTool: true); + } + + /// The drawing menu's Remove Unused Drawings: confirms, then removes them. + public async Task RemoveUnusedDrawingsAsync() + { + if (!CanEditDrawings || TopLevel.GetTopLevel(this) is not Window owner) + return; + if (!await ConfirmDialog.AskAsync(owner, DrawingCommands.CleanUnusedTitle, + DrawingCommands.CleanUnusedPrompt, "Yes")) + return; + if (!CanEditDrawings) + return; + if (DrawingCommands.HasUnusedDrawings(Tab.Document.Nest)) + RunDrawingCommand(() => DrawingCommands.CleanUnusedDrawings(Tab.Document.Nest, + label => Tab.Undo.BeginChange(label)), endTool: true); + } + + /// + /// A double-click on a drawing: the Drawing Properties dialog; OK saves the values as one + /// undo step and redraws the drawing's parts in their color. + /// + public async Task EditDrawingPropertiesAsync(Drawing drawing) + { + // As WinForms: the double-click puts a picked-up drawing down. + pickup.PutDown(); + pressedDrawing = null; + if (drawing == null || !CanEditDrawings || TopLevel.GetTopLevel(this) is not Window owner) + return; + var nest = Tab.Document.Nest; + var properties = await DrawingPropertiesDialog.ShowAsync(owner, drawing, nest); + if (properties == null || !CanEditDrawings || !ReferenceEquals(nest, Tab.Document.Nest) + || !nest.Drawings.Contains(drawing)) + return; + RunDrawingCommand(() => DrawingCommands.ApplyProperties(properties, + label => Tab.Undo.BeginChange(label)), endTool: false); + } + } +} diff --git a/OpenNest.Avalonia/NestView.axaml b/OpenNest.Avalonia/NestView.axaml index 61304dd2..5eb50fc0 100644 --- a/OpenNest.Avalonia/NestView.axaml +++ b/OpenNest.Avalonia/NestView.axaml @@ -40,16 +40,63 @@ - - - - - - - + + + + +