Files
OpenNest/OpenNest.Avalonia/OperationProgressDialog.cs
T
ajandClaude Opus 5.5 044b59463b feat(avalonia): arrange parts and common lines from Plate > Arrange
Plate > Arrange runs the shared Arrange edits on the active nest's
plate, each one undo step under the WinForms label:

- Left, Right, Top, Bottom, Horizontally and Vertically line the
  selection up with its first selected part; Evenly Space Horizontally
  and Vertically spread it; Center Parts centers every part in the work
  area.
- Join Common Line joins the selection at the kerf of the plate's
  cutting parameters, Remove Common Line removes its groups (each says
  why when it cannot), and Cut Common Lines Twice is a checked toggle
  showing the plate's setting.
- Expand Spacing and Fix Spacing search on a worker behind a modal
  Cancel window (OperationProgressDialog, the WinForms
  OperationProgressForm's rules): it appears once a run outlasts
  300 ms, Cancel, Escape and the close box only request cancellation,
  and it closes once the worker stops. The plate takes no edits until
  then. Expand needs two selected parts; while Auto Nest works on the
  nest both say to finish it first. Their result shows in the status
  bar.

A right click released on a selected part in Select opens a menu with
Join and Remove Common Line, enabled as in WinForms. While Auto Nest
works on the nest the other Arrange commands are disabled, as the
WinForms modal progress window keeps them out of reach.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 20:11:35 -05:00

133 lines
5.2 KiB
C#

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Threading;
using OpenNest.Forms;
namespace OpenNest.Avalonia
{
/// <summary>
/// The small "working" window with a Cancel button for a long synchronous plate command run on
/// a worker, as the WinForms OperationProgressForm (rules in <see cref="OperationProgress"/>).
/// Cancel, Escape and the close box only request cancellation: the window stays open showing
/// "Canceling..." until the worker has actually stopped, so the caller never continues while it
/// is still running.
/// </summary>
internal sealed class OperationProgressDialog : Window
{
private readonly Task task;
private readonly CancellationTokenSource cts;
private readonly Stopwatch stopwatch = Stopwatch.StartNew();
private readonly TextBlock statusText;
private readonly Button cancelButton;
private readonly DispatcherTimer elapsedTimer;
private bool finished;
private OperationProgressDialog(string title, string message, Task task, CancellationTokenSource cts)
{
this.task = task;
this.cts = cts;
Title = title;
Width = 380;
SizeToContent = SizeToContent.Height;
CanResize = false;
ShowInTaskbar = false;
WindowStartupLocation = WindowStartupLocation.CenterOwner;
statusText = new TextBlock();
// IsCancel makes Escape click it; the click only requests cancellation.
cancelButton = new Button { Content = "Cancel", IsCancel = true, HorizontalAlignment = HorizontalAlignment.Right };
cancelButton.Click += (_, _) => RequestCancel();
var panel = new StackPanel { Margin = new Thickness(12), Spacing = 8 };
panel.Children.Add(new TextBlock { Text = message, TextTrimming = global::Avalonia.Media.TextTrimming.CharacterEllipsis });
panel.Children.Add(new ProgressBar { IsIndeterminate = true, Height = 18 });
panel.Children.Add(statusText);
panel.Children.Add(cancelButton);
Content = panel;
elapsedTimer = new DispatcherTimer { Interval = OperationProgress.StatusInterval };
elapsedTimer.Tick += (_, _) => UpdateStatus();
UpdateStatus();
Opened += (_, _) =>
{
elapsedTimer.Start();
cancelButton.Focus();
task.ContinueWith(_ => Dispatcher.UIThread.Post(Finish), CancellationToken.None,
TaskContinuationOptions.None, TaskScheduler.Default);
};
Closing += (_, e) =>
{
if (finished)
return;
e.Cancel = true;
RequestCancel();
};
Closed += (_, _) => elapsedTimer.Stop();
}
/// <summary>
/// Runs <paramref name="work"/> on a worker and returns its result, rethrowing its
/// exception. The caller's window is blocked for up to <paramref name="showDelay"/>, as the
/// WinForms window blocks; a run still going then shows this window modally over
/// <paramref name="owner"/>, whose Cancel requests cancellation through the token passed to
/// <paramref name="work"/>. Completes only once the worker has stopped, whether or not it
/// honored the request.
/// </summary>
public static async Task<T> RunAsync<T>(Window owner, string title, string message,
Func<CancellationToken, T> work, TimeSpan? showDelay = null)
{
ArgumentNullException.ThrowIfNull(work);
using var cts = new CancellationTokenSource();
var token = cts.Token;
var task = Task.Run(() => work(token));
if (!OperationProgress.FinishesWithin(task, showDelay ?? OperationProgress.DefaultShowDelay))
{
var dialog = new OperationProgressDialog(title, message, task, cts);
if (owner != null)
await dialog.ShowDialog(owner);
else
{
var closed = new TaskCompletionSource();
dialog.Closed += (_, _) => closed.TrySetResult();
dialog.Show();
await closed.Task;
}
}
// The window closes only after the worker stops. Should it ever return early, stop
// the worker and wait for it rather than continue beside it.
if (!task.IsCompleted)
cts.Cancel();
return await task;
}
private void RequestCancel()
{
if (finished || cts.IsCancellationRequested)
return;
cts.Cancel();
cancelButton.IsEnabled = false;
UpdateStatus();
}
private void Finish()
{
if (finished)
return;
finished = true;
elapsedTimer.Stop();
Close();
}
private void UpdateStatus() =>
statusText.Text = OperationProgress.StatusText(stopwatch.Elapsed, cts.IsCancellationRequested);
}
}