mirror of
https://github.com/ajisaacs/OpenNest.git
synced 2026-12-01 06:41:42 -05:00
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 <noreply@anthropic.com>
This commit is contained in:
1 parent
8d1204e917
commit
7635846094
6 files changed
+953
-32
No files matched your search
@@ -0,0 +1,78 @@
|
||||
using System.ComponentModel;
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Media.Imaging;
|
||||
using OpenNest.Avalonia.Rendering;
|
||||
using OpenNest.Desktop;
|
||||
|
||||
namespace OpenNest.Avalonia
|
||||
{
|
||||
/// <summary>
|
||||
/// One row of the Drawings tab list: the shared <see cref="DrawingListRow"/> 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.
|
||||
/// </summary>
|
||||
public sealed class DrawingListItem : INotifyPropertyChanged
|
||||
{
|
||||
/// <summary>The picture's size, as the WinForms list draws it.</summary>
|
||||
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);
|
||||
|
||||
/// <summary>Shows <paramref name="value"/>, the same drawing's current row.</summary>
|
||||
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),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// 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 <see cref="DrawingProperties"/> (the caller saves them as one undo step); Cancel or
|
||||
/// Esc returns null and changes nothing.
|
||||
/// </summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>The edited values, or null when the user cancelled.</summary>
|
||||
public static Task<DrawingProperties> ShowAsync(Window owner, Drawing drawing, Nest nest) =>
|
||||
new DrawingPropertiesDialog(drawing, nest).ShowDialog<DrawingProperties>(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,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>The chosen color, or null when the user cancelled.</summary>
|
||||
public static Task<DrawingColor?> ShowAsync(Window owner, DrawingColor current) =>
|
||||
new ColorChoiceDialog(current).ShowDialog<DrawingColor?>(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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<DrawingListItem> 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;
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The drawing selected in the list, or null.</summary>
|
||||
public Drawing SelectedDrawing => (DrawingList.SelectedItem as DrawingListItem)?.Drawing;
|
||||
|
||||
/// <summary>Whether the drawing commands can run: not while Auto Nest works on the nest.</summary>
|
||||
public bool CanEditDrawings => !Canvas.EditsLocked;
|
||||
|
||||
/// <summary>Whether Hide Fully Nested Drawings is on.</summary>
|
||||
public bool HidesFullyNestedDrawings
|
||||
{
|
||||
get => HideNestedButton.IsChecked == true;
|
||||
set => HideNestedButton.IsChecked = value;
|
||||
}
|
||||
|
||||
private static Drawing DrawingAt(object source) =>
|
||||
(source as Visual)?.FindAncestorOfType<ListBoxItem>(includeSelf: true)?.DataContext is DrawingListItem item
|
||||
? item.Drawing
|
||||
: null;
|
||||
|
||||
/// <summary>Refreshes the list shortly, once however many parts change before then.</summary>
|
||||
private void ScheduleDrawingListRefresh()
|
||||
{
|
||||
if (!Dispatcher.UIThread.CheckAccess())
|
||||
{
|
||||
Dispatcher.UIThread.Post(ScheduleDrawingListRefresh);
|
||||
return;
|
||||
}
|
||||
drawingListTimer.Stop();
|
||||
drawingListTimer.Start();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<ScrollViewer>();
|
||||
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<Part> e) => ScheduleDrawingListRefresh();
|
||||
|
||||
private void OnShownPlatePartRemoved(object sender, ItemRemovedEventArgs<Part> 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<MenuItem>())
|
||||
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}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// (<paramref name="endTool"/>), which may be placing one of them.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>The drawing menu's Delete: confirms, then deletes the drawing and its parts.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>The drawing menu's Remove Unused Drawings: confirms, then removes them.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -40,16 +40,63 @@
|
||||
</Panel>
|
||||
</TabItem>
|
||||
<TabItem Header="Drawings" FontSize="14" MinHeight="34">
|
||||
<DataGrid x:Name="DrawingGrid" x:DataType="local:DrawingRow" IsReadOnly="True"
|
||||
SelectionMode="Single"
|
||||
FontSize="13" AutoGenerateColumns="False"
|
||||
GridLinesVisibility="Horizontal" CanUserSortColumns="True">
|
||||
<DataGrid.Columns>
|
||||
<DataGridTextColumn Header="Drawing" Binding="{Binding Name}" Width="*" />
|
||||
<DataGridTextColumn Header="Nested" Binding="{Binding Nested}" />
|
||||
<DataGridTextColumn Header="Required" Binding="{Binding Required}" />
|
||||
</DataGrid.Columns>
|
||||
</DataGrid>
|
||||
<!-- As the WinForms drawing list and its toolbar (NestView.Drawings.cs): a press picks
|
||||
a drawing up for the plate, a drag drops one part, a double-click opens Drawing
|
||||
Properties. -->
|
||||
<DockPanel>
|
||||
<StackPanel DockPanel.Dock="Top" Orientation="Horizontal" Spacing="4" Margin="4,3">
|
||||
<!-- Its menu lists the shared sort choices (NestView.Drawings.cs). -->
|
||||
<Button x:Name="SortDrawingsButton" Content="Sort ▾" FontSize="12" />
|
||||
<ToggleButton x:Name="HideNestedButton" Content="Hide nested" FontSize="12"
|
||||
ToolTip.Tip="Hide fully nested drawings" />
|
||||
</StackPanel>
|
||||
<Panel>
|
||||
<ListBox x:Name="DrawingList" SelectionMode="Single" Background="White">
|
||||
<ListBox.Styles>
|
||||
<Style Selector="ListBoxItem">
|
||||
<Setter Property="Padding" Value="0" />
|
||||
<Setter Property="BorderThickness" Value="2" />
|
||||
<Setter Property="BorderBrush" Value="Transparent" />
|
||||
</Style>
|
||||
<!-- As WinForms: the selected row is outlined in the highlight color. -->
|
||||
<Style Selector="ListBoxItem:selected /template/ ContentPresenter">
|
||||
<Setter Property="BorderBrush" Value="#0078D7" />
|
||||
</Style>
|
||||
</ListBox.Styles>
|
||||
<ListBox.ContextMenu>
|
||||
<ContextMenu x:Name="DrawingMenu">
|
||||
<MenuItem x:Name="DeleteDrawingMenuItem" Header="Delete" />
|
||||
<Separator x:Name="DrawingMenuSeparator" />
|
||||
<MenuItem x:Name="RemoveUnusedDrawingsMenuItem" Header="Remove Unused Drawings..." />
|
||||
</ContextMenu>
|
||||
</ListBox.ContextMenu>
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate x:DataType="local:DrawingListItem">
|
||||
<Border Background="{Binding Background}" MinHeight="85"
|
||||
BorderBrush="LightGray" BorderThickness="0,0,0,1">
|
||||
<Grid ColumnDefinitions="4,Auto,*">
|
||||
<Border Grid.Column="0" Background="{Binding Bar}" />
|
||||
<Image Grid.Column="1" Source="{Binding Thumbnail}" Width="85" Height="75"
|
||||
Margin="1,5,10,5" VerticalAlignment="Top" />
|
||||
<StackPanel Grid.Column="2" Margin="0,4,4,4">
|
||||
<TextBlock Text="{Binding Name}" FontWeight="Bold" FontSize="13"
|
||||
Foreground="Black" TextTrimming="CharacterEllipsis" />
|
||||
<TextBlock Text="{Binding Quantity}" Foreground="Gray" FontSize="12"
|
||||
Margin="0,3,0,0" IsVisible="{Binding HasQuantity}" />
|
||||
<TextBlock Text="{Binding Size}" Foreground="Gray" FontSize="12" />
|
||||
<TextBlock Text="{Binding Area}" Foreground="Gray" FontSize="12" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
<!-- Shown when Hide nested emptied the list; clicking it shows the drawings again. -->
|
||||
<TextBlock x:Name="DrawingEmptyText" IsVisible="False" Foreground="Gray"
|
||||
TextWrapping="Wrap" TextAlignment="Center" Margin="12"
|
||||
HorizontalAlignment="Stretch" VerticalAlignment="Top" Cursor="Hand" />
|
||||
</Panel>
|
||||
</DockPanel>
|
||||
</TabItem>
|
||||
</TabControl>
|
||||
</Border>
|
||||
|
||||
@@ -12,8 +12,6 @@ using OpenNest.Desktop.Interaction;
|
||||
|
||||
namespace OpenNest.Avalonia
|
||||
{
|
||||
public sealed record DrawingRow(string Name, int Nested, int Required, Drawing Drawing);
|
||||
|
||||
/// <summary>
|
||||
/// One open nest: Plates and Drawings tabs on the left, the plate header and plate view on
|
||||
/// the right. Each tab keeps its own view, so switching nests keeps each one's plate and zoom.
|
||||
@@ -38,14 +36,15 @@ namespace OpenNest.Avalonia
|
||||
plates = new PlateManager(tab.Document.Nest);
|
||||
// Starts watching the last two plates (the tab already put the empty plate there).
|
||||
plates.EnsureSentinel();
|
||||
InitializeDrawingList();
|
||||
Refresh(0);
|
||||
// Adding parts from the drawing list, as the WinForms nest window: a press picks a
|
||||
// drawing up for the plate view, a drag drops one part on the plate.
|
||||
DrawingGrid.AddHandler(PointerPressedEvent, OnDrawingPressed, RoutingStrategies.Tunnel,
|
||||
DrawingList.AddHandler(PointerPressedEvent, OnDrawingPressed, RoutingStrategies.Tunnel,
|
||||
handledEventsToo: true);
|
||||
DrawingGrid.AddHandler(PointerMovedEvent, OnDrawingDragged, RoutingStrategies.Tunnel,
|
||||
DrawingList.AddHandler(PointerMovedEvent, OnDrawingDragged, RoutingStrategies.Tunnel,
|
||||
handledEventsToo: true);
|
||||
DrawingGrid.AddHandler(PointerReleasedEvent, (_, _) => pressedDrawing = null,
|
||||
DrawingList.AddHandler(PointerReleasedEvent, (_, _) => pressedDrawing = null,
|
||||
RoutingStrategies.Tunnel, handledEventsToo: true);
|
||||
Canvas.GotFocus += OnCanvasFocused;
|
||||
DragDrop.SetAllowDrop(Canvas, true);
|
||||
@@ -62,17 +61,13 @@ namespace OpenNest.Avalonia
|
||||
private Drawing pressedDrawing;
|
||||
private Point pressPoint;
|
||||
|
||||
private static Drawing DrawingUnder(PointerEventArgs e) =>
|
||||
(e.Source as Visual)?.FindAncestorOfType<DataGridRow>(includeSelf: true)
|
||||
?.DataContext is DrawingRow row
|
||||
? row.Drawing
|
||||
: null;
|
||||
private static Drawing DrawingUnder(PointerEventArgs e) => DrawingAt(e.Source);
|
||||
|
||||
// As the WinForms list: a single left press picks the drawing up (a drag can start from
|
||||
// it); a double-click puts it down.
|
||||
private void OnDrawingPressed(object sender, PointerPressedEventArgs e)
|
||||
{
|
||||
var point = e.GetCurrentPoint(DrawingGrid);
|
||||
var point = e.GetCurrentPoint(DrawingList);
|
||||
pressPoint = point.Position;
|
||||
pressedDrawing = null;
|
||||
if (!point.Properties.IsLeftButtonPressed)
|
||||
@@ -91,7 +86,7 @@ namespace OpenNest.Avalonia
|
||||
private async void OnDrawingDragged(object sender, PointerEventArgs e)
|
||||
{
|
||||
var drawing = pressedDrawing;
|
||||
var point = e.GetCurrentPoint(DrawingGrid);
|
||||
var point = e.GetCurrentPoint(DrawingList);
|
||||
if (drawing == null || !point.Properties.IsLeftButtonPressed)
|
||||
return;
|
||||
var dx = point.Position.X - pressPoint.X;
|
||||
@@ -126,7 +121,7 @@ namespace OpenNest.Avalonia
|
||||
|
||||
private void OnCanvasFocused(object sender, GotFocusEventArgs e)
|
||||
{
|
||||
var selected = (DrawingGrid.SelectedItem as DrawingRow)?.Drawing;
|
||||
var selected = SelectedDrawing;
|
||||
if (pickup.TakeOnPlateEnter(selected) is { } drawing)
|
||||
Canvas.PlaceDrawing(drawing);
|
||||
}
|
||||
@@ -234,17 +229,11 @@ namespace OpenNest.Avalonia
|
||||
PlateList.SelectedIndex = nest.Plates.Count > 0
|
||||
? System.Math.Clamp(selectIndex, 0, nest.Plates.Count - 1)
|
||||
: -1;
|
||||
// As the WinForms list: the selected drawing stays selected when the list is rebuilt,
|
||||
// matched as WinForms matches it (by name), so it survives an Undo's new objects.
|
||||
var selected = (DrawingGrid.SelectedItem as DrawingRow)?.Drawing;
|
||||
DrawingGrid.ItemsSource = nest.Drawings
|
||||
.Where(d => !d.IsCutOff)
|
||||
.Select(d => new DrawingRow(d.Name, d.Quantity.Nested, d.Quantity.Required, d))
|
||||
.ToList();
|
||||
DrawingGrid.SelectedItem = ((IEnumerable<DrawingRow>)DrawingGrid.ItemsSource)
|
||||
.FirstOrDefault(row => Equals(row.Drawing, selected));
|
||||
shownCounts = CountsText(nest);
|
||||
ShowPlate();
|
||||
// After the plate: each row counts the drawing's parts on the shown plate. The
|
||||
// selected drawing stays selected, matched by name after an Undo's new objects.
|
||||
RefreshDrawingList();
|
||||
}
|
||||
|
||||
// As the WinForms nest window binding a nest: the saved head-lock defaults in the nest's
|
||||
@@ -318,6 +307,7 @@ namespace OpenNest.Avalonia
|
||||
plate?.Parts.Count == keptSelection.PartCount ? keptSelection.Indices : Array.Empty<int>());
|
||||
else
|
||||
Canvas.Plate = plate;
|
||||
WatchShownPlate(plate);
|
||||
PlateLabel.Text = plate == null
|
||||
? "No plates"
|
||||
: $"Plate {index + 1} of {nest.Plates.Count} "
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Runtime.CompilerServices;
|
||||
using Avalonia.Media.Imaging;
|
||||
using OpenNest.Desktop.Rendering;
|
||||
using SkiaSharp;
|
||||
|
||||
namespace OpenNest.Avalonia.Rendering
|
||||
{
|
||||
/// <summary>
|
||||
/// A drawing's picture for the Drawings tab and the Drawing Properties dialog, drawn as the
|
||||
/// WinForms <c>Program.GetImage</c> draws it: the material filled in the drawing's color, the
|
||||
/// etches in the scheme's etch color and the cuts over them in the part outline color, fitted
|
||||
/// inside a 5 pixel margin with the y axis up. Lead-ins are not drawn.
|
||||
/// </summary>
|
||||
internal static class DrawingThumbnail
|
||||
{
|
||||
private sealed record Key(CNC.Program Program, uint Fill, uint Outline, uint Etch, int Width, int Height);
|
||||
|
||||
private sealed record Entry(Key Key, Bitmap Image);
|
||||
|
||||
// One picture per drawing, redrawn when its program, color, the scheme or the size changes.
|
||||
private static readonly ConditionalWeakTable<Drawing, Entry> Cache = new();
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="drawing"/>'s picture <paramref name="width"/> by <paramref name="height"/>
|
||||
/// device-independent pixels, drawn at <paramref name="scaling"/> pixels each; null when
|
||||
/// it has nothing to draw.
|
||||
/// </summary>
|
||||
public static Bitmap For(Drawing drawing, int width, int height, double scaling = 1)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(drawing);
|
||||
if (drawing.Program == null || width <= 0 || height <= 0)
|
||||
return null;
|
||||
|
||||
var palette = SkiaSchemePalette.For(ColorScheme.Default);
|
||||
var fill = SkiaSchemePalette.ToSk(drawing.Color);
|
||||
var pixelWidth = System.Math.Max(1, (int)System.Math.Round(width * scaling));
|
||||
var pixelHeight = System.Math.Max(1, (int)System.Math.Round(height * scaling));
|
||||
var key = new Key(drawing.Program, (uint)fill, (uint)palette.PartOutline(fill), (uint)palette.Etch,
|
||||
pixelWidth, pixelHeight);
|
||||
if (Cache.TryGetValue(drawing, out var entry) && entry.Key == key)
|
||||
return entry.Image;
|
||||
|
||||
var image = Render(drawing.Program, pixelWidth, pixelHeight, scaling, fill, palette.PartOutline(fill), palette.Etch);
|
||||
Cache.AddOrUpdate(drawing, new Entry(key, image));
|
||||
return image;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="drawing"/>'s picture filled in <paramref name="color"/> rather than its
|
||||
/// own, not cached: the Drawing Properties dialog's preview of a color not yet saved.
|
||||
/// </summary>
|
||||
public static Bitmap Preview(Drawing drawing, System.Drawing.Color color, int width, int height, double scaling = 1)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(drawing);
|
||||
if (drawing.Program == null || width <= 0 || height <= 0)
|
||||
return null;
|
||||
var palette = SkiaSchemePalette.For(ColorScheme.Default);
|
||||
var fill = SkiaSchemePalette.ToSk(color);
|
||||
return Render(drawing.Program,
|
||||
System.Math.Max(1, (int)System.Math.Round(width * scaling)),
|
||||
System.Math.Max(1, (int)System.Math.Round(height * scaling)),
|
||||
scaling, fill, palette.PartOutline(fill), palette.Etch);
|
||||
}
|
||||
|
||||
private static Bitmap Render(CNC.Program program, int width, int height, double scaling,
|
||||
SKColor fill, SKColor outline, SKColor etch)
|
||||
{
|
||||
var layers = ProgramGeometry.Layers(program);
|
||||
using var cutPath = SkiaFigures.ToPath(layers.Cut);
|
||||
using var etchPath = SkiaFigures.ToPath(layers.Etch);
|
||||
using var fillPath = SkiaFigures.ToPath(ProgramGeometry.Fill(program));
|
||||
var hasCuts = cutPath.PointCount > 0;
|
||||
var hasEtches = etchPath.PointCount > 0;
|
||||
if (!hasCuts && !hasEtches)
|
||||
return null;
|
||||
|
||||
var bounds = hasCuts ? cutPath.Bounds : etchPath.Bounds;
|
||||
if (hasCuts && hasEtches)
|
||||
bounds = SKRect.Union(bounds, etchPath.Bounds);
|
||||
|
||||
// As WinForms: fit 10 pixels inside the picture (5 each side), centered, y up.
|
||||
var margin = (float)(10 * scaling);
|
||||
var scale = System.Math.Min(
|
||||
(height - margin) / System.Math.Max(bounds.Height, 0.001f),
|
||||
(width - margin) / System.Math.Max(bounds.Width, 0.001f));
|
||||
var matrix = SKMatrix.CreateScale(scale, -scale);
|
||||
matrix = matrix.PostConcat(SKMatrix.CreateTranslation(
|
||||
(width - bounds.Width * scale) / 2 - bounds.Left * scale,
|
||||
(height - bounds.Height * scale) / 2 + bounds.Bottom * scale));
|
||||
cutPath.Transform(matrix);
|
||||
etchPath.Transform(matrix);
|
||||
fillPath.Transform(matrix);
|
||||
|
||||
using var surface = SKSurface.Create(new SKImageInfo(width, height, SKColorType.Bgra8888, SKAlphaType.Premul));
|
||||
var canvas = surface.Canvas;
|
||||
canvas.Clear(SKColors.Transparent);
|
||||
using (var paint = new SKPaint { IsAntialias = true, Style = SKPaintStyle.Fill, Color = fill })
|
||||
canvas.DrawPath(fillPath, paint);
|
||||
using (var paint = new SKPaint
|
||||
{
|
||||
IsAntialias = true,
|
||||
Style = SKPaintStyle.Stroke,
|
||||
Color = etch,
|
||||
StrokeWidth = (float)(1.5 * scaling),
|
||||
})
|
||||
canvas.DrawPath(etchPath, paint);
|
||||
// A coincident cut must remain visible over an etch.
|
||||
using (var paint = new SKPaint
|
||||
{
|
||||
IsAntialias = true,
|
||||
Style = SKPaintStyle.Stroke,
|
||||
Color = outline,
|
||||
StrokeWidth = (float)scaling,
|
||||
})
|
||||
canvas.DrawPath(cutPath, paint);
|
||||
|
||||
using var snapshot = surface.Snapshot();
|
||||
using var png = snapshot.Encode(SKEncodedImageFormat.Png, 100);
|
||||
using var stream = new MemoryStream();
|
||||
png.SaveTo(stream);
|
||||
stream.Position = 0;
|
||||
return new Bitmap(stream);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user