feat(avalonia): add the engine list, status bar and Nest > Machine

The toolbar's Engine list shows each engine's description beside its
name and its tooltip, and saves the choice through EngineSelection. The
status bar follows the WinForms strip: the tool's name and hint with the
last notice, the location (a click switches between following the mouse
and showing left clicks, saved for both apps), the selection, the
nest's machine (either button lists the machines to assign), material,
plate utilization and the version. Nest > Machine assigns a machine as
one undoable step, refused while Auto Nest works on the nest or the
plate's tool is busy; Auto Nest is enabled only with a plate to nest on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Opus 5.5 committed 2026-11-29 20:10:34 -05:00
1 parent 021af04222
commit ac894bbd9d
5 files changed
+390 -34

No files matched your search

+17
View File
@@ -97,6 +97,23 @@ namespace OpenNest.Avalonia
return notices.Count == 0 ? null : string.Join(" ", notices);
});
/// <summary>
/// Reads the machines again off the UI thread, as the WinForms machine lists read them
/// each time they open; a failed read keeps the last list. Returns the list.
/// </summary>
public static Task<IReadOnlyList<MachineConfig>> RefreshMachinesAsync() => Task.Run(() =>
{
try
{
MachineConfigs = Machines.LoadMachines();
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// The list read at startup (or last time) stays.
}
return MachineConfigs;
});
private static string OneLine(string text) =>
string.Join(" ", text.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries));
}
+307
View File
@@ -0,0 +1,307 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
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;
using OpenNest.Forms;
using OpenNest.Geometry;
namespace OpenNest.Avalonia
{
/// <summary>
/// The toolbar's engine list and the status bar, as the WinForms main window has them: the
/// message (the active tool's name and hint, then the last notice), the cursor location (a
/// click switches between following the mouse and showing the last left click, kept in the
/// user settings both apps share), the selection, the nest's machine (a click or right-click
/// lists the machines to assign, as Nest &gt; Machine does), its material, the plate's
/// utilization and the version. Commands that need a plate, or no running Auto Nest on the
/// nest, are enabled accordingly.
/// </summary>
public partial class MainWindow
{
private static readonly IBrush LocationFollowing = Brushes.Black;
private static readonly IBrush LocationOnClick = Brushes.Gray;
// Each plate view's last shown location, kept while the cursor is elsewhere, as WinForms
// keeps each view's current point.
private readonly ConditionalWeakTable<PlateCanvas, StrongBox<Vector>> locations = new();
private bool locationFollowsMouse = true;
private bool loadingEngines;
// Utilization changes only when parts are added or removed: computed once per plate and count.
private (Plate Plate, int Parts, string Text) utilization;
private void InitializeStatusBar()
{
locationFollowsMouse = MainStatusText.ReadLocationFollowsMouse(
UserSettingsFile.Read(UserSettingsFile.DefaultPath));
LocationStatusText.Foreground = locationFollowsMouse ? LocationFollowing : LocationOnClick;
ToolTip.SetTip(MachineStatus, MainStatusText.MachineToolTip);
VersionStatusText.Text = MainStatusText.Version(MainStatusText.DisplayVersion(typeof(MainWindow).Assembly));
ToolTip.SetTip(VersionStatusText, MainStatusText.VersionToolTip);
InitializeEngineCombo();
}
/// <summary>
/// Every registered engine, with its description beside its name in the open list (the
/// closed box shows the name alone), selecting the saved engine.
/// </summary>
private void InitializeEngineCombo()
{
var names = EngineSelection.UiEngineNames.ToList();
EngineComboBox.ItemTemplate = new FuncDataTemplate<string>((name, _) => EngineRow(name));
EngineComboBox.SelectionBoxItemTemplate = new FuncDataTemplate<string>((name, _) =>
new TextBlock { Text = name, VerticalAlignment = VerticalAlignment.Center });
loadingEngines = true;
try
{
EngineComboBox.ItemsSource = names;
EngineComboBox.SelectedItem = names.FirstOrDefault(n => n == EngineSelection.EngineName)
?? names.FirstOrDefault(n => string.Equals(n, EngineSelection.EngineName, StringComparison.OrdinalIgnoreCase));
}
finally
{
loadingEngines = false;
}
SetEngineToolTip(EngineSelection.EngineName);
}
private static Control EngineRow(string name)
{
var row = new Grid { ColumnDefinitions = new ColumnDefinitions("140,Auto") };
row.Children.Add(new TextBlock { Text = name, VerticalAlignment = VerticalAlignment.Center });
var description = new TextBlock
{
Text = EngineSelection.Description(name),
Foreground = Brushes.Gray,
MaxWidth = 480,
TextTrimming = TextTrimming.CharacterEllipsis,
VerticalAlignment = VerticalAlignment.Center,
};
Grid.SetColumn(description, 1);
row.Children.Add(description);
var tip = EngineSelection.ToolTip(name);
if (!string.IsNullOrEmpty(tip))
ToolTip.SetTip(row, tip);
return row;
}
private void SetEngineToolTip(string name)
{
var tip = EngineSelection.ToolTip(name);
ToolTip.SetTip(EngineComboBox, string.IsNullOrEmpty(tip) ? null : tip);
}
// A user's choice is saved for the next launch (engine-selection.json, both apps).
private void OnEngineSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (loadingEngines || EngineComboBox.SelectedItem is not string name)
return;
EngineSelection.EngineName = name;
SetEngineToolTip(name);
}
private void WatchLocationClicks(NestView view)
{
var canvas = view.PlateView;
canvas.AddHandler(PointerPressedEvent, (_, e) =>
{
if (locationFollowsMouse || !e.GetCurrentPoint(canvas).Properties.IsLeftButtonPressed)
return;
if (canvas.CursorWorld is { } at)
Location(canvas).Value = at;
if (view == ActiveView)
UpdateStatus();
}, RoutingStrategies.Bubble, handledEventsToo: true);
}
private StrongBox<Vector> Location(PlateCanvas canvas) =>
locations.GetValue(canvas, _ => new StrongBox<Vector>(new Vector(0, 0)));
// A left click switches the location between following the mouse and showing clicks.
private void OnLocationStatusReleased(object sender, PointerReleasedEventArgs e)
{
if (e.InitialPressMouseButton != MouseButton.Left)
return;
locationFollowsMouse = !locationFollowsMouse;
UserSettingsFile.Update(UserSettingsFile.DefaultPath,
settings => MainStatusText.WriteLocationFollowsMouse(settings, locationFollowsMouse));
LocationStatusText.Foreground = locationFollowsMouse ? LocationFollowing : LocationOnClick;
UpdateStatus();
}
private void UpdateStatus()
{
var view = ActiveView;
var canvas = view?.PlateView;
UpdateCommandState(view);
if (view == null)
{
Show(Status, notice ?? "Create a new nest or open a .nest file to begin.");
ToolTip.SetTip(Status, null);
Show(LocationStatusText, "");
Show(SelectionStatusText, "");
Show(MachineStatusText, "");
Show(MaterialStatusText, "");
Show(UtilizationStatusText, "");
return;
}
// The active tool's name and hint first, as the WinForms status label shows them.
var message = canvas.Tools.Status;
if (notice != null)
message += " | " + notice;
Show(Status, message);
ToolTip.SetTip(Status, message);
var location = Location(canvas);
if (locationFollowsMouse && canvas.CursorWorld is { } at)
location.Value = at;
Show(LocationStatusText, MainStatusText.Location(location.Value));
var plate = canvas.Plate;
var selected = plate == null
? new List<Part>()
: canvas.Selection.Parts.Where(plate.Parts.Contains).ToList();
Show(SelectionStatusText, Desktop.Interaction.SelectionStatus.Text(selected));
var nest = view.Tab.Document.Nest;
Show(MachineStatusText, MainStatusText.Machine(nest.Machine));
Show(MaterialStatusText, MainStatusText.Material(nest));
Show(UtilizationStatusText, UtilizationText(plate));
}
private string UtilizationText(Plate plate)
{
if (plate == null)
return "";
if (!ReferenceEquals(utilization.Plate, plate) || utilization.Parts != plate.Parts.Count)
utilization = (plate, plate.Parts.Count, MainStatusText.Utilization(plate.Utilization()));
return utilization.Text;
}
// Sets a label's text; a label with none is hidden with its border.
private static void Show(TextBlock label, string text)
{
if (label.Text != text)
label.Text = text;
if (label.Parent is Border border && border.Classes.Contains("status"))
border.IsVisible = !string.IsNullOrEmpty(text);
}
/// <summary>The status bar's labels, for --snapshot's text file.</summary>
private string StatusBarText() =>
string.Join(" ", new[]
{
Status, LocationStatusText, SelectionStatusText, MachineStatusText,
MaterialStatusText, UtilizationStatusText, VersionStatusText,
}
.Select(label => label.Text)
.Where(text => !string.IsNullOrEmpty(text)));
/// <summary>
/// As the WinForms toolbar: Auto Nest needs a plate (while it runs it is the Stop
/// command), and the machine cannot change while Auto Nest works on the nest.
/// </summary>
private void UpdateCommandState(NestView view)
{
var canNest = nesting != null || view?.PlateView.Plate != null;
AutoNestButton.IsEnabled = canNest;
AutoNestMenuItem.IsEnabled = canNest;
var canAssign = view != null && view.Tab != nestingTab;
NestMachineMenuItem.IsEnabled = canAssign;
MachineStatus.IsEnabled = canAssign;
}
// Nest > Machine lists the machines each time it opens.
private async void OnNestMachineMenuOpened(object sender, RoutedEventArgs e)
{
if (!ReferenceEquals(e.Source, NestMachineMenuItem))
return;
var view = ActiveView;
FillMachineItems(NestMachineMenuItem.Items, view, DesktopSettings.MachineConfigs);
// Read again, as the WinForms menu reads them, and shown if the menu is still open.
var machines = await DesktopSettings.RefreshMachinesAsync();
if (NestMachineMenuItem.IsSubMenuOpen && view == ActiveView)
FillMachineItems(NestMachineMenuItem.Items, view, machines);
}
// Either button lists the machines above the label, as Nest > Machine does.
private async void OnMachineStatusReleased(object sender, PointerReleasedEventArgs e)
{
var view = ActiveView;
if (view == null || view.Tab == nestingTab
|| e.InitialPressMouseButton is not (MouseButton.Left or MouseButton.Right))
return;
e.Handled = true;
var flyout = new MenuFlyout { Placement = PlacementMode.TopEdgeAlignedLeft };
FillMachineItems(flyout.Items, view, DesktopSettings.MachineConfigs);
flyout.ShowAt(MachineStatus);
var machines = await DesktopSettings.RefreshMachinesAsync();
if (flyout.IsOpen && view == ActiveView)
FillMachineItems(flyout.Items, view, machines);
}
private void FillMachineItems(ItemCollection items, NestView view, IEnumerable<MachineConfig> machines)
{
items.Clear();
var nest = view?.Tab.Document.Nest;
foreach (var entry in MachineMenu.Items(nest, nest == null ? null : machines))
{
var item = new MenuItem
{
// A name's underscores are shown as typed, not taken as access keys.
Header = entry.Text.Replace("_", "__"),
ToggleType = MenuItemToggleType.CheckBox,
IsChecked = entry.Checked,
IsEnabled = entry.Enabled,
};
if (entry.Machine is { } machine)
item.Click += (_, _) => AssignMachine(view, machine);
items.Add(item);
}
}
/// <summary>
/// Assigns <paramref name="machine"/> to the view's nest as one "Machine" step, as the
/// WinForms Nest &gt; Machine does: its support grid on every sheet, its cut-off settings
/// for the view and its spacing for the nest's defaults and untouched trailing sheet.
/// Refused while Auto Nest works on the nest or the plate's tool is busy.
/// </summary>
private async void AssignMachine(NestView view, MachineConfig machine)
{
var tab = view.Tab;
if (!tabs.Tabs.Contains(tab) || MachineMenu.IsAssigned(tab.Document.Nest, machine))
return;
if (PlateWorkGuard.IsBusy(tab == nestingTab, new[] { view.PlateView.Tools.Current }))
{
await ConfirmDialog.ShowAsync(this, "Machine", PlateWorkGuard.BusyMessage);
return;
}
var nest = tab.Document.Nest;
try
{
using var change = tab.Undo.BeginChange("Machine");
change.MarkChanged();
DesktopSettings.Machines.ApplyMachine(nest, machine, view.Plates, new[] { view.PlateView.CutOffSettings });
change.Complete();
}
catch (Exception ex)
{
// The step rolled the nest back to its last recorded state.
ShowNotice($"Could not assign the machine {machine.Name}: {ex.Message}");
}
// The sheets' support grid and spacing may have changed.
view.RefreshInPlace();
UpdateStatus();
}
}
}
+46 -2
View File
@@ -35,6 +35,10 @@
<MenuItem x:Name="SelectAllMenuItem" Header="Select _All" InputGesture="Ctrl+A" Click="OnSelectAll" />
</MenuItem>
<MenuItem Header="_Nest">
<!-- Rebuilt each time it opens (MainWindow.StatusBar.cs), as the status bar's machine label lists it. -->
<MenuItem x:Name="NestMachineMenuItem" Header="_Machine" SubmenuOpened="OnNestMachineMenuOpened">
<MenuItem Header="(no nest open)" IsEnabled="False" />
</MenuItem>
<MenuItem x:Name="AutoNestMenuItem" Header="_Auto Nest" Click="OnAutoNest" />
</MenuItem>
<MenuItem Header="_Plate">
@@ -78,12 +82,52 @@
<Button Content="Fit" Click="OnFit" />
<Button Content="Previous" Click="OnPreviousPlate" />
<Button Content="Next" Click="OnNextPlate" />
<TextBlock Text="Engine:" VerticalAlignment="Center" Margin="8,0,0,0" />
<!-- Items, templates and the saved selection are set in MainWindow.StatusBar.cs. -->
<ComboBox x:Name="EngineComboBox" Width="150" VerticalAlignment="Center"
SelectionChanged="OnEngineSelectionChanged" />
<Button x:Name="AutoNestButton" Content="Auto Nest" Click="OnAutoNest" />
</StackPanel>
</Border>
<Border DockPanel.Dock="Bottom" Padding="6,3" Background="#F0F0F0">
<TextBlock x:Name="Status" Text="Create a new nest or open a .nest file to begin." />
<!-- As the WinForms status strip: message, location (click: follow the mouse or only clicks)
and selection, then machine (click or right-click: assign one), material, utilization
and the version. Texts and handlers are in MainWindow.StatusBar.cs. -->
<Border DockPanel.Dock="Bottom" Padding="2,1" Background="#F0F0F0">
<Border.Styles>
<Style Selector="Border.status">
<Setter Property="Padding" Value="6,2" />
<Setter Property="BorderBrush" Value="#C8C8C8" />
<Setter Property="BorderThickness" Value="1,0,0,0" />
<Setter Property="Background" Value="Transparent" />
</Style>
</Border.Styles>
<Grid ColumnDefinitions="Auto,Auto,Auto,*,Auto,Auto,Auto,Auto">
<Border Grid.Column="0" Padding="6,2">
<TextBlock x:Name="Status" Text="Create a new nest or open a .nest file to begin."
MaxWidth="640" TextTrimming="CharacterEllipsis" />
</Border>
<Border Grid.Column="1" Classes="status" Cursor="Hand"
PointerReleased="OnLocationStatusReleased">
<TextBlock x:Name="LocationStatusText" />
</Border>
<Border Grid.Column="2" Classes="status">
<TextBlock x:Name="SelectionStatusText" />
</Border>
<Border Grid.Column="4" x:Name="MachineStatus" Classes="status" Cursor="Hand"
PointerReleased="OnMachineStatusReleased">
<TextBlock x:Name="MachineStatusText" />
</Border>
<Border Grid.Column="5" Classes="status">
<TextBlock x:Name="MaterialStatusText" />
</Border>
<Border Grid.Column="6" Classes="status">
<TextBlock x:Name="UtilizationStatusText" />
</Border>
<Border Grid.Column="7" Classes="status">
<TextBlock x:Name="VersionStatusText" Foreground="#6D6D6D" />
</Border>
</Grid>
</Border>
<!-- One tab per open nest, along the bottom of the window. -->
+6 -30
View File
@@ -54,6 +54,8 @@ namespace OpenNest.Avalonia
var engineWarning = EngineSelection.LoadSavedSelection();
if (!string.IsNullOrEmpty(engineWarning))
notice = engineWarning;
// The toolbar's engine list (with the saved engine) and the status bar labels.
InitializeStatusBar();
// Post processors from Posts/ (their materials registered), then the machines,
// reported in the status line as the WinForms app reports them in dialogs.
if (DesktopSettings.LoadPosts(Path.Combine(AppContext.BaseDirectory, "Posts")) is { } postWarning)
@@ -215,6 +217,7 @@ namespace OpenNest.Avalonia
view.PlateView.PlacementOrder = ReadClonePlacementOrder;
RestoreViewToggles(view);
view.ViewChanged += (_, _) => { if (view == ActiveView) UpdateStatus(); };
WatchLocationClicks(view);
views[tab] = view;
WatchHistory(tab);
notice = null;
@@ -297,8 +300,8 @@ namespace OpenNest.Avalonia
using var bitmap = new global::Avalonia.Media.Imaging.RenderTargetBitmap(size);
bitmap.Render(this);
bitmap.Save(path);
// The status line beside the image, so headless checks can read it.
File.WriteAllText(path + ".txt", Status.Text);
// The status bar beside the image, so headless checks can read it.
File.WriteAllText(path + ".txt", StatusBarText());
closeConfirmed = true;
Close();
};
@@ -838,6 +841,7 @@ namespace OpenNest.Avalonia
AutoNestButton.Content = running ? "Stop" : "Auto Nest";
AutoNestMenuItem.Header = running ? "_Stop Auto Nest" : "_Auto Nest";
UpdateUndoMenu();
UpdateStatus();
}
/// <summary>Completes once the machines are read (see <see cref="DesktopSettings.LoadMachinesAsync"/>).</summary>
@@ -947,34 +951,6 @@ namespace OpenNest.Avalonia
}
}
private void UpdateStatus()
{
var view = ActiveView;
var canvas = view?.PlateView;
if (canvas?.Plate == null)
{
var empty = view == null
? "Create a new nest or open a .nest file to begin."
: $"{view.Tab.Name} No plates";
Status.Text = notice ?? empty;
return;
}
// The active tool's name and hint first, as the WinForms status label shows them.
var text = $"{canvas.Tools.Status} {view.Tab.Name} Plate {view.PlateIndex + 1} of {view.PlateCount}"
+ $" Zoom {canvas.Zoom:0.##} px/unit";
if (canvas.CursorWorld is { } at)
text += $" X {at.X:0.000} Y {at.Y:0.000}";
var selected = canvas.Selection.Parts.Where(canvas.Plate.Parts.Contains).ToList();
if (selected.Count > 0)
text += " " + Desktop.Interaction.SelectionStatus.Text(selected);
if (canvas.HoveredPart is { } part)
text += $" Over: {part.BaseDrawing.Name}";
if (notice != null)
text += $" | {notice}";
Status.Text = text;
}
private sealed class Command : System.Windows.Input.ICommand
{
private readonly Action action;
+14 -2
View File
@@ -204,6 +204,10 @@ namespace OpenNest.Avalonia
// Keeps one empty plate at the end of the nest as edits add or remove parts on the last
// two plates, inside the edit's own undo step, as the WinForms nest window's manager does.
private PlateManager plates;
/// <summary>The manager keeping the nest's trailing empty plate, for edits of the plate defaults.</summary>
public PlateManager Plates => plates;
private (IReadOnlyList<int> Indices, int PartCount) keptSelection = (Array.Empty<int>(), -1);
/// <summary>Raised when the shown plate, zoom, hover or selection changes.</summary>
@@ -262,8 +266,16 @@ namespace OpenNest.Avalonia
{
var nest = Tab.Document.Nest;
var counts = CountsText(nest);
if (counts == shownCounts)
return;
if (counts != shownCounts)
RefreshInPlace();
}
/// <summary>
/// Rebuilds both lists keeping the shown plate, its zoom and the selection, after an edit
/// that changed the nest's sheets or settings in place (Nest &gt; Machine).
/// </summary>
public void RefreshInPlace()
{
var shown = Canvas.Plate;
keptSelection = shown != null
? (Canvas.Selection.PartIndices, shown.Parts.Count)