using System;
using System.Collections.Generic;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.VisualTree;
using OpenNest.CNC;
using OpenNest.Data;
using OpenNest.Desktop;
using OpenNest.Desktop.Interaction;
namespace OpenNest.Avalonia
{
///
/// Plate > Simulate Cutting's playback controls, as the WinForms Cut Simulator: play and
/// pause at a speed, restart and end, step by part or cutout (and by move with the arrow
/// keys), scrub, and the time, part, drawing and motion at the playhead. The feeds, pierce,
/// acceleration and etch choice retime the cut as they change and are remembered on close.
/// Follows the nest's shown plate; the shared holds the
/// playhead and the plate view draws it.
///
internal sealed class CutSimulatorWindow : Window
{
private const int TrackResolution = 1000;
private readonly NestView view;
private readonly CutSimulationPlayback playback = new();
private readonly DispatcherTimer timer = new() { Interval = TimeSpan.FromMilliseconds(30) };
private readonly Button playButton;
private readonly ComboBox speedBox;
private readonly Slider track;
private readonly TextBlock timeText, partText, drawingText, motionText;
private readonly NumberField feed, holeFeed, rapid, pierce;
private readonly MachineConfig machine;
private readonly CheckBox skipEtch;
private readonly Units units;
private Plate plate;
private bool updatingTrack;
private bool rebuildQueued;
/// The nest's machine, whose acceleration times the moves, or null for full speed.
public CutSimulatorWindow(NestView view, MachineConfig machine)
{
this.view = view;
this.machine = machine;
units = view.Tab.Document.Nest.Units;
Title = "Cut Simulator";
SizeToContent = SizeToContent.WidthAndHeight;
CanResize = false;
ShowInTaskbar = false;
WindowStartupLocation = WindowStartupLocation.Manual;
var restart = TransportButton("⏮", 44, 15, "Restart");
playButton = TransportButton("▶", 80, 22, "Play / pause (Space)");
playButton.Name = "Play";
var end = TransportButton("⏭", 44, 15, "Jump to end");
speedBox = new ComboBox { Name = "Speed", Width = 80, VerticalAlignment = VerticalAlignment.Center };
foreach (var speed in CutSimulationPlayback.Speeds)
speedBox.Items.Add(CutSimulationStatus.SpeedText(speed));
speedBox.SelectedIndex = CutSimulationPlayback.DefaultSpeedIndex;
var transport = Row(restart, playButton, end,
new TextBlock { Text = "Speed", VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(12, 0, 0, 0) },
speedBox);
var previousPart = JumpButton("◀◀ Part", "Back to the start of this part, or the part before (Page Up)");
var previousContour = JumpButton("◀ Cutout", "Back to the start of this cutout or perimeter, or the one before (Ctrl+Left)");
var nextContour = JumpButton("Cutout ▶", "Next cutout or perimeter (Ctrl+Right)");
var nextPart = JumpButton("Part ▶▶", "Next part (Page Down)");
var jumps = Row(previousPart, previousContour, nextContour, nextPart);
track = new Slider { Name = "Track", Minimum = 0, Maximum = TrackResolution, Focusable = true };
ToolTip.SetTip(track, "Drag to scrub through the cut (Left/Right step one move)");
timeText = new TextBlock { Name = "Time", FontWeight = FontWeight.Bold };
partText = new TextBlock { Name = "Part" };
// Two lines for long drawing names; longer ones trim and show in full on hover.
drawingText = new TextBlock
{
Name = "Drawing",
TextWrapping = TextWrapping.Wrap,
TextTrimming = TextTrimming.CharacterEllipsis,
MaxLines = 2,
};
motionText = new TextBlock { Name = "Motion" };
var status = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), ColumnSpacing = 8, RowSpacing = 2 };
AddStatusRow(status, 0, "Time", timeText);
AddStatusRow(status, 1, "Part", partText);
AddStatusRow(status, 2, "Drawing", drawingText);
AddStatusRow(status, 3, "Motion", motionText);
// Fixed width so changing text never resizes the window.
status.Width = 400;
status.HorizontalAlignment = HorizontalAlignment.Left;
var saved = CutTimeSettingsFile.Read();
var loaded = saved.ToCutParameters(units, machine);
var rate = UnitsHelper.GetShortTimeUnitPair(units);
feed = new NumberField("Feed", loaded.Feedrate, CutTimeEntry.MinimumRate, CutTimeEntry.MaximumRate, 0, rate, 130);
holeFeed = new NumberField("HoleFeed", loaded.HoleFeedrate ?? loaded.Feedrate, CutTimeEntry.MinimumRate,
CutTimeEntry.MaximumRate, 0, rate, 130);
rapid = new NumberField("Rapid", loaded.RapidTravelRate, CutTimeEntry.MinimumRate, CutTimeEntry.MaximumRate, 0, rate, 130);
pierce = new NumberField("Pierce", loaded.PierceTime.TotalSeconds, 0, CutTimeEntry.SimulatorMaximumPierce, 1, "s", 130);
ToolTip.SetTip(feed.Box, "Feed for outside contours and cut-offs (the CI Fiber post's exterior, L4)");
ToolTip.SetTip(holeFeed.Box, "Feed for holes and other interior contours (the CI Fiber post's interior, L2)");
var rates = new Grid
{
ColumnDefinitions = new ColumnDefinitions("Auto,Auto,Auto,Auto"),
RowDefinitions = new RowDefinitions("Auto,Auto"),
ColumnSpacing = 8,
RowSpacing = 6,
};
AddRate(rates, 0, 0, "Outside feed", feed);
AddRate(rates, 0, 2, "Hole feed", holeFeed);
AddRate(rates, 1, 0, "Rapid", rapid);
AddRate(rates, 1, 2, "Pierce", pierce);
var machineText = new TextBlock
{
Name = "Machine",
Text = machine?.Name ?? "None (full speed)",
VerticalAlignment = VerticalAlignment.Center,
};
ToolTip.SetTip(machineText, "The nest's machine, whose acceleration limits time the moves (Nest > Machine)");
skipEtch = new CheckBox
{
Name = "SkipEtch",
Content = "Skip etch-only contours",
IsChecked = loaded.SkipScribe,
Margin = new Thickness(12, 0, 0, 0),
};
ToolTip.SetTip(skipEtch, "Leave out contours that only etch, as the CI Fiber post does by default");
var motion = Row(new TextBlock { Text = "Machine", VerticalAlignment = VerticalAlignment.Center },
machineText, skipEtch);
var layout = new StackPanel { Margin = new Thickness(10), Spacing = 8 };
foreach (var part in new Control[] { transport, jumps, track, status, rates, motion })
layout.Children.Add(part);
Content = layout;
restart.Click += (_, _) => playback.Restart();
end.Click += (_, _) => playback.End();
playButton.Click += (_, _) => TogglePlay();
previousPart.Click += (_, _) => playback.PreviousPart();
previousContour.Click += (_, _) => playback.PreviousContour();
nextContour.Click += (_, _) => playback.NextContour();
nextPart.Click += (_, _) => playback.NextPart();
speedBox.SelectionChanged += (_, _) => ApplySpeed();
track.ValueChanged += (_, _) =>
{
if (!updatingTrack)
playback.Seek(track.Value / TrackResolution);
};
foreach (var field in new[] { feed, holeFeed, rapid, pierce })
field.Changed += (_, _) => Rebuild();
skipEtch.IsCheckedChanged += (_, _) => Rebuild();
timer.Tick += (_, _) => playback.Advance();
playback.Changed += OnPlaybackChanged;
ApplySpeed();
view.PlateView.CutSimulation = playback;
view.ViewChanged += OnViewChanged;
AttachPlate(view.PlateView.Plate);
Rebuild();
OnPlaybackChanged(this, EventArgs.Empty);
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
Opened += (_, _) => PlaceAtOwnerCorner();
Closed += OnClosed;
}
/// The parameters the boxes time the cut with.
private CutParameters GetCutParameters() =>
CutTimeEntry.Parameters(feed.Value, holeFeed.Value, rapid.Value, pierce.Value, skipEtch.IsChecked == true,
units, machine);
private void ApplySpeed()
{
var index = System.Math.Clamp(speedBox.SelectedIndex, 0, CutSimulationPlayback.Speeds.Count - 1);
playback.Speed = CutSimulationPlayback.Speeds[index];
}
private void Rebuild()
{
if (plate == null)
{
playback.Clear();
return;
}
playback.Load(CutSimulation.Build(plate, GetCutParameters()));
}
// Parts may have moved since the timeline was built; moves raise no plate event.
private void TogglePlay() => playback.TogglePlay(Rebuild);
private void AttachPlate(Plate value)
{
if (plate != null)
{
plate.PartAdded -= OnPartsChanged;
plate.PartRemoved -= OnPartsChanged;
plate.PartsReordered -= OnPartsChanged;
}
plate = value;
if (plate != null)
{
plate.PartAdded += OnPartsChanged;
plate.PartRemoved += OnPartsChanged;
plate.PartsReordered += OnPartsChanged;
}
}
// A fill adds parts one at a time; rebuild once after the batch.
private void OnPartsChanged(object sender, EventArgs e)
{
if (rebuildQueued)
return;
rebuildQueued = true;
Dispatcher.UIThread.Post(() =>
{
rebuildQueued = false;
if (IsVisible)
Rebuild();
});
}
// The header's plate buttons stay live: the simulation follows the shown plate.
private void OnViewChanged(object sender, EventArgs e)
{
if (ReferenceEquals(view.PlateView.Plate, plate))
return;
AttachPlate(view.PlateView.Plate);
playback.Pause();
playback.Clear();
Rebuild();
}
private void OnPlaybackChanged(object sender, EventArgs e)
{
timer.IsEnabled = playback.IsPlaying;
playButton.Content = playback.IsPlaying ? "⏸" : "▶";
var status = CutSimulationStatus.For(playback, plate, units);
timeText.Text = status.Time;
partText.Text = status.Part;
drawingText.Text = status.Drawing;
ToolTip.SetTip(drawingText, string.IsNullOrEmpty(status.Drawing) ? null : status.Drawing);
motionText.Text = status.Motion;
updatingTrack = true;
track.Value = playback.Simulation is { Steps.Count: > 0 }
? System.Math.Round(TrackResolution * playback.Progress)
: 0;
updatingTrack = false;
view.PlateView.InvalidateVisual();
}
// As the WinForms simulator, while no number or list box has the keyboard: Escape
// closes, Space plays or pauses, Ctrl+arrows step cutouts, Page Up/Down parts, arrows
// moves and Home restarts.
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
if (FocusManager?.GetFocusedElement() is Visual focused && TakesKeys(focused))
return;
Action action = (e.Key, e.KeyModifiers) switch
{
(Key.Escape, KeyModifiers.None) => Close,
(Key.Space, KeyModifiers.None) => TogglePlay,
(Key.Right, KeyModifiers.Control) => playback.NextContour,
(Key.Left, KeyModifiers.Control) => playback.PreviousContour,
(Key.PageDown, KeyModifiers.None) => playback.NextPart,
(Key.PageUp, KeyModifiers.None) => playback.PreviousPart,
(Key.Right, KeyModifiers.None) => () => playback.StepMove(1),
(Key.Left, KeyModifiers.None) => () => playback.StepMove(-1),
(Key.Home, KeyModifiers.None) => playback.Restart,
_ => null,
};
if (action == null)
return;
e.Handled = true;
action();
}
private static bool TakesKeys(Visual focused)
{
for (var visual = focused; visual != null; visual = visual.GetVisualParent())
{
if (visual is NumericUpDown or ComboBox)
return true;
}
return false;
}
// Near the owner's bottom-right corner, over the plate, as WinForms places it.
private void PlaceAtOwnerCorner()
{
if (Owner is not Window owner)
return;
var scale = owner.DesktopScaling;
var corner = owner.PointToScreen(new Point(owner.ClientSize.Width, owner.ClientSize.Height));
var width = (int)(Bounds.Width * scale);
var height = (int)(Bounds.Height * scale);
Position = new PixelPoint(
System.Math.Max(owner.Position.X, corner.X - width - (int)(24 * scale)),
System.Math.Max(owner.Position.Y, corner.Y - height - (int)(48 * scale)));
}
private void OnClosed(object sender, EventArgs e)
{
CutTimeSettingsFile.Save(GetCutParameters());
timer.Stop();
playback.Changed -= OnPlaybackChanged;
playback.Clear();
view.ViewChanged -= OnViewChanged;
AttachPlate(null);
view.PlateView.CutSimulation = null;
}
private static Button TransportButton(string glyph, double width, double fontSize, string tip)
{
var button = new Button
{
Content = glyph,
Width = width,
Height = 40,
FontSize = fontSize,
HorizontalContentAlignment = HorizontalAlignment.Center,
VerticalContentAlignment = VerticalAlignment.Center,
Padding = new Thickness(0),
};
ToolTip.SetTip(button, tip);
return button;
}
private static Button JumpButton(string text, string tip)
{
var button = new Button { Content = text, MinWidth = 80, HorizontalContentAlignment = HorizontalAlignment.Center };
ToolTip.SetTip(button, tip);
return button;
}
private static StackPanel Row(params Control[] controls)
{
var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6 };
foreach (var control in controls)
row.Children.Add(control);
return row;
}
private static void AddStatusRow(Grid grid, int row, string caption, TextBlock value)
{
grid.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
var label = new TextBlock { Text = caption, Foreground = Brushes.Gray };
Grid.SetRow(label, row);
grid.Children.Add(label);
Grid.SetRow(value, row);
Grid.SetColumn(value, 1);
grid.Children.Add(value);
}
private static void AddRate(Grid grid, int row, int column, string caption, NumberField field)
{
var label = new TextBlock { Text = caption, VerticalAlignment = VerticalAlignment.Center };
Grid.SetRow(label, row);
Grid.SetColumn(label, column);
grid.Children.Add(label);
Grid.SetRow(field.View, row);
Grid.SetColumn(field.View, column + 1);
grid.Children.Add(field.View);
}
}
}