From 8d1204e91735f4a7faa380ff8bfbaa8c27fc8ced Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Mon, 30 Nov 2026 18:42:20 -0500 Subject: [PATCH 1/2] feat(desktop): share the Drawings tab rows, drawing commands and properties Moves the Drawings tab's row content (quantity, size, area, highlight and quantity bar, the hidden-list note), Delete Drawing, Remove Unused Drawings and the Drawing Properties dialog's values and color rules into OpenNest.Desktop so the Avalonia app can share them. The WinForms list, nest window and Edit Drawing form delegate to them unchanged. Co-Authored-By: Claude Opus 5.5 --- .../Drawings/DrawingCommandsTests.cs | 135 ++++++++++++++ .../Drawings/DrawingListRowTests.cs | 81 +++++++++ .../Drawings/DrawingPropertiesTests.cs | 134 ++++++++++++++ OpenNest.Desktop/DrawingCommands.cs | 100 ++++++++++ OpenNest.Desktop/DrawingListRow.cs | 83 +++++++++ OpenNest.Desktop/DrawingProperties.cs | 171 ++++++++++++++++++ OpenNest/Controls/DrawingListBox.cs | 47 ++--- OpenNest/Forms/EditDrawingForm.cs | 123 ++++--------- OpenNest/Forms/EditNestForm.cs | 33 +--- 9 files changed, 758 insertions(+), 149 deletions(-) create mode 100644 OpenNest.Desktop.Tests/Drawings/DrawingCommandsTests.cs create mode 100644 OpenNest.Desktop.Tests/Drawings/DrawingListRowTests.cs create mode 100644 OpenNest.Desktop.Tests/Drawings/DrawingPropertiesTests.cs create mode 100644 OpenNest.Desktop/DrawingCommands.cs create mode 100644 OpenNest.Desktop/DrawingListRow.cs create mode 100644 OpenNest.Desktop/DrawingProperties.cs diff --git a/OpenNest.Desktop.Tests/Drawings/DrawingCommandsTests.cs b/OpenNest.Desktop.Tests/Drawings/DrawingCommandsTests.cs new file mode 100644 index 00000000..fa711d5d --- /dev/null +++ b/OpenNest.Desktop.Tests/Drawings/DrawingCommandsTests.cs @@ -0,0 +1,135 @@ +using System.Drawing; +using OpenNest.Undo; + +namespace OpenNest.Desktop.Tests.Drawings; + +public class DrawingCommandsTests +{ + /// + /// A nest window's state: "square" (two required) with one part on each of two plates, + /// "unused" with none, the trailing empty plate and a history started on it. + /// + private sealed class Env + { + public Env() + { + var nest = TestNests.OneSquare(); + Square = nest.Drawings.First(); + Square.Quantity.Required = 2; + Unused = new Drawing("unused", (CNC.Program)Square.Program.Clone()) { Color = Color.Coral }; + nest.Drawings.Add(Unused); + nest.Plates[0].Quantity = 1; + var second = new Plate(new Geometry.Size(48, 96)) { Quantity = 1 }; + second.Parts.Add(new Part(Square)); + nest.Plates.Add(second); + nest.UpdateDrawingQuantities(); + Document = new Document { Nest = nest }; + Plates = new PlateManager(nest); + Plates.EnsureSentinel(); + Undo = new NestUndoRecorder(Document); + Undo.Reset(); + } + + public Drawing Square { get; } + public Drawing Unused { get; } + 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 int SquareParts => Nest.Plates.Sum(p => p.Parts.Count(part => part.BaseDrawing.Name == "square")); + } + + [Fact] + public void DeleteDrawing_RemovesItsPartsAndTheDrawing_AsOneStep() + { + var env = new Env(); + Assert.Equal(2, env.SquareParts); + + DrawingCommands.DeleteDrawing(env.Nest, env.Square, env.BeginChange); + + Assert.Equal(0, env.SquareParts); + Assert.DoesNotContain(env.Square, env.Nest.Drawings); + Assert.Single(env.Nest.Drawings); + Assert.Equal(1, env.Steps); + Assert.Equal("Undo Delete Drawing", env.Undo.UndoText); + + env.Undo.Undo(); + Assert.Equal(2, env.SquareParts); + Assert.Equal(2, env.Nest.Drawings.Count); + Assert.Equal(2, env.Nest.Drawings.Single(d => d.Name == "square").Quantity.Nested); + } + + [Fact] + public void DeletePrompt_NamesTheDrawing() => + Assert.Equal("Delete drawing 'square' and all its parts from every plate?", + DrawingCommands.DeletePrompt(new Drawing("square"))); + + [Fact] + public void CleanUnusedDrawings_RemovesOnlyDrawingsWithNoParts_AsOneStep() + { + var env = new Env(); + Assert.True(DrawingCommands.HasUnusedDrawings(env.Nest)); + + Assert.True(DrawingCommands.CleanUnusedDrawings(env.Nest, env.BeginChange)); + + Assert.Equal(new[] { "square" }, env.Nest.Drawings.Select(d => d.Name)); + Assert.Equal(1, env.Steps); + Assert.Equal("Undo Clean Unused Drawings", env.Undo.UndoText); + + env.Undo.Undo(); + Assert.Equal(2, env.Nest.Drawings.Count); + } + + [Fact] + public void CleanUnusedDrawings_WithNoneUnused_RecordsNothing() + { + var env = new Env(); + DrawingCommands.CleanUnusedDrawings(env.Nest, env.BeginChange); + + Assert.False(DrawingCommands.CleanUnusedDrawings(env.Nest, env.BeginChange)); + + Assert.False(DrawingCommands.HasUnusedDrawings(env.Nest)); + Assert.Equal(1, env.Steps); + } + + [Fact] + public void ApplyProperties_SavesTheValues_AsOneStep() + { + var env = new Env(); + var properties = new DrawingProperties(env.Square, env.Nest) + { + Name = "bracket", + Customer = "Acme", + Quantity = 7, + Priority = -3, + CutFirst = true, + AllowCommonLine = true, + Formed = true, + }; + + DrawingCommands.ApplyProperties(properties, env.BeginChange); + + Assert.Equal("bracket", env.Square.Name); + Assert.Equal("Acme", env.Square.Customer); + Assert.Equal(7, env.Square.Quantity.Required); + Assert.Equal(2, env.Square.Quantity.Nested); + Assert.Equal(-3, env.Square.Priority); + Assert.True(env.Square.CutFirst); + Assert.True(env.Square.AllowCommonLine); + Assert.True(env.Square.IsFormed); + Assert.False(env.Square.HasCustomColor); + Assert.Equal(1, env.Steps); + Assert.Equal("Undo Drawing Properties", env.Undo.UndoText); + + env.Undo.Undo(); + var restored = env.Nest.Drawings.Single(d => d.Quantity.Nested == 2); + Assert.Equal("square", restored.Name); + Assert.Equal(2, restored.Quantity.Required); + Assert.False(restored.CutFirst); + } +} diff --git a/OpenNest.Desktop.Tests/Drawings/DrawingListRowTests.cs b/OpenNest.Desktop.Tests/Drawings/DrawingListRowTests.cs new file mode 100644 index 00000000..a671123a --- /dev/null +++ b/OpenNest.Desktop.Tests/Drawings/DrawingListRowTests.cs @@ -0,0 +1,81 @@ +namespace OpenNest.Desktop.Tests.Drawings; + +public class DrawingListRowTests +{ + private static (Nest Nest, Drawing Drawing) Nested(int required) + { + var nest = TestNests.OneSquare(); + var drawing = nest.Drawings.First(); + drawing.Quantity.Required = required; + nest.Plates[0].Quantity = 1; + nest.UpdateDrawingQuantities(); + return (nest, drawing); + } + + [Fact] + public void ShowsTheNameQuantitySizeAndArea() + { + var (_, drawing) = Nested(3); + + var row = DrawingListRow.For(drawing, plate: null, Units.Inches); + + Assert.Same(drawing, row.Drawing); + Assert.Equal("square", row.Name); + Assert.Equal("1 of 3 nested", row.Quantity); + Assert.Equal("10 x 10", row.Size); + Assert.Equal("100 sq/in", row.Area); + Assert.False(row.IsHighlighted); + Assert.Equal(DrawingQuantityBar.Short, row.Bar); + } + + [Fact] + public void PrefixesTheCountOnTheShownPlate() + { + var (nest, drawing) = Nested(3); + + Assert.Equal("[1] 1 of 3 nested", DrawingListRow.For(drawing, nest.Plates[0], Units.Inches).Quantity); + Assert.Equal("1 of 3 nested", DrawingListRow.For(drawing, new Plate(), Units.Inches).Quantity); + } + + [Fact] + public void AllNested_IsHighlightedWithACompleteBar() + { + var (_, drawing) = Nested(1); + + var row = DrawingListRow.For(drawing, null, Units.Millimeters); + + Assert.True(row.IsHighlighted); + Assert.Equal(DrawingQuantityBar.Complete, row.Bar); + Assert.Equal("100 sq/mm", row.Area); + } + + [Fact] + public void NoRequiredQuantity_HasNoBar_ButNestedPartsHighlight() + { + var (_, drawing) = Nested(0); + + var row = DrawingListRow.For(drawing, null, Units.Inches); + + Assert.Equal(DrawingQuantityBar.None, row.Bar); + Assert.True(row.IsHighlighted); + } + + [Fact] + public void HiddenQuantity_LeavesOutTheQuantityHighlightAndBar() + { + var (_, drawing) = Nested(1); + + var row = DrawingListRow.For(drawing, null, Units.Inches, hideQuantity: true); + + Assert.Null(row.Quantity); + Assert.False(row.IsHighlighted); + Assert.Equal(DrawingQuantityBar.None, row.Bar); + } + + [Theory] + [InlineData(true, 2, DrawingListRow.AllHiddenText)] + [InlineData(true, 0, null)] + [InlineData(false, 2, null)] + public void EmptyText_ExplainsOnlyAListTheFilterEmptied(bool hide, int drawings, string expected) => + Assert.Equal(expected, DrawingListRow.EmptyText(hide, drawings)); +} diff --git a/OpenNest.Desktop.Tests/Drawings/DrawingPropertiesTests.cs b/OpenNest.Desktop.Tests/Drawings/DrawingPropertiesTests.cs new file mode 100644 index 00000000..cf8723db --- /dev/null +++ b/OpenNest.Desktop.Tests/Drawings/DrawingPropertiesTests.cs @@ -0,0 +1,134 @@ +using System.Drawing; + +namespace OpenNest.Desktop.Tests.Drawings; + +[Collection(ColorSchemeState.Collection)] +public class DrawingPropertiesTests +{ + private static Drawing Square(string name = "square") + { + var drawing = TestNests.OneSquare().Drawings.First(); + drawing.Name = name; + return drawing; + } + + [Fact] + public void ReadsTheDrawingsValues() + { + var drawing = Square("bracket"); + drawing.Customer = "Acme"; + drawing.Quantity.Required = 5; + drawing.Priority = 2; + drawing.CutFirst = true; + drawing.Source = new SourceInfo { Path = "/parts/bracket.dxf" }; + + var properties = new DrawingProperties(drawing); + + Assert.Equal("bracket", properties.Name); + Assert.Equal("Acme", properties.Customer); + Assert.Equal(5, properties.Quantity); + Assert.Equal(2, properties.Priority); + Assert.True(properties.CutFirst); + Assert.False(properties.AllowCommonLine); + Assert.False(properties.Formed); + Assert.Equal("Drawing Properties - bracket", properties.Title); + Assert.Equal("10 x 10", properties.SizeText); + Assert.Equal("100", properties.AreaText); + Assert.Equal("bracket.dxf", properties.SourceText); + Assert.Equal("/parts/bracket.dxf", properties.SourcePath); + } + + [Fact] + public void WithoutASource_ShowsADash() + { + var properties = new DrawingProperties(Square()); + + Assert.Null(properties.SourcePath); + Assert.Equal("-", properties.SourceText); + } + + [Fact] + public void NestedText_CountsRemainingAgainstTheEditedQuantity() + { + var nest = TestNests.OneSquare(); + nest.Plates[0].Quantity = 1; + nest.UpdateDrawingQuantities(); + var properties = new DrawingProperties(nest.Drawings.First(), nest); + Assert.Equal("1 nested, 0 remaining", properties.NestedText); + + properties.Quantity = 4; + + Assert.Equal("1 nested, 3 remaining", properties.NestedText); + } + + [Fact] + public void OnlyAPickedColorBecomesCustom() + { + var drawing = Square(); + drawing.Color = Color.Coral; + var unchanged = new DrawingProperties(drawing); + Assert.Equal(DrawingProperties.AutomaticColorText, unchanged.ColorModeText); + Assert.False(unchanged.CanUseAutomaticColor); + unchanged.ApplyTo(drawing); + Assert.False(drawing.HasCustomColor); + + var picked = new DrawingProperties(drawing); + picked.PickColor(Color.Red); + Assert.Equal(DrawingProperties.CustomColorText, picked.ColorModeText); + Assert.True(picked.CanUseAutomaticColor); + picked.ApplyTo(drawing); + + Assert.True(drawing.HasCustomColor); + Assert.Equal(Color.Red.ToArgb(), drawing.Color.ToArgb()); + } + + [Fact] + public void AutomaticColor_ClearsTheCustomColor_WithTheDrawingsPaletteSlot() + { + var state = new ColorSchemeState(); + try + { + ColorSchemeRegistry.Apply(ColorSchemeRegistry.Get("Classic")); + var nest = new Nest("Automatic"); + nest.Drawings.Add(new Drawing("First")); + nest.Drawings.Add(new Drawing("Cutoff") { IsCutOff = true }); + var drawing = new Drawing("Bracket") { Color = Color.Red, HasCustomColor = true }; + nest.Drawings.Add(drawing); + + var properties = new DrawingProperties(drawing, nest); + Assert.Equal(DrawingProperties.CustomColorText, properties.ColorModeText); + + properties.UseAutomaticColor(); + + Assert.Equal(DrawingProperties.AutomaticColorText, properties.ColorModeText); + Assert.False(properties.CanUseAutomaticColor); + Assert.True(drawing.HasCustomColor); + + properties.ApplyTo(drawing); + + Assert.False(drawing.HasCustomColor); + Assert.Equal(Drawing.GetPartColor(1).ToArgb(), drawing.Color.ToArgb()); + Assert.Equal(DrawingProperties.AutomaticColorText, new DrawingProperties(drawing, nest).ColorModeText); + } + finally + { + state.Restore(); + } + } + + [Fact] + public void APickedColorCancelsAPendingAutomatic() + { + var drawing = Square(); + drawing.Color = Color.Red; + drawing.HasCustomColor = true; + var properties = new DrawingProperties(drawing); + properties.UseAutomaticColor(); + + properties.PickColor(Color.Blue); + properties.ApplyTo(drawing); + + Assert.True(drawing.HasCustomColor); + Assert.Equal(Color.Blue.ToArgb(), drawing.Color.ToArgb()); + } +} diff --git a/OpenNest.Desktop/DrawingCommands.cs b/OpenNest.Desktop/DrawingCommands.cs new file mode 100644 index 00000000..07d938e5 --- /dev/null +++ b/OpenNest.Desktop/DrawingCommands.cs @@ -0,0 +1,100 @@ +using System; +using System.Linq; +using OpenNest.Undo; + +namespace OpenNest.Desktop; + +/// +/// The Drawings tab's nest edits, toolkit-neutral: Delete on a drawing's menu, Remove Unused +/// Drawings and the Drawing Properties dialog's OK. Each one is one undo step under the WinForms +/// label, opened with (the window's BeginChange), with the +/// WinForms confirmation texts for the front ends to ask first. +/// +public static class DrawingCommands +{ + public const string DeleteLabel = "Delete Drawing"; + + /// The title of Delete's confirmation. + public const string DeleteTitle = "Delete Drawing"; + + public const string CleanUnusedLabel = "Clean Unused Drawings"; + + /// The title of Remove Unused Drawings' confirmation. + public const string CleanUnusedTitle = "Clean Drawings"; + + /// Remove Unused Drawings' confirmation. + public const string CleanUnusedPrompt = "Remove unused drawings?"; + + public const string PropertiesLabel = "Drawing Properties"; + + /// Delete's confirmation for . + public static string DeletePrompt(Drawing drawing) + { + ArgumentNullException.ThrowIfNull(drawing); + return $"Delete drawing '{drawing.Name}' and all its parts from every plate?"; + } + + /// Whether the nest has a drawing with no part on any plate. + public static bool HasUnusedDrawings(Nest nest) + { + ArgumentNullException.ThrowIfNull(nest); + return nest.Drawings.Any(d => d.Quantity.Nested == 0); + } + + /// + /// Removes the drawings with no part on any plate, as one "Clean Unused Drawings" step. + /// + /// Whether a drawing was removed; when none would be, nothing is recorded. + public static bool CleanUnusedDrawings(Nest nest, Func beginChange) + { + ArgumentNullException.ThrowIfNull(nest); + ArgumentNullException.ThrowIfNull(beginChange); + if (!HasUnusedDrawings(nest)) + return false; + + using var change = beginChange(CleanUnusedLabel); + change.MarkChanged(); + nest.Drawings.RemoveWhere(d => d.Quantity.Nested == 0); + change.Complete(); + return true; + } + + /// + /// Deletes and its parts from every plate, as one "Delete Drawing" + /// step. The plates' part lists keep the drawings' nested quantities. + /// + public static void DeleteDrawing(Nest nest, Drawing drawing, Func beginChange) + { + ArgumentNullException.ThrowIfNull(nest); + ArgumentNullException.ThrowIfNull(drawing); + ArgumentNullException.ThrowIfNull(beginChange); + using var change = beginChange(DeleteLabel); + change.MarkChanged(); + // Emptying the last plates drops trailing empty ones, so walk a copy. + foreach (var plate in nest.Plates.ToList()) + { + for (var i = plate.Parts.Count - 1; i >= 0; i--) + { + if (plate.Parts[i].BaseDrawing == drawing) + plate.Parts.RemoveAt(i); + } + } + + nest.Drawings.Remove(drawing); + change.Complete(); + } + + /// + /// The Drawing Properties dialog's OK: saved to its drawing as + /// one "Drawing Properties" step. A cancelled dialog calls nothing, so nothing is recorded. + /// + public static void ApplyProperties(DrawingProperties properties, Func beginChange) + { + ArgumentNullException.ThrowIfNull(properties); + ArgumentNullException.ThrowIfNull(beginChange); + using var change = beginChange(PropertiesLabel); + change.MarkChanged(); + properties.ApplyTo(properties.Drawing); + change.Complete(); + } +} diff --git a/OpenNest.Desktop/DrawingListRow.cs b/OpenNest.Desktop/DrawingListRow.cs new file mode 100644 index 00000000..1cdb1a29 --- /dev/null +++ b/OpenNest.Desktop/DrawingListRow.cs @@ -0,0 +1,83 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace OpenNest.Desktop; + +/// The bar down a Drawings tab row's left edge, for a drawing with a required quantity. +public enum DrawingQuantityBar +{ + /// No quantity is required (or quantities are hidden): no bar. + None, + + /// All of the required quantity is nested: a green bar. + Complete, + + /// Some of the required quantity is still to nest: an orange bar. + Short, +} + +/// +/// One row of the Drawings tab list, as the WinForms list draws it beside the drawing's +/// thumbnail: its name, "[on this plate] nested of required nested", its size and its area in +/// square units. A drawing whose nested parts left none remaining is highlighted, and a drawing +/// with a required quantity carries a bar saying whether all of it is nested. +/// +public sealed record DrawingListRow( + Drawing Drawing, + string Name, + string Quantity, + string Size, + string Area, + bool IsHighlighted, + DrawingQuantityBar Bar) +{ + /// The note an emptied list shows when Hide Fully Nested Drawings hid every drawing. + public const string AllHiddenText = "All drawings are fully nested and hidden.\n\nClick here to show them."; + + /// + /// The row of . Its count on (the plate + /// shown beside the list; null omits it) prefixes the quantity when there is one. With + /// the row has no quantity, highlight or bar. + /// + public static DrawingListRow For(Drawing drawing, Plate plate, Units units, bool hideQuantity = false) + { + ArgumentNullException.ThrowIfNull(drawing); + var quantity = drawing.Quantity; + string quantityText = null; + var bar = DrawingQuantityBar.None; + if (!hideQuantity) + { + quantityText = $"{quantity.Nested} of {quantity.Required} nested"; + var onPlate = plate?.Parts.Count(part => part.BaseDrawing == drawing) ?? 0; + if (onPlate > 0) + quantityText = $"[{onPlate}] {quantityText}"; + if (quantity.Required > 0) + bar = quantity.Nested >= quantity.Required ? DrawingQuantityBar.Complete : DrawingQuantityBar.Short; + } + + return new DrawingListRow( + drawing, + drawing.Name, + quantityText, + drawing.Program.BoundingBox().Size.ToString(4), + $"{System.Math.Round(drawing.Area, 4)} sq/{UnitsHelper.GetShortString(units)}", + !hideQuantity && quantity.Nested > 0 && quantity.Remaining == 0, + bar); + } + + /// The rows of , in their order. + public static IReadOnlyList For(IEnumerable drawings, Plate plate, Units units) + { + ArgumentNullException.ThrowIfNull(drawings); + return drawings.Select(drawing => For(drawing, plate, units)).ToList(); + } + + /// + /// The note the list shows in place of rows: when Hide Fully + /// Nested Drawings () emptied a list of a nest that has + /// drawings, so they don't look lost; otherwise null. The filter stays the user's choice. + /// + public static string EmptyText(bool hideFullyNested, int drawingCount) => + hideFullyNested && drawingCount > 0 ? AllHiddenText : null; +} diff --git a/OpenNest.Desktop/DrawingProperties.cs b/OpenNest.Desktop/DrawingProperties.cs new file mode 100644 index 00000000..d35c7951 --- /dev/null +++ b/OpenNest.Desktop/DrawingProperties.cs @@ -0,0 +1,171 @@ +using System; +using System.Drawing; + +namespace OpenNest.Desktop; + +/// +/// The Drawing Properties dialog's values and rules, toolkit-neutral: read from a drawing, edited +/// by the dialog, then saved back with . Its color is either one picked here +/// (custom) or the color scheme's palette color for the drawing's slot in the nest (Automatic); +/// only a color actually picked becomes custom, so reopening and saving keeps the palette color. +/// +public sealed class DrawingProperties +{ + /// The quantity and priority boxes' limits. + public const int MaxQuantity = 999999; + + public const int MinPriority = -999999; + + public const int MaxPriority = 999999; + + public const string CustomColorText = "Custom color"; + + public const string AutomaticColorText = "Automatic color from the color scheme"; + + // The palette color Automatic asked for, while the color is still that one. + private Color? automaticColor; + + /// Reads 's values; holds it (or null). + public DrawingProperties(Drawing drawing, Nest nest = null) + { + ArgumentNullException.ThrowIfNull(drawing); + Drawing = drawing; + Nest = nest; + Color = drawing.Color; + Name = drawing.Name; + Customer = drawing.Customer; + Quantity = drawing.Quantity.Required; + Priority = drawing.Priority; + CutFirst = drawing.CutFirst; + AllowCommonLine = drawing.AllowCommonLine; + Formed = drawing.IsFormed; + } + + public Drawing Drawing { get; } + + public Nest Nest { get; } + + public string Name { get; set; } + + public string Customer { get; set; } + + public int Quantity { get; set; } + + public int Priority { get; set; } + + public bool CutFirst { get; set; } + + public bool AllowCommonLine { get; set; } + + /// Formed (bent or rolled) after cutting. + public bool Formed { get; set; } + + /// The color shown; set it directly to keep a pending Automatic when it is unchanged. + public Color Color { get; set; } + + /// The dialog's title. + public string Title => string.IsNullOrEmpty(Drawing.Name) + ? "Drawing Properties" + : $"Drawing Properties - {Drawing.Name}"; + + /// A color picked in the dialog: it cancels a pending Automatic. + public void PickColor(Color color) + { + automaticColor = null; + Color = color; + } + + /// Automatic: the palette color for the drawing's slot, saved as not custom. + public void UseAutomaticColor() + { + automaticColor = AutomaticColor(); + Color = automaticColor.Value; + } + + public bool IsAutomaticColorRequested => automaticColor?.ToArgb() == Color.ToArgb(); + + /// Whether saving makes (or keeps) the color custom. + public bool IsCustomColor => + !IsAutomaticColorRequested + && (Drawing.HasCustomColor || Color.ToArgb() != Drawing.Color.ToArgb()); + + /// The note beside the color swatch. + public string ColorModeText => IsCustomColor ? CustomColorText : AutomaticColorText; + + /// Whether Automatic can be chosen: only for a custom color. + public bool CanUseAutomaticColor => IsCustomColor; + + /// The palette color for the drawing's slot among the nest's non-cutoff drawings. + public Color AutomaticColor() + { + var index = 0; + if (Nest != null) + { + foreach (var d in Nest.Drawings) + { + if (ReferenceEquals(d, Drawing)) + break; + if (!d.IsCutOff) + index++; + } + } + return Drawing.GetPartColor(index); + } + + /// "n nested, m remaining", the remaining counted against the quantity being edited. + public string NestedText + { + get + { + var nested = Drawing.Quantity.Nested; + var remaining = System.Math.Max(Quantity - nested, 0); + return $"{nested} nested, {remaining} remaining"; + } + } + + public string SizeText + { + get + { + var box = Drawing.Program.BoundingBox(); + return $"{box.Length:0.###} x {box.Width:0.###}"; + } + } + + public string AreaText => $"{Drawing.Area:0.###}"; + + /// The full path of the file the drawing came from, or null. + public string SourcePath => string.IsNullOrEmpty(Drawing.Source?.Path) ? null : Drawing.Source.Path; + + /// The source file's name, or "-" when there is none. + public string SourceText => SourcePath == null ? "-" : System.IO.Path.GetFileName(SourcePath); + + /// Saves the values to ; Automatic recolors the nest's drawings. + public void ApplyTo(Drawing drawing) + { + ArgumentNullException.ThrowIfNull(drawing); + drawing.Name = Name; + drawing.Customer = Customer; + drawing.Quantity.Required = Quantity; + drawing.Priority = Priority; + drawing.CutFirst = CutFirst; + drawing.AllowCommonLine = AllowCommonLine; + drawing.SetFormed(Formed); + if (IsAutomaticColorRequested) + { + if (!drawing.HasCustomColor) + return; + + drawing.HasCustomColor = false; + if (Nest != null && Nest.Drawings.Contains(drawing)) + ColorSchemeRegistry.RecolorDrawings(Nest); + else + drawing.Color = AutomaticColor(); + } + else if (IsCustomColor) + { + drawing.Color = Color; + drawing.HasCustomColor = true; + } + } +} diff --git a/OpenNest/Controls/DrawingListBox.cs b/OpenNest/Controls/DrawingListBox.cs index 9349d865..fe0a47db 100644 --- a/OpenNest/Controls/DrawingListBox.cs +++ b/OpenNest/Controls/DrawingListBox.cs @@ -3,6 +3,7 @@ using System.Drawing; using System.Linq; using System.Runtime.InteropServices; using System.Windows.Forms; +using OpenNest.Desktop; using Size = System.Drawing.Size; namespace OpenNest.Controls @@ -204,12 +205,8 @@ namespace OpenNest.Controls return; var isSelected = (e.State & DrawItemState.Selected) != 0; - Brush bgBrush; - - if (!HideQuantity && dwg.Quantity.Nested > 0 && dwg.Quantity.Remaining == 0) - bgBrush = SystemBrushes.Info; - else - bgBrush = Brushes.White; + var row = DrawingListRow.For(dwg, Plate, Units, HideQuantity); + var bgBrush = row.IsHighlighted ? SystemBrushes.Info : Brushes.White; e.Graphics.FillRectangle(bgBrush, e.Bounds); @@ -225,11 +222,11 @@ namespace OpenNest.Controls e.Graphics.DrawRectangle(borderPen, borderRect); } - if (!HideQuantity && dwg.Quantity.Required > 0) + if (row.Bar != DrawingQuantityBar.None) { var barWidth = 4; var barColor = - dwg.Quantity.Nested >= dwg.Quantity.Required + row.Bar == DrawingQuantityBar.Complete ? Color.FromArgb(76, 175, 80) : Color.FromArgb(255, 152, 0); using var barBrush = new SolidBrush(barColor); @@ -259,43 +256,23 @@ namespace OpenNest.Controls var textBrush = Brushes.Black; var detailBrush = Brushes.Gray; - e.Graphics.DrawString(dwg.Name, nameFont, textBrush, pt); + e.Graphics.DrawString(row.Name, nameFont, textBrush, pt); - var bounds = dwg.Program.BoundingBox(); - var text2 = bounds.Size.ToString(4); - var text3 = string.Format( - "{0} sq/{1}", - System.Math.Round(dwg.Area, 4), - UnitsHelper.GetShortString(Units) - ); - - if (HideQuantity) + if (row.Quantity != null) { pt.Y += 22; - e.Graphics.DrawString(text2, Font, detailBrush, pt); + e.Graphics.DrawString(row.Quantity, Font, detailBrush, pt); pt.Y += 18; - e.Graphics.DrawString(text3, Font, detailBrush, pt); } else { - var text1 = string.Format( - "{0} of {1} nested", - dwg.Quantity.Nested, - dwg.Quantity.Required - ); - var onPlate = Plate?.Parts.Count(part => part.BaseDrawing == dwg) ?? 0; - - if (onPlate > 0) - text1 = $"[{onPlate}] {text1}"; - pt.Y += 22; - e.Graphics.DrawString(text1, Font, detailBrush, pt); - pt.Y += 18; - e.Graphics.DrawString(text2, Font, detailBrush, pt); - pt.Y += 18; - e.Graphics.DrawString(text3, Font, detailBrush, pt); } + e.Graphics.DrawString(row.Size, Font, detailBrush, pt); + pt.Y += 18; + e.Graphics.DrawString(row.Area, Font, detailBrush, pt); + using var separatorPen = new Pen(Color.LightGray); var separatorY = e.Bounds.Bottom - 1; e.Graphics.DrawLine(separatorPen, e.Bounds.X, separatorY, e.Bounds.Right, separatorY); diff --git a/OpenNest/Forms/EditDrawingForm.cs b/OpenNest/Forms/EditDrawingForm.cs index f2572c5b..51f7b419 100644 --- a/OpenNest/Forms/EditDrawingForm.cs +++ b/OpenNest/Forms/EditDrawingForm.cs @@ -1,6 +1,7 @@ using System; using System.Drawing; using System.Windows.Forms; +using OpenNest.Desktop; namespace OpenNest.Forms { @@ -9,8 +10,7 @@ namespace OpenNest.Forms private const int PreviewInset = 24; private Drawing drawing; - private Nest nest; - private Color? automaticColor; + private DrawingProperties properties; public EditDrawingForm() { @@ -89,9 +89,9 @@ namespace OpenNest.Forms private void UpdateColor() { colorSwatch.BackColor = colorDialog1.Color; - var customColor = IsCustomColor; - colorModeLabel.Text = customColor ? "Custom color" : "Automatic color from the color scheme"; - automaticColorButton.Enabled = customColor; + properties.Color = colorDialog1.Color; + colorModeLabel.Text = properties.ColorModeText; + automaticColorButton.Enabled = properties.CanUseAutomaticColor; UpdateImage(); } @@ -100,74 +100,32 @@ namespace OpenNest.Forms if (drawing == null) return; - var nested = drawing.Quantity.Nested; - var remaining = System.Math.Max(Quantity - nested, 0); - nestedLabel.Text = $"{nested} nested, {remaining} remaining"; + properties.Quantity = Quantity; + nestedLabel.Text = properties.NestedText; } private void LoadDetails() { - var box = drawing.Program.BoundingBox(); - sizeLabel.Text = $"{box.Length:0.###} x {box.Width:0.###}"; - areaLabel.Text = $"{drawing.Area:0.###}"; - - var path = drawing.Source?.Path; - if (string.IsNullOrEmpty(path)) - { - sourceLabel.Text = "-"; - toolTip.SetToolTip(sourceLabel, null); - } - else - { - sourceLabel.Text = System.IO.Path.GetFileName(path); - toolTip.SetToolTip(sourceLabel, path); - } + sizeLabel.Text = properties.SizeText; + areaLabel.Text = properties.AreaText; + sourceLabel.Text = properties.SourceText; + toolTip.SetToolTip(sourceLabel, properties.SourcePath); } - /// - /// The palette color for the drawing's slot among the nest's non-cutoff drawings. - /// - private Color AutomaticColor() - { - var index = 0; - if (nest != null) - { - foreach (var d in nest.Drawings) - { - if (ReferenceEquals(d, drawing)) - break; - if (!d.IsCutOff) - index++; - } - } - return Drawing.GetPartColor(index); - } - - private bool IsAutomaticColorRequested => - automaticColor?.ToArgb() == colorDialog1.Color.ToArgb(); - - // Only a color actually picked here becomes custom; reopening and saving keeps the palette color. - private bool IsCustomColor => - !IsAutomaticColorRequested - && (drawing.HasCustomColor || colorDialog1.Color.ToArgb() != drawing.Color.ToArgb()); - public void LoadDrawing(Drawing drawing, Nest nest = null) { this.drawing = drawing; - this.nest = nest; - automaticColor = null; + properties = new DrawingProperties(drawing, nest); - colorDialog1.Color = drawing.Color; - DrawingName = drawing.Name; - Customer = drawing.Customer; - Quantity = drawing.Quantity.Required; - Priority = drawing.Priority; - CutFirst = drawing.CutFirst; - AllowCommonLine = drawing.AllowCommonLine; - Formed = drawing.IsFormed; - Text = string.IsNullOrEmpty(drawing.Name) - ? "Drawing Properties" - : $"Drawing Properties - {drawing.Name}"; + colorDialog1.Color = properties.Color; + DrawingName = properties.Name; + Customer = properties.Customer; + Quantity = properties.Quantity; + Priority = properties.Priority; + CutFirst = properties.CutFirst; + AllowCommonLine = properties.AllowCommonLine; + Formed = properties.Formed; + Text = properties.Title; LoadDetails(); UpdateNestedLabel(); UpdateColor(); @@ -175,29 +133,16 @@ namespace OpenNest.Forms public void SaveDrawing(Drawing drawing) { - drawing.Name = DrawingName; - drawing.Customer = Customer; - drawing.Quantity.Required = Quantity; - drawing.Priority = Priority; - drawing.CutFirst = CutFirst; - drawing.AllowCommonLine = AllowCommonLine; - drawing.SetFormed(Formed); - if (IsAutomaticColorRequested) - { - if (!drawing.HasCustomColor) - return; - - drawing.HasCustomColor = false; - if (nest != null && nest.Drawings.Contains(drawing)) - ColorSchemeRegistry.RecolorDrawings(nest); - else - drawing.Color = AutomaticColor(); - } - else if (IsCustomColor) - { - drawing.Color = colorDialog1.Color; - drawing.HasCustomColor = true; - } + properties.Name = DrawingName; + properties.Customer = Customer; + properties.Quantity = Quantity; + properties.Priority = Priority; + properties.CutFirst = CutFirst; + properties.AllowCommonLine = AllowCommonLine; + properties.Formed = Formed; + // The dialog's color is the one shown; a pending Automatic holds while it is unchanged. + properties.Color = colorDialog1.Color; + properties.ApplyTo(drawing); } protected override void OnShown(EventArgs e) @@ -215,14 +160,14 @@ namespace OpenNest.Forms return; // A picked color cancels a pending Automatic. - automaticColor = null; + properties.PickColor(colorDialog1.Color); UpdateColor(); } private void AutomaticColor_Click(object sender, EventArgs e) { - automaticColor = AutomaticColor(); - colorDialog1.Color = automaticColor.Value; + properties.UseAutomaticColor(); + colorDialog1.Color = properties.Color; UpdateColor(); } } diff --git a/OpenNest/Forms/EditNestForm.cs b/OpenNest/Forms/EditNestForm.cs index 78381648..b47f1b21 100644 --- a/OpenNest/Forms/EditNestForm.cs +++ b/OpenNest/Forms/EditNestForm.cs @@ -674,10 +674,7 @@ namespace OpenNest.Forms /// private void UpdateDrawingListEmptyText() { - drawingListBox1.EmptyText = - hideNestedButton.Checked && Nest.Drawings.Count > 0 - ? "All drawings are fully nested and hidden.\n\nClick here to show them." - : null; + drawingListBox1.EmptyText = DrawingListRow.EmptyText(hideNestedButton.Checked, Nest.Drawings.Count); } public void Save() @@ -1774,8 +1771,8 @@ namespace OpenNest.Forms private void drawingListBox1_RemoveUnusedRequested(object sender, EventArgs e) { var result = MessageBox.Show( - "Remove unused drawings?", - "Clean Drawings", + DrawingCommands.CleanUnusedPrompt, + DrawingCommands.CleanUnusedTitle, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1 @@ -1788,10 +1785,9 @@ namespace OpenNest.Forms /// Removes the drawings with no part on any plate. public void CleanUnusedDrawings() { - if (!Nest.Drawings.Any(d => d.Quantity.Nested == 0)) + if (!DrawingCommands.CleanUnusedDrawings(Nest, label => BeginChange(label))) return; - RecordChange("Clean Unused Drawings", () => Nest.Drawings.RemoveWhere(d => d.Quantity.Nested == 0)); UpdateDrawingList(); } @@ -1911,7 +1907,7 @@ namespace OpenNest.Forms if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK) { - RecordChange("Drawing Properties", () => form.SaveDrawing(drawing)); + RecordChange(DrawingCommands.PropertiesLabel, () => form.SaveDrawing(drawing)); RefreshDrawingColor(drawing); @@ -1931,8 +1927,8 @@ namespace OpenNest.Forms private void drawingListBox1_DeleteRequested(object sender, Drawing drawing) { var result = MessageBox.Show( - $"Delete drawing '{drawing.Name}' and all its parts from every plate?", - "Delete Drawing", + DrawingCommands.DeletePrompt(drawing), + DrawingCommands.DeleteTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2 @@ -1947,20 +1943,7 @@ namespace OpenNest.Forms /// Deletes and its parts from every plate. public void DeleteDrawing(Drawing drawing) { - RecordChange("Delete Drawing", () => - { - // Emptying the last plates drops trailing empty ones, so walk a copy. - foreach (var plate in Nest.Plates.ToList()) - { - for (var i = plate.Parts.Count - 1; i >= 0; i--) - { - if (plate.Parts[i].BaseDrawing == drawing) - plate.Parts.RemoveAt(i); - } - } - - Nest.Drawings.Remove(drawing); - }); + DrawingCommands.DeleteDrawing(Nest, drawing, label => BeginChange(label)); UpdateDrawingList(); UpdatePlateList(); PlateView.Invalidate(); From 763584609473e7757257924ed2f6cfef3ba43e39 Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Mon, 30 Nov 2026 18:53:18 -0500 Subject: [PATCH 2/2] feat(avalonia): port the Drawings tab and Drawing Properties The Drawings tab now shows the WinForms rows: each drawing's picture, name, "[on this plate] nested of required nested", size and area, with the fully-nested highlight and quantity bar, refreshed 50 ms after parts change 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, with the note to show them again. Its menu deletes a drawing or removes the unused ones after the WinForms confirmations, and a double-click opens Drawing Properties; each edit is one undo step through the shared commands. Co-Authored-By: Claude Opus 5.5 --- OpenNest.Avalonia/DrawingListItem.cs | 78 ++++ OpenNest.Avalonia/DrawingPropertiesDialog.cs | 391 ++++++++++++++++++ OpenNest.Avalonia/NestView.Drawings.cs | 288 +++++++++++++ OpenNest.Avalonia/NestView.axaml | 67 ++- OpenNest.Avalonia/NestView.axaml.cs | 34 +- .../Rendering/DrawingThumbnail.cs | 127 ++++++ 6 files changed, 953 insertions(+), 32 deletions(-) create mode 100644 OpenNest.Avalonia/DrawingListItem.cs create mode 100644 OpenNest.Avalonia/DrawingPropertiesDialog.cs create mode 100644 OpenNest.Avalonia/NestView.Drawings.cs create mode 100644 OpenNest.Avalonia/Rendering/DrawingThumbnail.cs 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 @@ - - - - - - - + + + + +