diff --git a/OpenNest.Avalonia/Controls/EditableCombo.cs b/OpenNest.Avalonia/Controls/EditableCombo.cs new file mode 100644 index 00000000..ef03a6cd --- /dev/null +++ b/OpenNest.Avalonia/Controls/EditableCombo.cs @@ -0,0 +1,87 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Avalonia.Controls; +using Avalonia.Layout; + +namespace OpenNest.Avalonia.Controls +{ + /// + /// A text box with a list to pick from, as a WinForms drop-down combo box: any text can be + /// typed, typing offers the items that start with it, and the arrow button lists them all. + /// + internal sealed class EditableCombo : UserControl + { + private readonly AutoCompleteBox box = new() + { + FilterMode = AutoCompleteFilterMode.StartsWith, + MinimumPrefixLength = 1, + MaxDropDownHeight = 320, + HorizontalAlignment = HorizontalAlignment.Stretch, + }; + + private IReadOnlyList items = Array.Empty(); + + public EditableCombo() + { + var open = new Button + { + Content = "▾", + Padding = new global::Avalonia.Thickness(6, 0), + VerticalAlignment = VerticalAlignment.Stretch, + Focusable = false, + }; + open.Click += (_, _) => ShowAll(); + box.DropDownClosed += (_, _) => box.FilterMode = AutoCompleteFilterMode.StartsWith; + box.TextChanged += (_, _) => TextChanged?.Invoke(this, EventArgs.Empty); + box.LostFocus += (_, _) => LostFocusText?.Invoke(this, EventArgs.Empty); + var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") }; + grid.Children.Add(box); + Grid.SetColumn(open, 1); + grid.Children.Add(open); + Content = grid; + } + + /// Raised when the text changes, typed or picked. + public event EventHandler TextChanged; + + /// Raised when the box loses the keyboard, for tidying the typed text. + public event EventHandler LostFocusText; + + public string Text + { + get => box.Text ?? ""; + set => box.Text = value ?? ""; + } + + /// The items listed, in order; the text is kept. + public IReadOnlyList Items + { + get => items; + set + { + var text = Text; + items = (value ?? Array.Empty()).ToList(); + box.ItemsSource = items; + if (Text != text) + Text = text; + } + } + + public bool FocusText() => box.Focus(); + + // Lists every item, whatever is typed, as a WinForms combo box's arrow does. + private void ShowAll() + { + if (items.Count == 0) + return; + box.FilterMode = AutoCompleteFilterMode.None; + var text = Text; + box.ItemsSource = null; + box.ItemsSource = items; + if (Text != text) + Text = text; + box.IsDropDownOpen = true; + } + } +} diff --git a/OpenNest.Avalonia/EditNestDialog.cs b/OpenNest.Avalonia/EditNestDialog.cs new file mode 100644 index 00000000..f6b15ba9 --- /dev/null +++ b/OpenNest.Avalonia/EditNestDialog.cs @@ -0,0 +1,375 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Input; +using Avalonia.Interactivity; +using Avalonia.Layout; +using Avalonia.Media; +using OpenNest.Avalonia.Controls; +using OpenNest.Data; +using OpenNest.Desktop; + +namespace OpenNest.Avalonia +{ + /// What Edit Nest's Done returns: the values to write and whether new nests start from them. + internal sealed record EditNestResult(NestInfoValues Values, bool UseForNewNests); + + /// + /// Nest > Edit, as the WinForms Edit Nest dialog: the Info tab (name, dates, thickness, + /// material and grade, customer, units, status and author), the Defaults tab (the plate + /// size, part and edge spacing and quadrant new plates start from, and whether new nests + /// start from them too) and the Notes tab. The name is read-only unless renaming is + /// allowed (in File mode the name is the file's, set by Save As). Done is enabled while + /// holds; it returns the values (the caller writes + /// the nest as one undo step), Cancel or Esc returns null. + /// + internal sealed class EditNestDialog : Window + { + private readonly TextBox name = new() { Name = "NestName" }; + private readonly TextBox created = new() { Name = "DateCreated", IsReadOnly = true }; + private readonly TextBox modified = new() { Name = "DateLastModified", IsReadOnly = true }; + private readonly EditableCombo thickness = new() { Name = "Thickness" }; + private readonly EditableCombo material = new() { Name = "Material" }; + private readonly EditableCombo grade = new() { Name = "Grade" }; + private readonly TextBox customer = new() { Name = "Customer" }; + private readonly RadioButton inches = new() { Name = "Inches", Content = "Inches", GroupName = "NestUnits" }; + private readonly RadioButton millimeters = new() { Name = "Millimeters", Content = "Millimeters", GroupName = "NestUnits" }; + private readonly ComboBox status = new() { Name = "Status", HorizontalAlignment = HorizontalAlignment.Stretch }; + private readonly TextBox madeBy = new() { Name = "MadeBy" }; + private readonly TextBox size = new() { Name = "Size" }; + private readonly NumericUpDown partSpacing; + private readonly NumericUpDown left; + private readonly NumericUpDown top; + private readonly NumericUpDown right; + private readonly NumericUpDown bottom; + private readonly List unitLabels = new(); + private readonly QuadrantPicker quadrant = new() { Name = "Quadrant", Width = 200, Height = 126 }; + private readonly CheckBox useForNewNests = new() { Name = "UseForNewNests", Content = "Use these defaults for new nests" }; + private readonly TextBox notes = new() + { + Name = "Notes", + AcceptsReturn = true, + TextWrapping = TextWrapping.Wrap, + MinHeight = 300, + }; + private readonly TextBlock releaseOrigin = new() { Name = "ReleaseOrigin", VerticalAlignment = VerticalAlignment.Center }; + private readonly Button done = new() { Name = "Done", Content = "Done", IsDefault = true, MinWidth = 90 }; + private readonly NestInfoValues shown; + private readonly List catalog; + private Units thicknessUnits; + private string gradeMaterialKey = ""; + + private EditNestDialog(NestInfoValues values, IEnumerable materials, bool allowRename, + bool offerNewNestDefaults, string releaseOriginText) + { + shown = values; + catalog = (materials ?? Enumerable.Empty()).ToList(); + Title = "Edit Nest"; + Width = 620; + SizeToContent = SizeToContent.Height; + CanResize = false; + ShowInTaskbar = false; + WindowStartupLocation = WindowStartupLocation.CenterOwner; + + partSpacing = Box("PartSpacing", values.PartSpacing); + left = Box("Left", values.LeftSpacing); + top = Box("Top", values.TopSpacing); + right = Box("Right", values.RightSpacing); + bottom = Box("Bottom", values.BottomSpacing); + + name.Text = values.Name; + name.IsReadOnly = !allowRename; + created.Text = values.DateCreated.ToShortDateString(); + modified.Text = values.DateLastModified.ToShortDateString(); + customer.Text = values.Customer; + madeBy.Text = values.MadeBy; + notes.Text = values.Notes; + size.Text = values.SizeText; + quadrant.Quadrant = values.Quadrant; + useForNewNests.IsVisible = offerNewNestDefaults; + releaseOrigin.Text = releaseOriginText ?? ""; + + status.ItemsSource = NestStatuses.WorkflowOrder; + status.ItemTemplate = new global::Avalonia.Controls.Templates.FuncDataTemplate( + (value, _) => new TextBlock { Text = NestStatuses.DisplayName(value) }); + status.SelectedItem = values.Status; + + // The material list: the posts' materials and the machines' catalog; the grades on + // file follow the material. + material.Items = NestInfoValues.MaterialNames(PostProcessorMaterials.Names, catalog); + material.Text = values.MaterialName; + grade.Text = values.MaterialGrade; + gradeMaterialKey = SharedListNames.Key(values.MaterialName); + grade.Items = NestInfoValues.Grades(catalog, values.MaterialName); + material.TextChanged += (_, _) => RefreshGrades(); + + thicknessUnits = values.Units; + thickness.Items = ThicknessItems(values.Units); + thickness.Text = StandardThicknesses.Format(values.Thickness, values.Units); + // A typed gauge or matching decimal shows as its listed label, as WinForms does. + thickness.LostFocusText += (_, _) => + { + if (StandardThicknesses.TryParse(thickness.Text, thicknessUnits, out var value) + && thickness.Text.Trim().Length > 0) + thickness.Text = StandardThicknesses.Format(value, thicknessUnits); + }; + (values.Units == Units.Millimeters ? millimeters : inches).IsChecked = true; + inches.IsCheckedChanged += (_, _) => UnitsChanged(); + + name.TextChanged += (_, _) => EnableCheck(); + thickness.TextChanged += (_, _) => EnableCheck(); + size.TextChanged += (_, _) => EnableCheck(); + foreach (var box in new[] { partSpacing, left, top, right, bottom }) + box.ValueChanged += (_, _) => EnableCheck(); + + done.Click += (_, _) => Close(new EditNestResult(Values(), useForNewNests.IsVisible && useForNewNests.IsChecked == true)); + var cancel = new Button { Content = "Cancel", IsCancel = true, MinWidth = 90 }; + cancel.Click += (_, _) => Close(null); + + var tabs = new TabControl + { + Items = + { + new TabItem { Header = "Info", Content = InfoTab() }, + new TabItem { Header = "Defaults", Content = DefaultsTab() }, + new TabItem { Header = "Notes", Content = notes }, + }, + }; + var buttons = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto,Auto"), ColumnSpacing = 8 }; + buttons.Children.Add(releaseOrigin); + Grid.SetColumn(done, 1); + buttons.Children.Add(done); + Grid.SetColumn(cancel, 2); + buttons.Children.Add(cancel); + Content = new StackPanel + { + Margin = new Thickness(14), + Spacing = 14, + Children = { tabs, buttons }, + }; + + AddHandler(KeyDownEvent, (_, e) => + { + if (e.Key != Key.Escape) + return; + e.Handled = true; + Close(null); + }, RoutingStrategies.Tunnel); + Opened += (_, _) => + { + if (allowRename) + name.Focus(); + else + thickness.FocusText(); + }; + UpdateUnitLabels(); + EnableCheck(); + } + + /// + /// Shows the dialog on 's info. Returns what Done applies, or null + /// when the user cancelled. + /// + public static Task ShowAsync(Window owner, Nest nest, IEnumerable materials, + bool allowRename = false, bool offerNewNestDefaults = true, string releaseOrigin = null) => + new EditNestDialog(NestInfoValues.FromNest(nest), materials, allowRename, offerNewNestDefaults, releaseOrigin) + .ShowDialog(owner); + + private Control InfoTab() + { + var unitsRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 18, Children = { inches, millimeters } }; + var grid = Rows( + ("Name :", name), + ("Date Created :", created), + ("Date Last Modified :", modified), + ("Thickness :", thickness), + ("Material :", material), + ("Grade :", grade), + ("Customer :", customer), + ("Units :", unitsRow), + ("Status :", status), + ("Made By :", madeBy)); + grid.Margin = new Thickness(6, 10); + return grid; + } + + private Control DefaultsTab() + { + var plate = new Grid + { + ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), + RowDefinitions = new RowDefinitions("Auto,Auto"), + ColumnSpacing = 8, + RowSpacing = 8, + }; + AddRow(plate, 0, "Size :", size, null); + AddRow(plate, 1, "Part Spacing :", partSpacing, UnitLabel()); + + var edges = new Grid + { + ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), + RowDefinitions = new RowDefinitions("Auto,Auto,Auto,Auto"), + ColumnSpacing = 8, + RowSpacing = 8, + }; + AddRow(edges, 0, "Left :", left, UnitLabel()); + AddRow(edges, 1, "Top :", top, UnitLabel()); + AddRow(edges, 2, "Right :", right, UnitLabel()); + AddRow(edges, 3, "Bottom :", bottom, UnitLabel()); + + var leftColumn = new StackPanel { Spacing = 14, Width = 280, Children = { plate, Group("Edge Spacing", edges) } }; + var columns = new StackPanel + { + Orientation = Orientation.Horizontal, + Spacing = 16, + Children = { leftColumn, Group("Quadrant", quadrant) }, + }; + return new StackPanel { Margin = new Thickness(6, 10), Spacing = 14, Children = { columns, useForNewNests } }; + } + + private TextBlock UnitLabel() + { + var label = new TextBlock { VerticalAlignment = VerticalAlignment.Center }; + unitLabels.Add(label); + return label; + } + + // As the WinForms boxes: 0 to 999999, four decimals, a quarter step. + private static NumericUpDown Box(string name, double value) => new() + { + Name = name, + Minimum = (decimal)NestInfoValues.SpacingMinimum, + Maximum = (decimal)System.Math.Max(NestInfoValues.SpacingMaximum, value), + Increment = (decimal)NestInfoValues.SpacingIncrement, + ClipValueToMinMax = true, + FormatString = "0." + new string('0', NestInfoValues.SpacingDecimals), + Value = (decimal)value, + MinWidth = 150, + }; + + private static Grid Rows(params (string Label, Control Field)[] rows) + { + var grid = new Grid + { + ColumnDefinitions = new ColumnDefinitions("Auto,*"), + ColumnSpacing = 10, + RowSpacing = 8, + }; + for (var i = 0; i < rows.Length; i++) + { + grid.RowDefinitions.Add(new RowDefinition(GridLength.Auto)); + AddRow(grid, i, rows[i].Label, rows[i].Field, null); + } + return grid; + } + + private static void AddRow(Grid grid, int row, string label, Control field, TextBlock suffix) + { + var text = new TextBlock + { + Text = label, + VerticalAlignment = VerticalAlignment.Center, + HorizontalAlignment = HorizontalAlignment.Right, + }; + Grid.SetRow(text, row); + grid.Children.Add(text); + Grid.SetRow(field, row); + Grid.SetColumn(field, 1); + grid.Children.Add(field); + if (suffix == null) + return; + Grid.SetRow(suffix, row); + Grid.SetColumn(suffix, 2); + grid.Children.Add(suffix); + } + + // 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, + }, + }, + }; + + private static IReadOnlyList ThicknessItems(Units units) => + StandardThicknesses.Entries.Select(entry => StandardThicknesses.Label(entry, units)).ToList(); + + private Units SelectedUnits => millimeters.IsChecked == true ? Units.Millimeters : Units.Inches; + + // The spacing boxes' unit follows the choice, and the thickness keeps its number while + // its list changes units, as the WinForms thickness box does. + private void UnitsChanged() + { + var units = SelectedUnits; + if (units == thicknessUnits) + return; + var valid = StandardThicknesses.TryParse(thickness.Text, thicknessUnits, out var value); + thicknessUnits = units; + thickness.Items = ThicknessItems(units); + if (valid) + thickness.Text = StandardThicknesses.Format(value, units); + UpdateUnitLabels(); + EnableCheck(); + } + + private void UpdateUnitLabels() + { + var unit = UnitsHelper.GetShortString(SelectedUnits); + foreach (var label in unitLabels) + label.Text = unit; + } + + // A grade belongs to its material, so a new material clears a grade it does not have. + private void RefreshGrades() + { + var grades = NestInfoValues.Grades(catalog, material.Text); + var text = NestInfoValues.GradeAfterMaterialChange(gradeMaterialKey, material.Text, grade.Text, grades); + gradeMaterialKey = SharedListNames.Key(material.Text); + grade.Items = grades; + grade.Text = text; + } + + private static double Number(NumericUpDown box) => (double)(box.Value ?? 0); + + private bool ThicknessValid(out double value) => + StandardThicknesses.TryParse(thickness.Text, thicknessUnits, out value); + + private NestInfoValues Values() + { + ThicknessValid(out var thicknessValue); + return shown with + { + Name = (name.Text ?? "").Trim(), + Thickness = thicknessValue, + MaterialName = material.Text, + MaterialGrade = grade.Text, + Customer = customer.Text ?? "", + Units = SelectedUnits, + Status = status.SelectedItem is NestStatus value ? value : NestStatus.Quote, + MadeBy = madeBy.Text ?? "", + Notes = notes.Text ?? "", + SizeText = size.Text ?? "", + PartSpacing = Number(partSpacing), + LeftSpacing = Number(left), + TopSpacing = Number(top), + RightSpacing = Number(right), + BottomSpacing = Number(bottom), + Quadrant = quadrant.Quadrant, + }; + } + + private void EnableCheck() => done.IsEnabled = Values().CanApply(ThicknessValid(out _)); + } +} diff --git a/OpenNest.Avalonia/MainWindow.Nest.cs b/OpenNest.Avalonia/MainWindow.Nest.cs new file mode 100644 index 00000000..20f32ba4 --- /dev/null +++ b/OpenNest.Avalonia/MainWindow.Nest.cs @@ -0,0 +1,172 @@ +using System; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using Avalonia.Controls; +using Avalonia.Input; +using Avalonia.Interactivity; +using OpenNest.Data; +using OpenNest.Desktop; +using OpenNest.Forms; + +namespace OpenNest.Avalonia +{ + /// + /// Nest > Edit (also a click on the status bar's material label) and Clear Nest, and + /// Tools > Nest Defaults and Save Current Plate as Defaults, as the WinForms main window + /// has them. Each nest edit is one undo step through the shared ; + /// none runs while Auto Nest works on the nest. The nest defaults are saved where they are + /// read: the nest server once it holds them (Database mode), otherwise this PC's file. + /// + public partial class MainWindow + { + private void InitializeNestCommands() + { + ToolTip.SetTip(MaterialStatus, MainStatusText.MaterialToolTip); + // Clear Nest is enabled while there is something to clear, checked as the menu opens + // since parts can be added without a plate change; Save Current Plate as Defaults is + // shown while a nest is open. + if (ClearNestMenuItem.Parent is MenuItem nestMenu) + nestMenu.SubmenuOpened += (_, e) => + { + if (ReferenceEquals(e.Source, nestMenu)) + ClearNestMenuItem.IsEnabled = ActiveView?.Plates.CanClearAll ?? false; + }; + if (SaveCurrentPlateAsDefaultsMenuItem.Parent is MenuItem toolsMenu) + toolsMenu.SubmenuOpened += (_, e) => + { + if (ReferenceEquals(e.Source, toolsMenu)) + SaveCurrentPlateAsDefaultsMenuItem.IsVisible = ActiveView != null; + }; + } + + private async void OnEditNest(object sender, RoutedEventArgs e) => await EditNestAsync(); + + /// + /// Shows Edit Nest on the active nest and writes Done's values as one "Nest Info" step: + /// a changed material or thickness takes the machine's spacing, an untouched trailing + /// sheet follows the new plate defaults and the view's cut-off settings follow the + /// machine. The name is the file's, so it cannot be changed here. + /// + private async Task EditNestAsync() + { + var view = ActiveView; + if (view == null || IsNesting(view.Tab, "editing its info")) + return; + var tab = view.Tab; + var nest = tab.Document.Nest; + var machines = DesktopSettings.Machines; + var shownMadeBy = nest.MadeBy ?? ""; + var result = await EditNestDialog.ShowAsync(this, nest, machines.LoadMaterials()); + if (result == null || !tabs.Tabs.Contains(tab) || IsNesting(tab, "editing its info")) + return; + + try + { + NestCommands.EditNestInfo(nest, view.Plates, result.Values, machines.FindMachine(nest.Machine), + label => tab.Undo.BeginChange(label), + () => machines.ApplyCutOffDefaults(view.PlateView.CutOffSettings, nest)); + } + catch (Exception ex) + { + // The step rolled the nest back to its last recorded state. + ShowNotice($"Could not change the nest info: {ex.Message}"); + view.RefreshInPlace(); + return; + } + // A Made By the user typed is what later new nests start from, as WinForms keeps it. + if (NestInfoValues.MadeByToRemember(shownMadeBy, result.Values.MadeBy) is { } madeBy) + UserSettingsFile.Update(UserSettingsFile.DefaultPath, + settings => settings[NewNestUserSettingsFile.MadeByName] = madeBy); + if (result.UseForNewNests) + await SaveNestDefaultsAsync(() => + NestCommands.NewNestDefaults(nest, machines.LoadSavedNestDefaults(out _))); + // The plate defaults, spacing and units may have changed. + view.RefreshInPlace(); + UpdateStatus(); + } + + private async void OnClearNest(object sender, RoutedEventArgs e) + { + var view = ActiveView; + if (view == null || !CanWrite(view.Tab, "clearing it")) + return; + if (PlateWorkGuard.IsBusy(false, new[] { view.PlateView.Tools.Current })) + { + await ConfirmDialog.ShowAsync(this, "Clear Nest", NestCommands.ClearNestBusyMessage); + return; + } + view.PlateView.Tools.Select(); + if (!await ConfirmDialog.AskAsync(this, "Clear Nest", NestCommands.ClearNestQuestion, "Yes")) + return; + var tab = view.Tab; + if (!tabs.Tabs.Contains(tab) || !CanWrite(tab, "clearing it")) + return; + NestCommands.ClearNest(view.Plates, label => tab.Undo.BeginChange(label)); + view.RefreshInPlace(); + UpdateStatus(); + } + + // Tools > Nest Defaults: read where they are saved; the server's copy when it holds one. + private async void OnNestDefaults(object sender, RoutedEventArgs e) + { + var machines = DesktopSettings.Machines; + var defaults = machines.LoadSavedNestDefaults(out _); + if (DesktopSettings.Shared.TakeOfflineWarning() is { } offline) + await ConfirmDialog.ShowAsync(this, "Shared Settings", offline); + var configs = await DesktopSettings.RefreshMachinesAsync(); + var chosen = await NestDefaultsDialog.ShowAsync(this, defaults, configs, DesktopSettings.Shared.NestDefaultsSource()); + if (chosen != null) + await SaveNestDefaultsAsync(() => chosen); + } + + // As WinForms: the shown plate's size, quadrant and spacing in the nest's units, its + // machine, and the saved common-line usage (a plate holds none). + private async void OnSaveCurrentPlateAsDefaults(object sender, RoutedEventArgs e) + { + var view = ActiveView; + if (view?.PlateView.Plate is not { } plate) + return; + var nest = view.Tab.Document.Nest; + var machines = DesktopSettings.Machines; + await SaveNestDefaultsAsync(() => + PlateCommands.NewNestDefaults(nest, plate, machines.LoadSavedNestDefaults(out _))); + } + + /// Saves the nest defaults, telling the user when they could not be saved. + private async Task SaveNestDefaultsAsync(Func defaults) + { + try + { + DesktopSettings.Machines.SaveNestDefaults(defaults()); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + await ConfirmDialog.ShowAsync(this, "Nest Defaults", + "The nest defaults could not be saved.\n\n" + ex.Message); + } + } + + // A click edits the nest info; a right-click offers it in a menu, as WinForms does + // (its Show in Machine Configuration is not in this app yet). + private async void OnMaterialStatusReleased(object sender, PointerReleasedEventArgs e) + { + if (ActiveView == null) + return; + if (e.InitialPressMouseButton == MouseButton.Left) + { + e.Handled = true; + await EditNestAsync(); + return; + } + if (e.InitialPressMouseButton != MouseButton.Right) + return; + e.Handled = true; + var flyout = new MenuFlyout { Placement = PlacementMode.TopEdgeAlignedLeft }; + var edit = new MenuItem { Header = "Edit Nest..." }; + edit.Click += OnEditNest; + flyout.Items.Add(edit); + flyout.ShowAt(MaterialStatus); + } + } +} diff --git a/OpenNest.Avalonia/MainWindow.axaml b/OpenNest.Avalonia/MainWindow.axaml index f8788efa..6b6967e5 100644 --- a/OpenNest.Avalonia/MainWindow.axaml +++ b/OpenNest.Avalonia/MainWindow.axaml @@ -35,6 +35,8 @@ + + @@ -49,6 +51,7 @@ + @@ -119,6 +122,9 @@ + + @@ -171,7 +177,8 @@ PointerReleased="OnMachineStatusReleased"> - + diff --git a/OpenNest.Avalonia/MainWindow.axaml.cs b/OpenNest.Avalonia/MainWindow.axaml.cs index 4e0040b4..79720384 100644 --- a/OpenNest.Avalonia/MainWindow.axaml.cs +++ b/OpenNest.Avalonia/MainWindow.axaml.cs @@ -119,6 +119,7 @@ namespace OpenNest.Avalonia }); AddViewKeyBindings(); InitializePlateCommands(); + InitializeNestCommands(); // Ctrl+Tab before focus navigation takes the Tab key. AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); // .nest files dropped anywhere on the window, the nest view included, open in tabs. diff --git a/OpenNest.Avalonia/NestDefaultsDialog.cs b/OpenNest.Avalonia/NestDefaultsDialog.cs new file mode 100644 index 00000000..62e51bd4 --- /dev/null +++ b/OpenNest.Avalonia/NestDefaultsDialog.cs @@ -0,0 +1,250 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.Templates; +using Avalonia.Input; +using Avalonia.Interactivity; +using Avalonia.Layout; +using Avalonia.Media; +using OpenNest.Avalonia.Controls; +using OpenNest.Data; +using OpenNest.Desktop; + +namespace OpenNest.Avalonia +{ + /// + /// Tools > Nest Defaults, as the WinForms dialog: the machine, units, plate size, + /// quadrant, part and edge spacing and Auto Nest's common-line usage new nests start + /// from. Switching units converts the values shown. The line under the values says where + /// they are saved; when that is the nest server and it cannot be reached they are shown + /// read-only and cannot be saved. Save returns the defaults, Cancel or Esc returns null. + /// + internal sealed class NestDefaultsDialog : Window + { + private readonly Guid? savedMachineId; + private readonly ComboBox machine = new() { Name = "Machine", MinWidth = 236 }; + private readonly RadioButton inches = new() { Name = "Inches", Content = "Inches", GroupName = "DefaultUnits" }; + private readonly RadioButton millimeters = new() { Name = "Millimeters", Content = "Millimeters", GroupName = "DefaultUnits" }; + private readonly NumericUpDown width = Box("Width", NestDefaultsChoices.SizeMinimum); + private readonly NumericUpDown length = Box("Length", NestDefaultsChoices.SizeMinimum); + private readonly NumericUpDown partSpacing = Box("PartSpacing", NestDefaultsChoices.SpacingMinimum); + private readonly NumericUpDown edgeLeft = Box("EdgeLeft", NestDefaultsChoices.SpacingMinimum); + private readonly NumericUpDown edgeBottom = Box("EdgeBottom", NestDefaultsChoices.SpacingMinimum); + private readonly NumericUpDown edgeRight = Box("EdgeRight", NestDefaultsChoices.SpacingMinimum); + private readonly NumericUpDown edgeTop = Box("EdgeTop", NestDefaultsChoices.SpacingMinimum); + private readonly QuadrantPicker quadrant = new() { Name = "Quadrant", Width = 200, Height = 126 }; + private readonly ComboBox commonLines = new() { Name = "CommonLines", MinWidth = 180 }; + private readonly List unitLabels = new(); + private Units shownUnits; + + private NestDefaultsDialog(NestDefaults defaults, IEnumerable machines, (string Text, bool ReadOnly) source) + { + Title = "Nest Defaults"; + SizeToContent = SizeToContent.WidthAndHeight; + CanResize = false; + ShowInTaskbar = false; + WindowStartupLocation = WindowStartupLocation.CenterOwner; + + savedMachineId = defaults.MachineId; + var sorted = NestDefaultsChoices.SortedMachines(machines); + machine.ItemsSource = sorted; + machine.ItemTemplate = new FuncDataTemplate((m, _) => new TextBlock { Text = m?.Name }); + machine.SelectedItem = MachineSettingsSource.DefaultMachine(defaults, sorted); + machine.IsEnabled = sorted.Count > 0; + + shownUnits = defaults.Units; + (defaults.Units == Units.Millimeters ? millimeters : inches).IsChecked = true; + ShowValues(defaults); + commonLines.ItemsSource = NestDefaultsChoices.CommonLineUsages.Select(c => c.Text).ToList(); + commonLines.SelectedIndex = NestDefaultsChoices.CommonLineIndex(defaults.CommonLineUsage); + ToolTip.SetTip(commonLines, NestDefaultsChoices.CommonLineToolTip); + inches.IsCheckedChanged += (_, _) => UnitsChanged(); + + var save = new Button { Name = "Save", Content = "Save", IsDefault = true, MinWidth = 90, IsEnabled = !source.ReadOnly }; + save.Click += (_, _) => Close(GetDefaults()); + var cancel = new Button { Content = "Cancel", IsCancel = true, MinWidth = 90 }; + cancel.Click += (_, _) => Close(null); + + var general = Grid2(("Machine:", machine), + ("Units:", new StackPanel { Orientation = Orientation.Horizontal, Spacing = 18, Children = { inches, millimeters } })); + var plate = Grid2(("Width:", WithUnit(width)), ("Length:", WithUnit(length))); + var quadrantPanel = new StackPanel + { + Spacing = 6, + Children = { quadrant, new TextBlock { Text = NestDefaultsChoices.QuadrantHint, Foreground = Brushes.Gray } }, + }; + var spacing = new Grid + { + ColumnDefinitions = new ColumnDefinitions("Auto,Auto,24,Auto,Auto,Auto,Auto,Auto"), + RowDefinitions = new RowDefinitions("Auto,Auto,Auto"), + ColumnSpacing = 6, + RowSpacing = 8, + }; + Place(spacing, new TextBlock { Text = "Between parts:" }, 0, 0); + Place(spacing, WithUnit(partSpacing), 1, 0); + Place(spacing, new TextBlock { Text = "Plate edges:" }, 0, 3); + Place(spacing, WithUnit(edgeTop), 0, 5); + Place(spacing, WithUnit(edgeLeft), 1, 4); + Place(spacing, new TextBlock { Text = "Plate", HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center }, 1, 5); + Place(spacing, WithUnit(edgeRight), 1, 6); + Place(spacing, WithUnit(edgeBottom), 2, 5); + var nesting = Grid2(("Common lines:", commonLines)); + + var groups = new[] + { + Group("General", general), Group("Plate Size", plate), Group("Quadrant", quadrantPanel), + Group("Spacing", spacing), Group("Auto Nest", nesting), + }; + // Nothing typed here could be saved, so show the values without inviting edits. + foreach (var group in groups) + group.IsEnabled = !source.ReadOnly; + var top = new StackPanel + { + Orientation = Orientation.Horizontal, + Spacing = 12, + Children = { new StackPanel { Spacing = 12, Width = 360, Children = { groups[0], groups[1] } }, groups[2] }, + }; + var buttons = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto,Auto"), ColumnSpacing = 8 }; + buttons.Children.Add(new TextBlock + { + Name = "Source", + Text = source.Text, + Foreground = Brushes.Gray, + VerticalAlignment = VerticalAlignment.Center, + TextWrapping = TextWrapping.Wrap, + }); + Grid.SetColumn(save, 1); + buttons.Children.Add(save); + Grid.SetColumn(cancel, 2); + buttons.Children.Add(cancel); + Content = new StackPanel + { + Margin = new Thickness(12), + Spacing = 12, + Children = { top, groups[3], groups[4], buttons }, + }; + + AddHandler(KeyDownEvent, (_, e) => + { + if (e.Key != Key.Escape) + return; + e.Handled = true; + Close(null); + }, RoutingStrategies.Tunnel); + } + + /// + /// Shows with to choose from and + /// (where they save, and whether they can now). Returns the + /// defaults to save, or null when the user cancelled. + /// + public static Task ShowAsync(Window owner, NestDefaults defaults, IEnumerable machines, + (string Text, bool ReadOnly) source) => + new NestDefaultsDialog(defaults, machines, source).ShowDialog(owner); + + private Units SelectedUnits => millimeters.IsChecked == true ? Units.Millimeters : Units.Inches; + + private NestDefaults GetDefaults() => ReadValues(SelectedUnits); + + private NestDefaults ReadValues(Units units) => new() + { + Units = units, + Size = new Geometry.Size(Number(width), Number(length)), + Quadrant = quadrant.Quadrant, + PartSpacing = Number(partSpacing), + EdgeSpacing = new Geometry.Spacing(Number(edgeLeft), Number(edgeBottom), Number(edgeRight), Number(edgeTop)), + // With no machines on file there is nothing to choose, so keep the saved choice. + MachineId = NestDefaultsChoices.MachineIdToSave(machine.SelectedItem as MachineConfig, savedMachineId), + CommonLineUsage = NestDefaultsChoices.CommonLineAt(commonLines.SelectedIndex), + }; + + private void ShowValues(NestDefaults defaults) + { + Show(width, defaults.Size.Width); + Show(length, defaults.Size.Length); + Show(partSpacing, defaults.PartSpacing); + Show(edgeLeft, defaults.EdgeSpacing.Left); + Show(edgeBottom, defaults.EdgeSpacing.Bottom); + Show(edgeRight, defaults.EdgeSpacing.Right); + Show(edgeTop, defaults.EdgeSpacing.Top); + quadrant.Quadrant = defaults.Quadrant; + var suffix = defaults.Units == Units.Millimeters ? "mm" : "in"; + foreach (var label in unitLabels) + label.Text = suffix; + } + + // Switching units converts the values shown, so a 48 in plate stays 1219.2 mm. + private void UnitsChanged() + { + var units = SelectedUnits; + if (units == shownUnits) + return; + ShowValues(ReadValues(shownUnits).ConvertedTo(units)); + shownUnits = units; + } + + private static void Show(NumericUpDown box, double value) => + box.Value = (decimal)NestDefaultsChoices.Clamp(value, (double)box.Minimum, (double)box.Maximum); + + private static double Number(NumericUpDown box) => (double)(box.Value ?? box.Minimum); + + private static NumericUpDown Box(string name, double minimum) => new() + { + Name = name, + Minimum = (decimal)minimum, + Maximum = (decimal)NestDefaultsChoices.Maximum, + Increment = 1, + ClipValueToMinMax = true, + FormatString = "0." + new string('0', NestDefaultsChoices.Decimals), + Width = 160, + }; + + private Control WithUnit(NumericUpDown box) + { + var unit = new TextBlock { VerticalAlignment = VerticalAlignment.Center, Text = shownUnits == Units.Millimeters ? "mm" : "in" }; + unitLabels.Add(unit); + return new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, Children = { box, unit } }; + } + + private static void Place(Grid grid, Control control, int row, int column) + { + if (control is TextBlock) + control.VerticalAlignment = VerticalAlignment.Center; + Grid.SetRow(control, row); + Grid.SetColumn(control, column); + grid.Children.Add(control); + } + + private static Grid Grid2(params (string Label, Control Field)[] rows) + { + var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), ColumnSpacing = 10, RowSpacing = 8 }; + for (var i = 0; i < rows.Length; i++) + { + grid.RowDefinitions.Add(new RowDefinition(GridLength.Auto)); + Place(grid, new TextBlock { Text = rows[i].Label }, i, 0); + Place(grid, rows[i].Field, i, 1); + } + 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, + }, + }, + }; + } +}