diff --git a/OpenNest.WinForms.Tests/Controls/PlateListBoxTests.cs b/OpenNest.WinForms.Tests/Controls/PlateListBoxTests.cs new file mode 100644 index 00000000..e2907070 --- /dev/null +++ b/OpenNest.WinForms.Tests/Controls/PlateListBoxTests.cs @@ -0,0 +1,83 @@ +using System.Drawing; +using OpenNest.Controls; +using OpenNest.Geometry; +using OpenNest.Shapes; + +namespace OpenNest.WinForms.Tests.Controls; + +/// The Plates tab list draws each plate's picture once and redraws it only when it changes. +public class PlateListBoxTests +{ + [Fact] + public void ThePictureIsReusedUntilAPartMoves() => RunSta(() => + { + var (plate, part) = CreatePlate(); + using var list = new PlateListBox(); + list.SetPlates([plate]); + + var first = list.GetPreview(plate); + Assert.Same(first, list.GetPreview(plate)); + var before = Snapshot(first); + + part.Offset(new Vector(30, 0)); + var moved = list.GetPreview(plate); + + Assert.NotSame(first, moved); + Assert.NotEqual(before, Snapshot(moved)); + }); + + [Fact] + public void PartsShowInTheirDrawingsColorOnTheSheet() => RunSta(() => + { + var (plate, part) = CreatePlate(); + part.BaseDrawing.Color = Color.FromArgb(255, 200, 30, 30); + using var list = new PlateListBox(); + list.SetPlates([plate]); + + using var image = (Bitmap)list.GetPreview(plate).Clone(); + var found = false; + for (var x = 0; x < image.Width && !found; x++) + for (var y = 0; y < image.Height && !found; y++) + found = image.GetPixel(x, y).ToArgb() == part.BaseDrawing.Color.ToArgb(); + + Assert.True(found); + }); + + [Fact] + public void RowsBelowTheLastPlateAreNoRow() => RunSta(() => + { + var (plate, _) = CreatePlate(); + using var list = new PlateListBox { Height = 400 }; + list.CreateControl(); + list.SetPlates([plate]); + + Assert.Equal(0, list.RowAt(new Point(5, 5))); + Assert.Equal(-1, list.RowAt(new Point(5, list.ItemHeight + 10))); + }); + + private static (Plate Plate, Part Part) CreatePlate() + { + var nest = new Nest("preview"); + var drawing = new RectangleShape { Name = "SYN", Length = 20, Width = 10 }.GetDrawing(); + nest.Drawings.Add(drawing); + var plate = nest.CreatePlate(); + plate.Size = new OpenNest.Geometry.Size(60, 120); + var part = new Part(drawing); + part.Offset(new Vector(5, 5)); + plate.Parts.Add(part); + return (plate, part); + } + + private static int[] Snapshot(Image image) + { + using var bitmap = new Bitmap(image); + var pixels = new int[bitmap.Width * bitmap.Height]; + for (var y = 0; y < bitmap.Height; y++) + for (var x = 0; x < bitmap.Width; x++) + pixels[y * bitmap.Width + x] = bitmap.GetPixel(x, y).ToArgb(); + return pixels; + } + + private static void RunSta(System.Action testBody) => + StaTestThread.Run(testBody, TimeSpan.FromSeconds(60), "The plate list STA test did not complete."); +} diff --git a/OpenNest.WinForms.Tests/Forms/EditNestFocusTraversalTests.cs b/OpenNest.WinForms.Tests/Forms/EditNestFocusTraversalTests.cs index 6c80e121..cbac64ac 100644 --- a/OpenNest.WinForms.Tests/Forms/EditNestFocusTraversalTests.cs +++ b/OpenNest.WinForms.Tests/Forms/EditNestFocusTraversalTests.cs @@ -1,5 +1,6 @@ using System.Reflection; using System.Windows.Forms; +using OpenNest.Controls; using OpenNest.Forms; namespace OpenNest.WinForms.Tests.Forms; @@ -136,10 +137,10 @@ public class EditNestFocusTraversalTests return Assert.IsAssignableFrom(method.Invoke(form, null)); } - private static ListView PlateList(EditNestForm form) => - Assert.IsType(Assert.Single(form.Controls.Find("platesListView", true))); + private static PlateListBox PlateList(EditNestForm form) => + Assert.IsType(Assert.Single(form.Controls.Find("platesListView", true))); - private static void SelectPlatesTab(EditNestForm form, ListView plates) + private static void SelectPlatesTab(EditNestForm form, PlateListBox plates) { var tabControl = Assert.IsType(Assert.Single(form.Controls.Find("tabControl1", true))); tabControl.SelectedTab = Assert.IsType(plates.Parent); diff --git a/OpenNest.WinForms.Tests/Forms/EditNestPlateStockTooltipTests.cs b/OpenNest.WinForms.Tests/Forms/EditNestPlateStockTooltipTests.cs index c0afdd67..1d87e676 100644 --- a/OpenNest.WinForms.Tests/Forms/EditNestPlateStockTooltipTests.cs +++ b/OpenNest.WinForms.Tests/Forms/EditNestPlateStockTooltipTests.cs @@ -1,4 +1,5 @@ using System.Windows.Forms; +using OpenNest.Controls; using OpenNest.Forms; using OpenNest.Shapes; @@ -22,10 +23,9 @@ public class EditNestPlateStockTooltipTests form.LedgerLocations["DROP-1182"] = "B3"; form.UpdatePlateList(); - var plates = Assert.IsType(Assert.Single(form.Controls.Find("platesListView", true))); - Assert.True(plates.ShowItemToolTips); - Assert.Equal("Stock: DROP-1182 (B3)", plates.Items[0].ToolTipText); - Assert.Equal("", plates.Items[^1].ToolTipText); + var plates = Assert.IsType(Assert.Single(form.Controls.Find("platesListView", true))); + Assert.Equal("Stock: DROP-1182 (B3)", plates.GetToolTipText(0)); + Assert.Equal("", plates.GetToolTipText(plates.Items.Count - 1)); }); private static void RunSta(System.Action testBody) => diff --git a/OpenNest.WinForms.Tests/Forms/PlateReorderTests.cs b/OpenNest.WinForms.Tests/Forms/PlateReorderTests.cs index b53f2801..a15b329d 100644 --- a/OpenNest.WinForms.Tests/Forms/PlateReorderTests.cs +++ b/OpenNest.WinForms.Tests/Forms/PlateReorderTests.cs @@ -1,5 +1,6 @@ using System.Drawing; using System.Windows.Forms; +using OpenNest.Controls; using OpenNest.Forms; namespace OpenNest.WinForms.Tests.Forms; @@ -18,15 +19,15 @@ public class PlateReorderTests [Fact] public void DropSlotFollowsTheRowHalvesAndStopsBeforeTheSentinel() => UndoTestEnv.Run(env => { - var list = (ListView)Assert.Single(env.Editor.Controls.Find("platesListView", true)); + var list = (PlateListBox)Assert.Single(env.Editor.Controls.Find("platesListView", true)); var movable = env.Editor.PlateManager.MovableCount; Assert.Equal(env.Nest.Plates.Count - 1, movable); - var first = list.Items[0].Bounds; + var first = list.GetItemRectangle(0); Assert.Equal(0, env.Editor.GetPlateDropSlot(new Point(5, first.Top + 1))); Assert.Equal(1, env.Editor.GetPlateDropSlot(new Point(5, first.Bottom - 1))); - var sentinel = list.Items[movable].Bounds; + var sentinel = list.GetItemRectangle(movable); Assert.Equal(movable, env.Editor.GetPlateDropSlot(new Point(5, sentinel.Top + 1))); Assert.Equal(movable, env.Editor.GetPlateDropSlot(new Point(5, list.ClientSize.Height - 1))); }); @@ -41,9 +42,9 @@ public class PlateReorderTests Assert.Same(plate, env.Nest.Plates[1]); Assert.Same(plate, env.Editor.PlateManager.CurrentPlate); - var list = (ListView)Assert.Single(env.Editor.Controls.Find("platesListView", true)); - Assert.True(list.Items[1].Selected); - Assert.Equal("2", list.Items[1].Text); + var list = (PlateListBox)Assert.Single(env.Editor.Controls.Find("platesListView", true)); + Assert.Equal(1, list.SelectedIndex); + Assert.Same(plate, list.Items[1]); }); [Fact] @@ -63,8 +64,8 @@ public class PlateReorderTests Assert.Same(copy, env.Editor.PlateManager.CurrentPlate); if (source.CuttingParameters != null) Assert.NotSame(source.CuttingParameters, copy.CuttingParameters); - var list = (ListView)Assert.Single(env.Editor.Controls.Find("platesListView", true)); - Assert.True(list.Items[1].Selected); + var list = (PlateListBox)Assert.Single(env.Editor.Controls.Find("platesListView", true)); + Assert.Equal(1, list.SelectedIndex); Assert.NotNull(list.ContextMenuStrip); }); @@ -74,7 +75,7 @@ public class PlateReorderTests env.Editor.PlateManager.LoadAt(0); var plate = env.Nest.Plates[0]; var count = env.Nest.Plates.Count; - var list = (ListView)Assert.Single(env.Editor.Controls.Find("platesListView", true)); + var list = (PlateListBox)Assert.Single(env.Editor.Controls.Find("platesListView", true)); var item = Assert.IsType(list.ContextMenuStrip!.Items["deletePlateMenuItem"]); Assert.Equal("Delete Plate", item.Text); diff --git a/OpenNest/Controls/PlateListBox.cs b/OpenNest/Controls/PlateListBox.cs new file mode 100644 index 00000000..bf4ba8ce --- /dev/null +++ b/OpenNest/Controls/PlateListBox.cs @@ -0,0 +1,400 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Windows.Forms; +using OpenNest.CNC; +using OpenNest.Geometry; +using Size = System.Drawing.Size; + +namespace OpenNest.Controls +{ + /// + /// The Plates tab list: one row per plate with a picture of its sheet and parts, its number, + /// size, quantity, part count and utilization, drawn like the drawings list. Pictures are + /// cached per plate and redrawn only when the sheet or a part's placement changes. + /// + public class PlateListBox : ListBox + { + private const int WM_ERASEBKGND = 0x0014; + private const int DragThreshold = 3; + + private readonly Size imageSize; + private readonly Font nameFont; + private readonly ToolTip toolTip = new ToolTip(); + private readonly Dictionary previews = new Dictionary(); + private int toolTipIndex = -1; + private int pressedIndex = -1; + private Point pressedLocation; + + public PlateListBox() + { + DrawMode = DrawMode.OwnerDrawFixed; + ItemHeight = 85; + IntegralHeight = false; + + imageSize = new Size(110, ItemHeight - 10); + nameFont = new Font(Font.FontFamily, 10, FontStyle.Bold); + } + + /// The scheme the pictures take the sheet colors from. + public ColorScheme ColorScheme { get; set; } = ColorScheme.Default; + + /// The tooltip shown over a plate's row; null or empty shows none. + public Func ToolTipProvider { get; set; } + + /// + /// Raised when the left button is pressed on a row and the pointer then moves past the + /// drag threshold; the argument is the row's index. + /// + public event EventHandler RowDragStarted; + + /// The tooltip text of the row at , "" when it has none. + public string GetToolTipText(int index) => + index >= 0 && index < Items.Count && Items[index] is Plate plate + ? ToolTipProvider?.Invoke(plate) ?? "" + : ""; + + /// + /// Replaces the rows with , keeping the scroll position, and + /// forgets the pictures of plates no longer listed. + /// + public void SetPlates(IReadOnlyList plates) + { + var topIndex = TopIndex; + + BeginUpdate(); + Items.Clear(); + Items.AddRange(plates.Cast().ToArray()); + if (topIndex < Items.Count) + TopIndex = topIndex; + EndUpdate(); + + foreach (var gone in previews.Keys.Where(plate => !plates.Contains(plate)).ToList()) + { + previews[gone].Dispose(); + previews.Remove(gone); + } + } + + /// + /// The index of the row containing , or -1 when the point is + /// in the empty area below the last row. + /// + public int RowAt(Point location) + { + var index = IndexFromPoint(location); + if (index < 0 || index >= Items.Count) + return -1; + + return GetItemRectangle(index).Contains(location) ? index : -1; + } + + protected override void OnDrawItem(DrawItemEventArgs e) + { + if (e.Index < 0 || e.Index >= Items.Count || Items[e.Index] is not Plate plate) + return; + + var g = e.Graphics; + g.FillRectangle(Brushes.White, e.Bounds); + + if ((e.State & DrawItemState.Selected) != 0) + { + using var borderPen = new Pen(SystemColors.Highlight, 2); + g.DrawRectangle(borderPen, e.Bounds.X, e.Bounds.Y, e.Bounds.Width - 1, e.Bounds.Height - 1); + } + + g.DrawImage(GetPreview(plate), e.Bounds.X + 5, e.Bounds.Y + 5); + + var isSentinel = e.Index == Items.Count - 1 && plate.Parts.Count == 0; + var pt = new PointF(e.Bounds.X + imageSize.Width + 15, e.Bounds.Y + 5); + g.DrawString(isSentinel ? "New plate" : $"Plate {e.Index + 1}", nameFont, Brushes.Black, pt); + + var partCount = plate.Parts.Count(part => !part.BaseDrawing.IsCutOff); + var quantity = plate.Quantity > 1 ? $"×{plate.Quantity} " : ""; + var lines = new List + { + plate.Size.ToString(4), + isSentinel ? "Empty" : $"{quantity}{partCount} {(partCount == 1 ? "part" : "parts")}", + }; + if (partCount > 0) + lines.Add($"{plate.Utilization():P0} utilized"); + + foreach (var line in lines) + { + pt.Y += line == lines[0] ? 22 : 18; + g.DrawString(line, Font, Brushes.Gray, pt); + } + + using var separatorPen = new Pen(Color.LightGray); + var separatorY = e.Bounds.Bottom - 1; + g.DrawLine(separatorPen, e.Bounds.X, separatorY, e.Bounds.Right, separatorY); + } + + /// The plate's picture, redrawn only when what it shows has changed. + internal Image GetPreview(Plate plate) + { + var signature = Signature(plate); + if (previews.TryGetValue(plate, out var preview)) + { + if (preview.Signature == signature) + return preview.Image; + preview.Dispose(); + } + + preview = new Preview(signature, RenderPreview(plate)); + previews[plate] = preview; + return preview.Image; + } + + // Everything the picture shows: the sheet, its scheme and each part's program, place and color. + private int Signature(Plate plate) + { + var hash = new HashCode(); + hash.Add(plate.Size.Length); + hash.Add(plate.Size.Width); + hash.Add(plate.Quadrant); + hash.Add(RuntimeHelpers.GetHashCode(plate.Outline)); + hash.Add(RuntimeHelpers.GetHashCode(ColorScheme)); + foreach (var part in plate.Parts) + { + hash.Add(RuntimeHelpers.GetHashCode(part.Program)); + hash.Add(part.Location.X); + hash.Add(part.Location.Y); + // A rotation or mirror can rewrite the program in place, keeping its reference. + hash.Add(part.Rotation); + hash.Add(part.BoundingBox.Length); + hash.Add(part.BoundingBox.Width); + hash.Add(part.BaseDrawing.Color.ToArgb()); + } + + return hash.ToHashCode(); + } + + private Bitmap RenderPreview(Plate plate) + { + var image = new Bitmap(imageSize.Width, imageSize.Height); + using var g = Graphics.FromImage(image); + g.SmoothingMode = SmoothingMode.AntiAlias; + g.Clear(Color.White); + + var length = plate.Size.Length; + var width = plate.Size.Width; + if (length <= 0 || width <= 0) + return image; + + // Sheet extents around the origin as the plate view places them for this quadrant. + var left = plate.Quadrant is 2 or 3 ? -length : 0; + var bottom = plate.Quadrant is 3 or 4 ? -width : 0; + const float margin = 2; + var scale = (float)System.Math.Min( + (imageSize.Width - 2 * margin) / length, + (imageSize.Height - 2 * margin) / width); + var offsetX = (imageSize.Width - (float)length * scale) / 2; + var offsetY = (imageSize.Height + (float)width * scale) / 2; + + // World Y grows up; the sheet's lower-left corner sits at the picture's bottom-left. + using var toDevice = new Matrix(); + toDevice.Translate(offsetX, offsetY); + toDevice.Scale(scale, -scale); + toDevice.Translate((float)-left, (float)-bottom); + + var gdi = ColorScheme.Gdi(); + using var sheet = SheetPath(plate, left, bottom); + sheet.Transform(toDevice); + g.FillPath(gdi.LayoutFillBrush, sheet); + + using var outlinePen = new Pen(Color.FromArgb(70, 70, 70), 0); + var brushes = new Dictionary(); + var pens = new Dictionary(); + // Parts placed from one drawing at one rotation share a program, so a path is built once. + var localPaths = new Dictionary(ReferenceEqualityComparer.Instance); + try + { + foreach (var part in plate.Parts) + { + if (!localPaths.TryGetValue(part.Program, out var local)) + localPaths[part.Program] = local = part.Program.GetFillPath(Vector.Zero); + if (local.PointCount == 0) + continue; + + using var path = (GraphicsPath)local.Clone(); + using var place = toDevice.Clone(); + place.Translate((float)part.Location.X, (float)part.Location.Y); + path.Transform(place); + + var color = part.BaseDrawing.Color; + if (part.BaseDrawing.IsCutOff) + { + g.DrawPath(outlinePen, path); + continue; + } + + if (!brushes.TryGetValue(color, out var brush)) + brushes[color] = brush = new SolidBrush(color); + if (!pens.TryGetValue(color, out var pen)) + pens[color] = pen = new Pen(ColorScheme.GetPartOutlineColor(color), 0); + g.FillPath(brush, path); + g.DrawPath(pen, path); + } + } + finally + { + foreach (var path in localPaths.Values) + path.Dispose(); + foreach (var brush in brushes.Values) + brush.Dispose(); + foreach (var pen in pens.Values) + pen.Dispose(); + } + + g.DrawPath(gdi.LayoutOutlinePen, sheet); + return image; + } + + // The sheet in world units: its outline and obstacles when outlined, else its rectangle. + private static GraphicsPath SheetPath(Plate plate, double left, double bottom) + { + var path = new GraphicsPath(FillMode.Alternate); + var outline = plate.Outline; + if (outline == null) + { + path.AddRectangle(new RectangleF((float)left, (float)bottom, + (float)plate.Size.Length, (float)plate.Size.Width)); + return path; + } + + var origin = outline.PlacementOrigin(plate.Quadrant); + path.AddPolygon(ToPoints(outline.Points, origin)); + foreach (var obstacle in outline.Obstacles) + path.AddPolygon(ToPoints(obstacle, origin)); + return path; + } + + private static PointF[] ToPoints(IReadOnlyList points, Vector origin) => + points.Select(p => new PointF((float)(p.X + origin.X), (float)(p.Y + origin.Y))).ToArray(); + + protected override void OnMouseDown(MouseEventArgs e) + { + // The row menu acts on the current plate, so a right-click picks the row first. + if (e.Button == MouseButtons.Right) + { + var index = RowAt(e.Location); + if (index >= 0) + SelectedIndex = index; + } + + base.OnMouseDown(e); + pressedLocation = e.Location; + pressedIndex = e.Button == MouseButtons.Left && e.Clicks == 1 ? RowAt(e.Location) : -1; + } + + protected override void OnMouseMove(MouseEventArgs e) + { + base.OnMouseMove(e); + UpdateToolTip(e.Location); + + if (pressedIndex < 0 || e.Button != MouseButtons.Left) + return; + if (System.Math.Abs(e.X - pressedLocation.X) <= DragThreshold + && System.Math.Abs(e.Y - pressedLocation.Y) <= DragThreshold) + return; + + var index = pressedIndex; + pressedIndex = -1; + RowDragStarted?.Invoke(this, index); + } + + protected override void OnMouseUp(MouseEventArgs e) + { + pressedIndex = -1; + base.OnMouseUp(e); + } + + protected override void OnMouseLeave(EventArgs e) + { + base.OnMouseLeave(e); + toolTipIndex = -1; + toolTip.Hide(this); + } + + private void UpdateToolTip(Point location) + { + var index = RowAt(location); + if (index == toolTipIndex) + return; + + toolTipIndex = index; + var text = GetToolTipText(index); + toolTip.SetToolTip(this, string.IsNullOrEmpty(text) ? null : text); + } + + protected override void WndProc(ref Message m) + { + if (m.Msg == WM_ERASEBKGND) + { + // Rows paint themselves; only the area below the last row needs erasing. Windows + // erases a resized window before WinForms hears the new size, so the client + // size comes from Windows (as in the drawings list). + GetClientRect(Handle, out var client); + var clientWidth = client.Right - client.Left; + var clientHeight = client.Bottom - client.Top; + var itemBottom = Items.Count > 0 ? System.Math.Max(0, GetItemRectangle(Items.Count - 1).Bottom) : 0; + if (itemBottom < clientHeight) + { + using var g = Graphics.FromHdc(m.WParam); + g.FillRectangle(Brushes.White, 0, itemBottom, clientWidth, clientHeight - itemBottom); + } + + m.Result = (IntPtr)1; + return; + } + + base.WndProc(ref m); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + foreach (var preview in previews.Values) + preview.Dispose(); + previews.Clear(); + toolTip.Dispose(); + nameFont.Dispose(); + } + + base.Dispose(disposing); + } + + [StructLayout(LayoutKind.Sequential)] + private struct RECT + { + public int Left; + public int Top; + public int Right; + public int Bottom; + } + + [DllImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetClientRect(IntPtr hWnd, out RECT rect); + + private sealed class Preview : IDisposable + { + public Preview(int signature, Image image) + { + Signature = signature; + Image = image; + } + + public int Signature { get; } + public Image Image { get; } + + public void Dispose() => Image.Dispose(); + } + } +} diff --git a/OpenNest/Forms/EditNestForm.Designer.cs b/OpenNest/Forms/EditNestForm.Designer.cs index af9c127f..3093af7d 100644 --- a/OpenNest/Forms/EditNestForm.Designer.cs +++ b/OpenNest/Forms/EditNestForm.Designer.cs @@ -41,12 +41,7 @@ splitContainer = new System.Windows.Forms.SplitContainer(); tabControl1 = new System.Windows.Forms.TabControl(); tabPage1 = new System.Windows.Forms.TabPage(); - platesListView = new System.Windows.Forms.ListView(); - plateNumColumn = new System.Windows.Forms.ColumnHeader(); - sizeColumn = new System.Windows.Forms.ColumnHeader(); - qtyColumn = new System.Windows.Forms.ColumnHeader(); - partsColumn = new System.Windows.Forms.ColumnHeader(); - utilColumn = new System.Windows.Forms.ColumnHeader(); + platesListView = new OpenNest.Controls.PlateListBox(); toolStrip1 = new System.Windows.Forms.ToolStrip(); toolStripLabel2 = new System.Windows.Forms.ToolStripButton(); tabPage2 = new System.Windows.Forms.TabPage(); @@ -114,45 +109,16 @@ // platesListView // platesListView.BorderStyle = System.Windows.Forms.BorderStyle.None; - platesListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { plateNumColumn, sizeColumn, qtyColumn, partsColumn, utilColumn }); platesListView.Dock = System.Windows.Forms.DockStyle.Fill; - platesListView.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 0); - platesListView.FullRowSelect = true; - platesListView.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; + platesListView.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; + platesListView.ItemHeight = 85; platesListView.Location = new System.Drawing.Point(4, 30); platesListView.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - platesListView.MultiSelect = false; platesListView.Name = "platesListView"; platesListView.Size = new System.Drawing.Size(265, 394); platesListView.TabIndex = 1; - platesListView.UseCompatibleStateImageBehavior = false; - platesListView.View = System.Windows.Forms.View.Details; platesListView.DoubleClick += EditSelectedPlate_Click; // - // plateNumColumn - // - plateNumColumn.Text = ""; - plateNumColumn.Width = 30; - // - // sizeColumn - // - sizeColumn.Text = "Size"; - sizeColumn.Width = 80; - // - // qtyColumn - // - qtyColumn.Text = "Qty"; - // - // partsColumn - // - partsColumn.Text = "Parts"; - partsColumn.Width = 45; - // - // utilColumn - // - utilColumn.Text = "Util"; - utilColumn.Width = 45; - // // toolStrip1 // toolStrip1.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; @@ -310,15 +276,10 @@ private System.Windows.Forms.SplitContainer splitContainer; private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage tabPage1; - private System.Windows.Forms.ListView platesListView; - private System.Windows.Forms.ColumnHeader sizeColumn; - private System.Windows.Forms.ColumnHeader qtyColumn; + private OpenNest.Controls.PlateListBox platesListView; private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.TabPage tabPage2; private Controls.DrawingListBox drawingListBox1; - private System.Windows.Forms.ColumnHeader plateNumColumn; - private System.Windows.Forms.ColumnHeader partsColumn; - private System.Windows.Forms.ColumnHeader utilColumn; private System.Windows.Forms.ToolStrip toolStrip2; private System.Windows.Forms.ToolStripButton toolStripButton2; private System.Windows.Forms.ToolStripButton shapeLibraryButton; diff --git a/OpenNest/Forms/EditNestForm.PlateOrder.cs b/OpenNest/Forms/EditNestForm.PlateOrder.cs index a6e96e09..dc50ce8f 100644 --- a/OpenNest/Forms/EditNestForm.PlateOrder.cs +++ b/OpenNest/Forms/EditNestForm.PlateOrder.cs @@ -29,7 +29,7 @@ namespace OpenNest.Forms private void InitializePlateReordering() { platesListView.AllowDrop = true; - platesListView.ItemDrag += PlatesListView_ItemDrag; + platesListView.RowDragStarted += PlatesListView_RowDragStarted; platesListView.DragEnter += PlatesListView_DragOver; platesListView.DragOver += PlatesListView_DragOver; platesListView.DragDrop += PlatesListView_DragDrop; @@ -175,24 +175,22 @@ namespace OpenNest.Forms e.SuppressKeyPress = true; } - private void PlatesListView_ItemDrag(object sender, ItemDragEventArgs e) + private void PlatesListView_RowDragStarted(object sender, int index) { - if (IsInspecting || e.Button != MouseButtons.Left || e.Item is not ListViewItem item) - return; - if (item.Index >= PlateManager.MovableCount) + if (IsInspecting || index < 0 || index >= PlateManager.MovableCount) return; var effects = DragDropEffects.None; if (PlateManager.MovableCount >= 2) effects |= DragDropEffects.Move; - if (PlateManager.CanDuplicatePlate(item.Index, item.Index + 1)) + if (PlateManager.CanDuplicatePlate(index, index + 1)) effects |= DragDropEffects.Copy; if (effects == DragDropEffects.None) return; try { - platesListView.DoDragDrop(new PlateDragData(this, item.Index), effects); + platesListView.DoDragDrop(new PlateDragData(this, index), effects); } finally { @@ -261,15 +259,17 @@ namespace OpenNest.Forms internal int GetPlateDropSlot(Point client) { var movable = PlateManager.MovableCount; - var item = platesListView.GetItemAt(platesListView.ClientSize.Width / 2, client.Y); - if (item == null) + var index = platesListView.RowAt(new Point(platesListView.ClientSize.Width / 2, client.Y)); + if (index < 0) { - var top = platesListView.TopItem; - return top != null && client.Y < top.Bounds.Top ? top.Index : movable; + var top = platesListView.TopIndex; + return top < platesListView.Items.Count && client.Y < platesListView.GetItemRectangle(top).Top + ? top + : movable; } - var bounds = item.Bounds; - var slot = client.Y < bounds.Top + bounds.Height / 2 ? item.Index : item.Index + 1; + var bounds = platesListView.GetItemRectangle(index); + var slot = client.Y < bounds.Top + bounds.Height / 2 ? index : index + 1; return System.Math.Min(slot, movable); } @@ -282,11 +282,13 @@ namespace OpenNest.Forms return; plateDropSlot = slot; - var items = platesListView.Items; - if (items.Count == 0) + var count = platesListView.Items.Count; + if (count == 0) return; - var y = slot < items.Count ? items[slot].Bounds.Top : items[slot - 1].Bounds.Bottom; + var y = slot < count + ? platesListView.GetItemRectangle(slot).Top + : platesListView.GetItemRectangle(slot - 1).Bottom; plateDropIndicator.SetBounds(0, System.Math.Max(0, y - 1), platesListView.ClientSize.Width, 2); plateDropIndicator.Visible = true; plateDropIndicator.BringToFront(); @@ -302,26 +304,22 @@ namespace OpenNest.Forms // Scrolls one row when the pointer nears the top or bottom edge during a drag. private void AutoScrollPlateList(Point client) { - var items = platesListView.Items; - var top = platesListView.TopItem; - if (items.Count == 0 || top == null) + var count = platesListView.Items.Count; + var top = platesListView.TopIndex; + if (count == 0 || top >= count) return; - var margin = top.Bounds.Height; - if (client.Y < margin && top.Index > 0) + var margin = platesListView.ItemHeight; + var visibleRows = System.Math.Max(1, platesListView.ClientSize.Height / margin); + if (client.Y < margin && top > 0) { HidePlateDropIndicator(); - items[top.Index - 1].EnsureVisible(); + platesListView.TopIndex = top - 1; } - else if (client.Y > platesListView.ClientSize.Height - margin) + else if (client.Y > platesListView.ClientSize.Height - margin && top + visibleRows < count) { - var below = platesListView.GetItemAt(1, platesListView.ClientSize.Height - 1); - var next = below == null ? -1 : below.Index + 1; - if (next > 0 && next < items.Count) - { - HidePlateDropIndicator(); - items[next].EnsureVisible(); - } + HidePlateDropIndicator(); + platesListView.TopIndex = top + 1; } } } diff --git a/OpenNest/Forms/EditNestForm.Undo.cs b/OpenNest/Forms/EditNestForm.Undo.cs index f125f59c..ae3d0a49 100644 --- a/OpenNest/Forms/EditNestForm.Undo.cs +++ b/OpenNest/Forms/EditNestForm.Undo.cs @@ -76,7 +76,13 @@ namespace OpenNest.Forms private NestUndoRecorder CreateRecorder() { var recorder = new NestUndoRecorder(Document) { SwapIn = SwapInRestoredNest }; - recorder.Changed += (_, _) => UpdateTitle(); + recorder.Changed += (_, _) => + { + UpdateTitle(); + // A part moved or rotated in place adds and removes nothing, so only a recorded + // edit tells the plate list its picture may be out of date. + platesListView?.Invalidate(); + }; recorder.Restored += (_, _) => NestRestored?.Invoke(this, EventArgs.Empty); return recorder; } diff --git a/OpenNest/Forms/EditNestForm.cs b/OpenNest/Forms/EditNestForm.cs index 281cb95f..23b77361 100644 --- a/OpenNest/Forms/EditNestForm.cs +++ b/OpenNest/Forms/EditNestForm.cs @@ -108,13 +108,13 @@ namespace OpenNest.Forms toolStrip1.Renderer = renderer; toolStrip2.Renderer = renderer; - platesListView.ShowItemToolTips = true; + platesListView.ToolTipProvider = plate => LedgerStockAssignment.Describe(plate, LedgerLocations); platesListView.SelectedIndexChanged += (sender, e) => { - if (updatingPlateList || platesListView.SelectedIndices.Count == 0) + if (updatingPlateList || platesListView.SelectedIndex < 0) return; - PlateManager.LoadAt(platesListView.SelectedIndices[0]); + PlateManager.LoadAt(platesListView.SelectedIndex); }; InitializePlateReordering(); } @@ -553,24 +553,12 @@ namespace OpenNest.Forms updatingPlateList = true; var focused = ContainsFocus ? GetFocusedControl() : null; - platesListView.BeginUpdate(); - platesListView.Items.Clear(); - - var items = new ListViewItem[Nest.Plates.Count]; - - for (int i = 0; i < items.Length; ++i) - { - var plate = Nest.Plates[i]; - var item = GetListViewItem(plate, i + 1); - items[i] = item; - } - - platesListView.Items.AddRange(items); + platesListView.ColorScheme = PlateView.ColorScheme; + platesListView.SetPlates(Nest.Plates.ToList()); if (PlateManager.CurrentIndex < platesListView.Items.Count) - platesListView.Items[PlateManager.CurrentIndex].Selected = true; + platesListView.SelectedIndex = PlateManager.CurrentIndex; - platesListView.EndUpdate(); updatingPlateList = false; if (focused != null && focused != platesListView) @@ -1311,16 +1299,14 @@ namespace OpenNest.Forms if (index < 0 || index >= platesListView.Items.Count) return; - var item = platesListView.Items[index]; - if (item.Selected) + if (platesListView.SelectedIndex == index) return; - // Guarded so the list's own SelectedIndexChanged doesn't reload the plate. + // Guarded so the list's own SelectedIndexChanged doesn't reload the plate. Selecting + // a row scrolls it into view. var wasUpdating = updatingPlateList; updatingPlateList = true; - item.Selected = true; - item.Focused = true; - item.EnsureVisible(); + platesListView.SelectedIndex = index; updatingPlateList = wasUpdating; } @@ -1456,7 +1442,7 @@ namespace OpenNest.Forms private void EditSelectedPlate_Click(object sender, EventArgs e) { - if (platesListView.SelectedIndices.Count != 0) + if (platesListView.SelectedIndex >= 0) EditPlate(); } @@ -1859,23 +1845,6 @@ namespace OpenNest.Forms #endregion - private ListViewItem GetListViewItem(Plate plate, int id) - { - var item = new ListViewItem(); - item.ToolTipText = LedgerStockAssignment.Describe(plate, LedgerLocations) ?? ""; - item.Text = id.ToString(); - item.SubItems.Add(plate.Size.ToString(4)); - item.SubItems.Add(plate.Quantity.ToString()); - - var partCount = plate.Parts.Count(p => !p.BaseDrawing.IsCutOff); - item.SubItems.Add(partCount.ToString()); - - var util = plate.Utilization(); - item.SubItems.Add(partCount > 0 ? $"{util:P0}" : ""); - - return item; - } - private void PlateView_PartRemoved(object sender, ItemRemovedEventArgs e) { updateDrawingListTimer.Stop();